target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
---|---|---|
src/routes.js | onemorerocks/oneMore | import React from 'react';
import { IndexRoute, Route } from 'react-router';
import App from './client/app/App.jsx';
import { homeQuery } from './queries';
import Signup from './client/pages/Signup.jsx';
import Login from './client/pages/LoginPage.jsx';
import TabWrapper from './client/pages/TabWrapper.jsx';
export default (
<Route path="/" component={App} queries={homeQuery}>
<IndexRoute component={TabWrapper} queries={homeQuery} />
<Route path="/signup" component={Signup} />
<Route path="/login" component={Login} />
<Route path="/guys" queries={homeQuery} component={TabWrapper} />
<Route path="/guys/:profileId" queries={homeQuery} component={TabWrapper} />
<Route path="/profile" queries={homeQuery} component={TabWrapper} />
</Route>
);
|
app/src/components/Tag/DeleteModal.js | GetStream/Winds | import React from 'react';
import PropTypes from 'prop-types';
import ReactModal from 'react-modal';
import { deleteTag } from '../../api/tagAPI';
class DeleteModal extends React.Component {
constructor(props) {
super(props);
this.resetState = {
error: false,
submitting: false,
success: false,
};
this.state = { ...this.resetState };
}
closeModal = () => {
this.setState({ ...this.resetState });
this.props.toggleModal();
};
handleSubmit = () => {
this.setState({ submitting: true });
deleteTag(
this.props.dispatch,
this.props.tagId,
() => {
this.setState({ success: true, submitting: false });
setTimeout(() => {
this.props.onDelete();
this.closeModal();
}, 500);
},
() => this.setState({ error: true, submitting: false }),
);
};
render() {
let buttonText = 'DELETE';
if (this.state.submitting) buttonText = 'Deleting...';
else if (this.state.success) buttonText = 'Deleted!';
return (
<ReactModal
className="modal add-new-content-modal"
isOpen={this.props.isOpen}
onRequestClose={() => this.closeModal()}
overlayClassName="modal-overlay"
shouldCloseOnOverlayClick={true}
>
<header>
<h1>Delete Tag</h1>
</header>
<p>Are you sure you want to delete this tag?</p>
<label />
{this.state.error && (
<div className="error-message">
Oops, something went wrong. Please try again later.
</div>
)}
<div className="buttons">
<button
className="btn alert"
disabled={this.state.submitting}
onClick={this.handleSubmit}
>
{buttonText}
</button>
<button className="btn link cancel" onClick={() => this.closeModal()}>
Cancel
</button>
</div>
</ReactModal>
);
}
}
DeleteModal.defaultProps = {
isOpen: false,
};
DeleteModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
toggleModal: PropTypes.func.isRequired,
tagId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
};
export default DeleteModal;
|
src/components/Counter.js | erwaiyang/website-starter-kit | import React from 'react'
import PropTypes from 'prop-types'
const Counter = (props) => {
const {
count, increment, decrement, asyncIncrement,
} = props
return (
<div>
<h2>This is a Counter!</h2>
<span>count: {count}</span>
<button onClick={increment}>PLUS</button>
<button onClick={decrement}>MINUS</button>
<button onClick={asyncIncrement}>ASYNC PLUS</button>
</div>
)
}
Counter.propTypes = {
count: PropTypes.number.isRequired,
increment: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired,
asyncIncrement: PropTypes.func.isRequired,
}
export default Counter
|
demos/demo/src/components/Login/Input.js | FWeinb/cerebral | import React from 'react'
export default function Input ({
fieldType, icon, message, placeholder, showError, value,
onChange, onEnter}) {
const onKeyPress = e => {
if (e.key === 'Enter') {
e.preventDefault()
onEnter(e)
}
}
return (
<p className='control has-icon'>
<input className='input'
type={fieldType}
placeholder={placeholder}
value={value}
onChange={onChange}
onKeyPress={onKeyPress}
/>
{showError && (
<i className='fa fa-warning' />
)}
{showError && (
<span className='help is-danger'>
{message}
</span>
)}
{!showError && (
<i className={icon} />
)}
</p>
)
}
|
js/components/Header/2.js | alaxa27/Lukeat | import React, { Component } from "react";
import {
Container,
Header,
Title,
Content,
Button,
Icon,
Left,
Right,
Body,
Text
} from "native-base";
import styles from "./styles";
class Header2 extends Component {
// eslint-disable-line
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => this.props.navigation.goBack()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Header</Title>
</Body>
<Right>
<Button transparent onPress={() => this.props.navigation.goBack()}>
<Icon name="menu" />
</Button>
</Right>
</Header>
<Content padder>
<Text>
Header with Icon Buttons
</Text>
</Content>
</Container>
);
}
}
export default Header2;
|
src/js/components/icons/base/PlatformPiedPiper.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}-platform-pied-piper`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-pied-piper');
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}><path fillRule="evenodd" d="M0,19.4210526 C2.2736843,19.4210526 4.04210525,18.6631579 4.04210525,18.6631579 C4.04210525,18.6631579 7.0736842,11.0842105 11.368421,11.0842105 C14.6526316,11.0842105 15.1578947,13.6105264 15.1578947,13.6105264 C15.1578947,13.6105264 19.9578947,4.26315788 24,3 C20.2105263,6.03157895 20.7157895,9.31578948 18.9473684,10.831579 C17.1789474,12.3473684 17.1789477,10.8381579 15.1578951,14.375 C10.6105267,14.8802632 9.125,16.3894739 6.06315789,18.1578947 C11.3684206,15.6315794 12.3789474,15.3789474 17.1789474,15.631579 C17.6828892,15.6581022 17.9368421,15.8842105 17.6842105,16.3894737 C16.951256,17.8553827 16.4037001,20.0617486 15.4105263,19.9263158 C9.85263157,19.1684211 6.56842104,20.431579 3.78947367,20.431579 C1.0105263,20.431579 0,19.9263158 0,19.4210526 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'PlatformPiedPiper';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
files/rxjs/2.3.11/rx.lite.compat.js | labsvisual/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 // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
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;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
suportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
function isArguments(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `-0` vs. `+0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var hasProp = {}.hasOwnProperty;
/** @private */
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
/** @private */
var addProperties = Rx.internals.addProperties = function (obj) {
var sources = slice.call(arguments, 1);
for (var i = 0, len = sources.length; i < len; i++) {
var source = sources[i];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
// Collection polyfills
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// 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;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
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) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
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) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
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 {}.toString.call(arg) == arrayClass;
};
}
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
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];
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();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeRecImmediate(scheduler, pair) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair.first, action = pair.second, group = new CompositeDisposable(),
recursiveAction = function (state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.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 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({ first: state, second: 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({ 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, 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({ first: state, second: 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 Error('Periodic scheduling not supported.'); }
var s = state;
var 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); }
function scheduleRelative(state, dueTime, action) {
var dt = normalizeTime(dt);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
if (!item.isCancelled()) {
item.invoke();
}
}
}
}
function scheduleNow(state, action) {
return this.scheduleWithRelativeAndState(state, 0, action);
}
function scheduleRelative(state, dueTime, action) {
var dt = this.now() + Scheduler.normalize(dueTime),
si = new ScheduledItem(this, state, action, dt);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} else {
queue.enqueue(si);
}
return si.disposable;
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
currentScheduler.scheduleRequired = function () { return !queue; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
var scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* 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 = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (exception) {
var notification = new Notification('E');
notification.exception = exception;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchException = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
*
* @param observer Observer object.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) {
return n.accept(observer);
};
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
*
* @static
* @memberOf Observer
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler) {
return new AnonymousObserver(function (x) {
return handler(notificationCreateOnNext(x));
}, function (exception) {
return handler(notificationCreateOnError(exception));
}, function () {
return handler(notificationCreateOnCompleted());
});
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) {
inherits(AbstractObserver, _super);
/**
* Creates a new observer in a non-stopped state.
*
* @constructor
*/
function AbstractObserver() {
this.isStopped = false;
_super.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
*
* @memberOf AbstractObserver
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) {
this.next(value);
}
};
/**
* Notifies the observer that an exception has occurred.
*
* @memberOf AbstractObserver
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (_super) {
inherits(AnonymousObserver, _super);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
_super.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
*
* @example
* 1 - source.subscribe();
* 2 - source.subscribe(observer);
* 3 - source.subscribe(function (x) { console.log(x); });
* 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); });
* 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); });
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
var subscriber = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
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 (err) {
var self = this;
this.queue.push(function () {
self.observer.onError(err);
});
};
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));
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
*
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
*
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe) {
return new AnonymousObservable(subscribe);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next = it.next();
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
*
* @example
* var res = Rx.Observable.fromArray([1,2,3]);
* var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
*
* @example
* var res = Rx.Observable.return(42);
* var res = Rx.Observable.return(42, Rx.Scheduler.timeout);
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @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 = Observable.throwError = function (exception, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(exception);
});
});
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
});
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.catchException(xs, ys, zs);
* 2 - res = Rx.Observable.catchException([xs, ys, zs]);
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchException = Observable['catch'] = function () {
var items = argsOrArray(arguments, 0);
return enumerableFor(items).catchException();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var args = slice.call(arguments);
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
*
* @example
* 1 - concatenated = xs.concat(ys, zs);
* 2 - concatenated = xs.concat([ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
var items = slice.call(arguments, 0);
items.unshift(this);
return observableConcat.apply(this, items);
};
/**
* Concatenates all the observable sequences.
*
* @example
* 1 - res = Rx.Observable.concat(xs, ys, zs);
* 2 - res = Rx.Observable.concat([xs, ys, zs]);
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var sources = argsOrArray(arguments, 0);
return enumerableFor(sources).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatObservable = observableProto.concatAll =function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (observer) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
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;
activeCount === 0 && observer.onCompleted();
}));
return group;
});
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
*
* @example
* 1 - merged = Rx.Observable.merge(xs, ys, zs);
* 2 - merged = Rx.Observable.merge([xs, ys, zs]);
* 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs);
* 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]);
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources;
if (!arguments[0]) {
scheduler = immediateScheduler;
sources = slice.call(arguments, 1);
} else if (arguments[0].now) {
scheduler = arguments[0];
sources = slice.call(arguments, 1);
} else {
scheduler = immediateScheduler;
sources = slice.call(arguments, 0);
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableFromArray(sources, scheduler).mergeObservable();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeObservable = observableProto.mergeAll =function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && observer.onCompleted();
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
group.length === 1 && observer.onCompleted();
}));
return group;
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, observer.onError.bind(observer), function () {
rightSubscription.dispose();
}));
return disposables;
});
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
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();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (observer) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(observer),
other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop)
);
});
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
}
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) {
return zipArray.apply(this, arguments);
}
var parent = this, sources = slice.call(arguments), resultSelector = sources.pop();
sources.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var args = slice.call(arguments, 0),
first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
})(idx);
}
var compositeDisposable = new CompositeDisposable(subscriptions);
compositeDisposable.add(disposableCreate(function () {
for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) {
queues[qIdx] = [];
}
}));
return compositeDisposable;
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
return new AnonymousObservable(this.subscribe.bind(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 (observer) {
return source.subscribe(function (x) {
return x.accept(observer);
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
keySelector || (keySelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (exception) {
observer.onError(exception);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
*
* @example
* var res = observable.do(observer);
* var res = observable.do(onNext);
* var res = observable.do(onNext, onError);
* var res = observable.do(onNext, onError, onCompleted);
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext);
onError = observerOrOnNext.onError.bind(observerOrOnNext);
onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext);
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (!onError) {
observer.onError(err);
} else {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}
}, function () {
if (!onCompleted) {
observer.onCompleted();
} else {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
}
});
});
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
*
* @example
* var res = observable.finallyAction(function () { console.log('sequence ended'; });
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.finallyAction = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
});
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
});
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
*
* @example
* var res = repeated = source.repeat();
* var res = repeated = source.repeat(42);
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchException();
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (observer) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
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 () {
!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);
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.
* @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;
}
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.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* 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} prop The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (prop) {
return this.map(function (x) { return x[prop]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new Error(argumentOutOfRange); }
var source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.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;
}
}
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 RangeError(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) {
observer.onNext(x);
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.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var observable = this;
return new AnonymousObservable(function (observer) {
var i = 0, running = true;
return observable.subscribe(function (x) {
if (running) {
try {
running = predicate.call(thisArg, x, i++, observable);
} catch (e) {
observer.onError(e);
return;
}
if (running) {
observer.onNext(x);
} else {
observer.onCompleted();
}
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
*
* @example
* var res = source.where(function (value) { return value < 10; });
* var res = source.where(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.where = observableProto.filter = function (predicate, thisArg) {
var parent = this;
return new AnonymousObservable(function (observer) {
var count = 0;
return parent.subscribe(function (value) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, value, count++, parent);
} catch (exception) {
observer.onError(exception);
return;
}
if (shouldRun) {
observer.onNext(value);
}
}, observer.onError.bind(observer), observer.onCompleted.bind(observer));
});
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {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 args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
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 args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
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 fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation){
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch(event.type){
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
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;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* 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) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.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) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
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) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} 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) {
if (!subject.isDisposed) {
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 TypeError('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());
}) :
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.
*
* @example
* var res = source.share();
*
* @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.
*
* @example
* var res = source.shareValue(42);
*
* @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 window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, 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, window, scheduler) {
return this.replay(null, bufferSize, window, 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, subject.subscribe.bind(subject));
}
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 count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(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);
});
}
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.
*
* @example
* 1 - res = source.throttle(5000); // 5 seconds
* 2 - res = source.throttle(5000, scheduler);
*
* @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The throttled sequence.
*/
observableProto.throttle = function (dueTime, scheduler) {
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);
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
});
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = function (intervalOrSampler, scheduler) {
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 || (other = observableThrow(new Error('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);
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) {
observer.onCompleted();
}
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(function () {
start();
}, observer.onError.bind(observer), function () { start(); }));
}
return new CompositeDisposable(subscription, delays);
});
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
observer.onNext(q.shift().value);
}
observer.onCompleted();
});
});
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, observer.onError.bind(observer), function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { observer.onNext(next.value); }
}
observer.onCompleted();
});
});
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer));
});
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
});
};
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);
}
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 (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
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) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
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) {
observer.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.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);
}
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);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (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.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
/** @private */
var AutoDetachObserver = (function (_super) {
inherits(AutoDetachObserver, _super);
function AutoDetachObserver(observer) {
_super.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
if (!noError) {
this.dispose();
}
}
};
AutoDetachObserverPrototype.error = function (exn) {
try {
this.observer.onError(exn);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); };
/* @private */
AutoDetachObserverPrototype.disposable = function (value) {
return arguments.length ? this.getDisposable() : setDisposable(value);
};
AutoDetachObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
/** @private */
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
/**
* @private
* @memberOf InnerSubscription
*/
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.exception) {
observer.onError(this.exception);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, _super);
/**
* Creates a subject.
* @constructor
*/
function Subject() {
_super.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
}
addProperties(Subject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (exception) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = exception;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(exception);
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
for (var i = 0, len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
var ex = this.exception,
hv = this.hasValue,
v = this.value;
if (ex) {
observer.onError(ex);
} else if (hv) {
observer.onNext(v);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.value = null;
this.hasValue = false;
this.observers = [];
this.exception = null;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed.call(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var o, i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
hv = this.hasValue;
if (hv) {
for (i = 0, len = os.length; i < len; i++) {
o = os[i];
o.onNext(v);
o.onCompleted();
}
} else {
for (i = 0, len = os.length; i < len; i++) {
os[i].onCompleted();
}
}
this.observers = [];
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.exception = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
}
},
/**
* 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) { 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 AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed.call(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
var ex = this.exception;
if (ex) {
observer.onError(ex);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* @constructor
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.exception = null;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.exception = error;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
function 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.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
var n = this.q.length;
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
n++;
so.onError(this.error);
} else if (this.isStopped) {
n++;
so.onCompleted();
}
so.ensureActive(n);
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_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.call(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
}.call(this)); |
cheesecakes/plugins/settings-manager/admin/src/components/PopUpForm/index.js | strapi/strapi-examples | /**
*
* PopUpForm
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import { map } from 'lodash';
import WithFormSection from 'components/WithFormSection';
import styles from './styles.scss';
/* eslint-disable react/require-default-props */
class PopUpForm extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentWillUnmount() {
if (this.props.resetToggleDefaultConnection) this.props.resetToggleDefaultConnection();
}
render() {
return (
<div className={styles.popUpForm}>
<div className="row">
<div className="col-sm-12">
<div className={styles.padded}>
<div className="row">
{map(this.props.sections, (section) => {
// custom rendering
if (this.props.renderPopUpForm) {
// Need to pass props to use this.props.renderInput from WithFormSection HOC
return this.props.renderPopUpForm(section, this.props, styles);
}
return (
map(section.items, (item, key) => (
this.props.renderInput(item, key)
))
);
})}
</div>
</div>
</div>
</div>
</div>
);
}
}
PopUpForm.propTypes = {
renderInput: PropTypes.func,
renderPopUpForm: PropTypes.oneOfType([
PropTypes.func,
PropTypes.bool,
]),
resetToggleDefaultConnection: PropTypes.func,
sections: PropTypes.array,
};
export default WithFormSection(PopUpForm); // eslint-disable-line new-cap
|
src/shared/components/FunFact/index.js | CharlesMangwa/Chloe | /* @flow */
import React from 'react'
import { Text, View } from 'react-native'
import styles from './styles'
type Props = {
color: string,
fact: string,
}
const FunFact = (props: Props): React$Element<any> => {
const { color, fact } = props
return (
<View style={styles.container}>
<View style={[styles.tile, { backgroundColor: color }]}>
<Text style={styles.questionMark}>?</Text>
</View>
<View style={styles.wrapper}>
<Text style={styles.title}>LE SAVIEZ-VOUS ?</Text>
<Text style={styles.text}>{fact}</Text>
</View>
</View>
)
}
export default FunFact
|
ajax/libs/amazeui-react/1.1.2/amazeui.react.js | AMoo-Miki/cdnjs | /*! Amaze UI React v1.1.2 | by Amaze UI Team | (c) 2016 AllMobilize, Inc. | Licensed under MIT | 2016-07-04T17:22:36+0800 */
(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["AMUIReact"] = factory(require("react"), require("react-dom"));
else
root["AMUIReact"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_22__) {
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);
if (!React) {
throw new Error('AMUIReact requires React.');
}
module.exports = {
VERSION: '1.1.2',
// layout
Grid: __webpack_require__(2),
Col: __webpack_require__(6),
Container: __webpack_require__(7),
AvgGrid: __webpack_require__(8),
// elements
Button: __webpack_require__(9),
ButtonToolbar: __webpack_require__(14),
ButtonCheck: __webpack_require__(15),
ButtonGroup: __webpack_require__(17),
// form related
Form: __webpack_require__(18),
FormGroup: __webpack_require__(19),
FormFile: __webpack_require__(20),
Input: __webpack_require__(21),
UCheck: __webpack_require__(24),
Image: __webpack_require__(25),
Thumbnail: __webpack_require__(26),
Thumbnails: __webpack_require__(27),
Table: __webpack_require__(28),
// Code: require('./Code'),
// Navs
Nav: __webpack_require__(29),
NavItem: __webpack_require__(30),
Breadcrumb: __webpack_require__(32),
Pagination: __webpack_require__(33),
Topbar: __webpack_require__(34),
Tabs: __webpack_require__(36),
CollapsibleNav: __webpack_require__(37),
Article: __webpack_require__(41),
Badge: __webpack_require__(42),
Close: __webpack_require__(43),
Icon: __webpack_require__(23),
List: __webpack_require__(44),
ListItem: __webpack_require__(45),
Panel: __webpack_require__(46),
PanelGroup: __webpack_require__(47),
Progress: __webpack_require__(48),
Alert: __webpack_require__(49),
// DatePicker: require('./DateTimePicker'),
// TimePicker: require('./DateTimePicker'),
DateTimeInput: __webpack_require__(50).DateTimeInput,
DateTimePicker: __webpack_require__(50).DateTimePicker,
Dropdown: __webpack_require__(59),
Modal: __webpack_require__(60),
ModalTrigger: __webpack_require__(64),
Popover: __webpack_require__(66),
PopoverTrigger: __webpack_require__(67),
NProgress: __webpack_require__(68),
ScrollSpy: __webpack_require__(69),
ScrollSpyNav: __webpack_require__(73),
Selected: __webpack_require__(75),
Slider: __webpack_require__(76),
Sticky: __webpack_require__(77),
// widgets
Accordion: __webpack_require__(78),
Divider: __webpack_require__(79),
Footer: __webpack_require__(80),
Gallery: __webpack_require__(81),
GoTop: __webpack_require__(82),
Header: __webpack_require__(83),
ListNews: __webpack_require__(84),
Menu: __webpack_require__(85),
Navbar: __webpack_require__(86),
Titlebar: __webpack_require__(87),
// mixins
mixins: __webpack_require__(88)
};
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ },
/* 2 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Grid = React.createClass({
displayName: 'Grid',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
component: React.PropTypes.node.isRequired,
collapse: React.PropTypes.bool,
fixed: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'g',
component: 'div'
};
},
render: function render() {
var Component = this.props.component;
var classSet = this.getClassSet();
var props = this.props;
// .am-g-fixed
classSet[this.prefixClass('fixed')] = props.fixed;
// .am-g-collapse
classSet[this.prefixClass('collapse')] = props.collapse;
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
}
});
module.exports = Grid;
/***/ },
/* 3 */
/***/ 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;
}
}());
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var constants = __webpack_require__(5);
var nsPrefix = constants.NAMESPACE ? constants.NAMESPACE + '-' : '';
module.exports = {
getClassSet: function getClassSet(ignorePrefix) {
var classNames = {};
// uses `.am-` as prefix if `classPrefix` is not defined
var prefix = nsPrefix;
if (this.props.classPrefix) {
var classPrefix = this.setClassNamespace();
prefix = classPrefix + '-';
// don't return prefix if flag set
!ignorePrefix && (classNames[classPrefix] = true);
}
var amSize = this.props.amSize;
var amStyle = this.props.amStyle;
if (amSize) {
classNames[prefix + amSize] = true;
}
if (amStyle) {
classNames[prefix + amStyle] = true;
}
// add theme className for widgets
if (this.props.theme) {
classNames[prefix + this.props.theme] = true;
}
// states
classNames[constants.CLASSES.active] = this.props.active;
classNames[constants.CLASSES.disabled] = this.props.disabled;
// shape
classNames[constants.CLASSES.radius] = this.props.radius;
classNames[constants.CLASSES.round] = this.props.round;
// clearfix
classNames[constants.CLASSES.cf] = this.props.cf;
// am-divider
if (this.props.classPrefix !== 'divider') {
classNames[constants.CLASSES.divider] = this.props.divider;
}
return classNames;
},
// add namespace to classPrefix
setClassNamespace: function setClassNamespace(classPrefix) {
var prefix = classPrefix || this.props.classPrefix || '';
return nsPrefix + prefix;
},
prefixClass: function prefixClass(subClass) {
return this.setClassNamespace() + '-' + subClass;
}
};
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
var NAMESPACE = 'am';
var setNamespace = function setNamespace(className) {
return (NAMESPACE ? NAMESPACE + '-' : '') + className;
};
module.exports = {
NAMESPACE: NAMESPACE,
CLASSES: {
active: setNamespace('active'),
disabled: setNamespace('disabled'),
round: setNamespace('round'),
radius: setNamespace('radius'),
square: setNamespace('square'),
circle: setNamespace('circle'),
divider: setNamespace('divider'),
cf: setNamespace('cf'),
fl: setNamespace('fl'),
fr: setNamespace('fr')
},
STYLES: {
default: 'default',
primary: 'primary',
secondary: 'secondary',
success: 'success',
warning: 'warning',
danger: 'danger'
},
SIZES: {}
};
/***/ },
/* 6 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Col = React.createClass({
displayName: 'Col',
mixins: [ClassNameMixin],
propTypes: {
sm: React.PropTypes.number,
md: React.PropTypes.number,
lg: React.PropTypes.number,
smOffset: React.PropTypes.number,
mdOffset: React.PropTypes.number,
lgOffset: React.PropTypes.number,
smPush: React.PropTypes.number,
mdPush: React.PropTypes.number,
lgPush: React.PropTypes.number,
smPull: React.PropTypes.number,
mdPull: React.PropTypes.number,
lgPull: React.PropTypes.number,
classPrefix: React.PropTypes.string.isRequired,
component: React.PropTypes.node.isRequired,
end: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'u',
component: 'div'
};
},
render: function render() {
var Component = this.props.component;
var classSet = {};
var props = this.props;
var prefixClass = this.prefixClass;
['sm', 'md', 'lg'].forEach(function (size) {
var prop = size;
if (props[size]) {
classSet[prefixClass(size + '-' + props[prop])] = true;
}
prop = size + 'Offset';
if (props[prop] >= 0) {
classSet[prefixClass(size + '-offset-') + props[prop]] = true;
}
prop = size + 'Push';
if (props[prop] >= 0) {
classSet[prefixClass(size + '-push-') + props[prop]] = true;
}
prop = size + 'Pull';
if (props[prop] >= 0) {
classSet[prefixClass(size + '-pull-') + props[prop]] = true;
}
// `xxResetOrder` prop
// - smResetOrder
// - mdResetOrder
// - lgResetOrder
if (props[size + 'ResetOrder']) {
classSet[prefixClass(size + '-reset-order')] = true;
}
// `xxCentered` prop
// - smCentered
// - mdCentered
// - lgCentered
if (props[size + 'Centered']) {
classSet[prefixClass(size + '-centered')] = true;
}
// `xxUnCentered` prop
// - smUnCentered
// - mdUnCentered
// - lgUnCentered
if (props[size + 'UnCentered']) {
classSet[prefixClass(size + '-uncentered')] = true;
}
});
// `end` prop - end column
classSet[prefixClass('end')] = props.end;
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
}
});
module.exports = Col;
/***/ },
/* 7 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Container = React.createClass({
displayName: 'Container',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
component: React.PropTypes.node.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'container',
component: 'div'
};
},
render: function render() {
var Component = this.props.component;
var classSet = this.getClassSet();
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
}
});
module.exports = Container;
/***/ },
/* 8 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var AvgGrid = React.createClass({
displayName: 'AvgGrid',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
component: React.PropTypes.node,
sm: React.PropTypes.number,
md: React.PropTypes.number,
lg: React.PropTypes.number
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'avg',
component: 'ul'
};
},
render: function render() {
var Component = this.props.component;
var classSet = {};
var prefixClass = this.prefixClass;
var props = this.props;
['sm', 'md', 'lg'].forEach(function (size) {
if (props[size]) {
classSet[prefixClass(size + '-' + props[size])] = true;
}
});
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
}
});
module.exports = AvgGrid;
/***/ },
/* 9 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var omit = __webpack_require__(10);
var Button = React.createClass({
displayName: 'Button',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
active: React.PropTypes.bool,
block: React.PropTypes.bool,
disabled: React.PropTypes.bool,
radius: React.PropTypes.bool,
round: React.PropTypes.bool,
component: React.PropTypes.node,
href: React.PropTypes.string,
target: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'btn',
type: 'button',
amStyle: 'default'
};
},
renderAnchor: function renderAnchor(classSet) {
var Component = this.props.component || 'a';
var href = this.props.href || '#';
var props = omit(this.props, 'type');
return React.createElement(
Component,
_extends({}, props, {
href: href,
className: classNames(this.props.className, classSet),
role: 'button'
}),
this.props.children
);
},
renderButton: function renderButton(classSet) {
var Component = this.props.component || 'button';
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
},
render: function render() {
var classSet = this.getClassSet();
var renderType = this.props.href || this.props.target ? 'renderAnchor' : 'renderButton';
// block button
classSet[this.prefixClass('block')] = this.props.block;
return this[renderType](classSet);
}
});
module.exports = Button;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
/*!
* object.omit <https://github.com/jonschlinkert/object.omit>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var isObject = __webpack_require__(11);
var forOwn = __webpack_require__(12);
module.exports = function omit(obj, keys) {
if (!isObject(obj)) return {};
var keys = [].concat.apply([], [].slice.call(arguments, 1));
var last = keys[keys.length - 1];
var res = {}, fn;
if (typeof last === 'function') {
fn = keys.pop();
}
var isFunction = typeof fn === 'function';
if (!keys.length && !isFunction) {
return obj;
}
forOwn(obj, function (value, key) {
if (keys.indexOf(key) === -1) {
if (!isFunction) {
res[key] = value;
} else if (fn(value, key, obj)) {
res[key] = value;
}
}
});
return res;
};
/***/ },
/* 11 */
/***/ function(module, exports) {
/*!
* is-extendable <https://github.com/jonschlinkert/is-extendable>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
module.exports = function isExtendable(val) {
return typeof val !== 'undefined' && val !== null
&& (typeof val === 'object' || typeof val === 'function');
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
/*!
* for-own <https://github.com/jonschlinkert/for-own>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var forIn = __webpack_require__(13);
var hasOwn = Object.prototype.hasOwnProperty;
module.exports = function forOwn(o, fn, thisArg) {
forIn(o, function(val, key) {
if (hasOwn.call(o, key)) {
return fn.call(thisArg, o[key], key, o);
}
});
};
/***/ },
/* 13 */
/***/ function(module, exports) {
/*!
* for-in <https://github.com/jonschlinkert/for-in>
*
* Copyright (c) 2014-2016, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
module.exports = function forIn(o, fn, thisArg) {
for (var key in o) {
if (fn.call(thisArg, o[key], key, o) === false) {
break;
}
}
};
/***/ },
/* 14 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var ButtonToolbar = React.createClass({
displayName: 'ButtonToolbar',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'btn-toolbar'
};
},
render: function render() {
var classSet = this.getClassSet();
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
}
});
module.exports = ButtonToolbar;
/***/ },
/* 15 */
/***/ 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__(1);
var CSSCore = __webpack_require__(16);
var ClassNameMixin = __webpack_require__(4);
var ButtonGroup = __webpack_require__(17);
var constants = __webpack_require__(5);
var ButtonCheck = React.createClass({
displayName: 'ButtonCheck',
mixins: [ClassNameMixin],
propTypes: {
clickHandler: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
clickHandler: function clickHandler() {}
};
},
handleClick: function handleClick(e) {
var changed = true;
var target = e.target;
var activeClassName = constants.CLASSES.active;
if (target && target.nodeName === 'INPUT') {
var parent = target.parentNode;
if (target.type === 'radio') {
if (target.checked && CSSCore.hasClass(parent, activeClassName)) {
changed = false;
} else {
var siblings = parent.parentNode.children;
// remove siblings activeClassName
for (var i = 0; i < siblings.length; i++) {
siblings[i] !== parent && CSSCore.removeClass(siblings[i], activeClassName);
}
}
}
if (changed) {
CSSCore.toggleClass(parent, activeClassName);
}
}
this.props.clickHandler.call(this);
},
render: function render() {
return React.createElement(
ButtonGroup,
_extends({}, this.props, {
onClick: this.handleClick,
className: this.setClassNamespace('btn-group-check')
}),
this.props.children
);
}
});
module.exports = ButtonCheck;
/***/ },
/* 16 */
/***/ 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.
*
* @via https://github.com/facebook/react/blob/master/src/vendor/core/CSSCore.js
*/
'use strict';
var CSSCore = {
/**
* Adds the class passed in to the element if it doesn't already have it.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
addClass: function addClass(element, className) {
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
},
/**
* Removes the class passed in from the element
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
removeClass: function removeClass(element, className) {
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
},
/**
* Helper to add or remove a class from an element based on a condition.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @param {*} bool condition to whether to add or remove the class
* @return {DOMElement} the element passed in
*/
conditionClass: function conditionClass(element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
},
/**
* Tests whether the element has the class specified.
*
* @param {DOMNode|DOMWindow} element the element to set the class on
* @param {string} className the CSS className
* @return {boolean} true if the element has the class, false if not
*/
hasClass: function hasClass(element, className) {
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
},
toggleClass: function toggleClass(element, className) {
return CSSCore.hasClass(element, className) ? CSSCore.removeClass(element, className) : CSSCore.addClass(element, className);
}
};
module.exports = CSSCore;
/***/ },
/* 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var ButtonGroup = React.createClass({
displayName: 'ButtonGroup',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
stacked: React.PropTypes.bool,
justify: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'btn-group'
};
},
render: function render() {
var classSet = this.getClassSet();
classSet[this.prefixClass('stacked')] = this.props.stacked;
classSet[this.prefixClass('justify')] = this.props.justify;
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
}
});
module.exports = ButtonGroup;
/***/ },
/* 18 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Form = React.createClass({
displayName: 'Form',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
horizontal: React.PropTypes.bool,
inline: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'form'
};
},
render: function render() {
var classSet = this.getClassSet();
classSet[this.prefixClass('horizontal')] = this.props.horizontal;
classSet[this.prefixClass('inline')] = this.props.inline;
return React.createElement(
'form',
_extends({}, this.props, {
className: classNames(classSet, this.props.className)
}),
this.props.children
);
}
});
module.exports = Form;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var FormGroup = React.createClass({
displayName: 'FormGroup',
mixins: [ClassNameMixin],
propTypes: {
validation: React.PropTypes.string,
amSize: React.PropTypes.oneOf(['sm', 'lg']),
hasFeedback: React.PropTypes.bool
},
render: function render() {
var classSet = {};
classSet[this.setClassNamespace('form-group')] = true;
this.props.validation && (classSet[this.setClassNamespace('form-' + this.props.validation)] = true);
classSet[this.setClassNamespace('form-feedback')] = this.props.hasFeedback;
classSet[this.setClassNamespace('form-icon')] = this.props.hasFeedback;
if (this.props.amSize) {
classSet[this.setClassNamespace('form-group-' + this.props.amSize)] = true;
}
return React.createElement(
'div',
{ className: classNames(classSet, this.props.className) },
this.props.children
);
}
});
module.exports = FormGroup;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Button = __webpack_require__(9);
var Input = __webpack_require__(21);
var FormFile = React.createClass({
displayName: 'FormFile',
mixins: [ClassNameMixin],
propTypes: {},
getDefaultProps: function getDefaultProps() {
return {};
},
render: function render() {
return React.createElement(
FormGroup,
{
className: this.setClassNamespace('form-file')
},
React.createElement(Input, { type: 'file', standalone: true })
);
}
});
module.exports = FormFile;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Inputs Components
* @desc includes input, input-group
*/
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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var FormGroup = __webpack_require__(19);
var Button = __webpack_require__(9);
var Icon = __webpack_require__(23);
var constants = __webpack_require__(5);
var Input = React.createClass({
displayName: 'Input',
mixins: [ClassNameMixin],
propTypes: {
type: React.PropTypes.string,
disabled: React.PropTypes.bool,
radius: React.PropTypes.bool,
round: React.PropTypes.bool,
amSize: React.PropTypes.oneOf(['sm', 'lg']),
amStyle: React.PropTypes.string,
validation: React.PropTypes.oneOf(['success', 'warning', 'error']),
label: React.PropTypes.node,
help: React.PropTypes.node,
addonBefore: React.PropTypes.node,
addonAfter: React.PropTypes.node,
btnBefore: React.PropTypes.node,
btnAfter: React.PropTypes.node,
id: React.PropTypes.string,
groupClassName: React.PropTypes.string,
wrapperClassName: React.PropTypes.string,
labelClassName: React.PropTypes.string,
helpClassName: React.PropTypes.string,
icon: React.PropTypes.string,
standalone: React.PropTypes.bool,
inline: React.PropTypes.bool,
hasFeedback: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
type: 'text'
};
},
getFieldDOMNode: function getFieldDOMNode() {
return ReactDOM.findDOMNode(this.refs.field);
},
getValue: function getValue() {
if (this.props.type === 'select' && this.props.multiple) {
return this.getSelectedOptions();
} else {
return this.getFieldDOMNode().value;
}
},
getChecked: function getChecked() {
return this.getFieldDOMNode().checked;
},
getSelectedOptions: function getSelectedOptions() {
var values = [];
var options = this.getFieldDOMNode().getElementsByTagName('option');
options.forEach(function (option) {
if (option.selected) {
var value = option.getAttribute('value') || option.innerHtml;
values.push(value);
}
});
return values;
},
isCheckboxOrRadio: function isCheckboxOrRadio() {
return this.props.type === 'radio' || this.props.type === 'checkbox';
},
isFile: function isFile() {
return this.props.type === 'file';
},
renderInput: function renderInput() {
var input = null;
var fieldClassName = this.isCheckboxOrRadio() || this.isFile() ? '' : this.setClassNamespace('form-field');
var classSet = {};
classSet[constants.CLASSES.round] = this.props.round;
classSet[constants.CLASSES.radius] = this.props.radius;
if (this.props.amSize && !this.props.standalone) {
classSet[this.setClassNamespace('input-' + this.props.amSize)] = true;
}
var classes = classNames(this.props.className, fieldClassName, classSet);
switch (this.props.type) {
case 'select':
input = React.createElement(
'select',
_extends({}, this.props, {
className: classes,
ref: 'field',
key: 'field'
}),
this.props.children
);
break;
case 'textarea':
input = React.createElement('textarea', _extends({}, this.props, {
className: classes,
ref: 'field',
key: 'field'
}));
break;
case 'submit':
case 'reset':
input = React.createElement(Button, _extends({}, this.props, {
component: 'input',
ref: 'field',
key: 'field'
}));
break;
default:
input = React.createElement('input', _extends({}, this.props, {
className: classes,
ref: 'field',
key: 'field'
}));
}
return input;
},
// Input wrapper if wrapperClassName set
renderWrapper: function renderWrapper(children) {
return this.props.wrapperClassName ? React.createElement(
'div',
{
className: this.props.wrapperClassName,
key: 'wrapper'
},
children
) : children;
},
// Wrap block checkbox/radio
renderCheckboxAndRadioWrapper: function renderCheckboxAndRadioWrapper(children) {
// Don't wrap inline checkbox/radio
return this.props.inline ? children : React.createElement(
'div',
{
className: this.setClassNamespace(this.props.type),
key: 'checkboxAndRadioWrapper'
},
children
);
},
renderLabel: function renderLabel(children) {
// label doesn't work with icon
/*if (this.props.icon) {
return null;
}*/
var classSet = {};
if (this.isCheckboxOrRadio()) {
// inline checkbox and radio
classSet[this.setClassNamespace(this.props.type + '-inline')] = this.props.inline;
} else {
// normal form label
classSet[this.setClassNamespace('form-label')] = true;
}
return this.props.label ? React.createElement(
'label',
{
htmlFor: this.props.id,
className: classNames(this.props.labelClassName, classSet),
key: 'label'
},
children,
this.props.label
) : children;
},
renderInputGroup: function renderInputGroup(children) {
var groupPrefix = this.setClassNamespace('input-group');
var addonClassName = groupPrefix + '-label';
var btnClassName = groupPrefix + '-btn';
var addonBefore = this.props.addonBefore ? React.createElement(
'span',
{ className: addonClassName, key: 'addonBefore' },
this.props.addonBefore
) : null;
var addonAfter = this.props.addonAfter ? React.createElement(
'span',
{ className: addonClassName, key: 'addonAfter' },
this.props.addonAfter
) : null;
var btnBefore = this.props.btnBefore ? React.createElement(
'span',
{ className: btnClassName, key: 'btnBefore' },
this.props.btnBefore
) : null;
var btnAfter = this.props.btnAfter ? React.createElement(
'span',
{ className: btnClassName, key: 'btnAfter' },
this.props.btnAfter
) : null;
var classSet = {};
if (this.props.amSize) {
classSet[groupPrefix + '-' + this.props.amSize] = true;
}
if (this.props.amStyle) {
classSet[groupPrefix + '-' + this.props.amStyle] = true;
}
return addonBefore || addonAfter || btnBefore || btnAfter ? React.createElement(
'div',
{
className: classNames(groupPrefix, classSet),
key: 'inputGroup'
},
addonBefore,
btnBefore,
children,
addonAfter,
btnAfter
) : children;
},
// form help
renderHelp: function renderHelp() {
return this.props.help ? React.createElement(
'p',
{
className: classNames(this.setClassNamespace('form-help'), this.props.helpClassName),
key: 'help'
},
this.props.help
) : '';
},
renderIcon: function renderIcon() {
var props = this.props;
var feedbackIcon = {
success: 'check',
warning: 'warning',
error: 'times'
};
var icon = props.icon || props.hasFeedback && props.validation && feedbackIcon[props.validation];
return icon ? React.createElement(Icon, { icon: icon, key: 'icon' }) : null;
},
render: function render() {
// standalone mode
if (this.props.standalone) {
return this.renderInput();
}
// render checkbox and radio, without FormGroup wrapper
if (this.isCheckboxOrRadio()) {
return this.renderWrapper(this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())));
}
var groupClassName = classNames(this.props.type === 'select' ? this.setClassNamespace('form-select') : null, this.props.icon && this.setClassNamespace('form-icon'), this.props.groupClassName);
return React.createElement(
FormGroup,
{
className: groupClassName,
validation: this.props.validation,
amSize: this.props.amSize,
hasFeedback: this.props.hasFeedback
},
[this.renderLabel(), this.renderWrapper(this.renderInputGroup(this.renderInput())), this.renderIcon(), this.renderHelp()]
);
}
});
module.exports = Input;
/***/ },
/* 22 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_22__;
/***/ },
/* 23 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Icon = React.createClass({
displayName: 'Icon',
mixins: [ClassNameMixin],
propTypes: {
amStyle: React.PropTypes.string,
fw: React.PropTypes.bool,
spin: React.PropTypes.bool,
button: React.PropTypes.bool,
size: React.PropTypes.string,
href: React.PropTypes.string,
component: React.PropTypes.node.isRequired,
icon: React.PropTypes.string.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'icon',
component: 'span'
};
},
render: function render() {
var classes = this.getClassSet(true);
var props = this.props;
var Component = props.href ? 'a' : props.component;
var prefixClass = this.prefixClass;
var setClassNamespace = this.setClassNamespace;
// am-icon-[iconName]
classes[prefixClass(props.icon)] = true;
// am-icon-btn
classes[prefixClass('btn')] = props.button;
// button style
props.button && props.amStyle && (classes[setClassNamespace(props.amStyle)] = true);
// am-icon-fw
classes[prefixClass('fw')] = props.fw;
// am-icon-spin
classes[prefixClass('spin')] = props.spin;
return React.createElement(
Component,
_extends({}, props, {
className: classNames(classes, this.props.className)
}),
this.props.children
);
}
});
module.exports = Icon;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* Custom radio/checkbox style
*/
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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Input = __webpack_require__(21);
var Icon = __webpack_require__(23);
var constants = __webpack_require__(5);
var UCheck = React.createClass({
displayName: 'UCheck',
mixins: [ClassNameMixin],
propTypes: {
type: React.PropTypes.oneOf(['radio', 'checkbox']),
disabled: React.PropTypes.bool,
amStyle: React.PropTypes.oneOf(['secondary', 'success', 'warning', 'danger']),
inline: React.PropTypes.bool,
hasFeedback: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
type: 'checkbox'
};
},
render: function render() {
var classSet = {};
classSet[this.setClassNamespace(this.props.type)] = !this.props.inline;
classSet[this.setClassNamespace(this.props.type + '-inline')] = this.props.inline;
if (this.props.amStyle) {
classSet[this.setClassNamespace(this.props.amStyle)] = true;
}
return React.createElement(
'label',
{ className: classNames(this.props.className, classSet) },
React.createElement(Input, _extends({}, this.props, {
ref: 'field',
className: this.setClassNamespace('ucheck-checkbox'),
standalone: true
})),
React.createElement(
'span',
{ className: this.setClassNamespace('ucheck-icons') },
React.createElement(Icon, { icon: 'unchecked' }),
React.createElement(Icon, { icon: 'checked' })
),
this.props.label
);
}
});
module.exports = UCheck;
/***/ },
/* 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var constants = __webpack_require__(5);
var Image = React.createClass({
displayName: 'Image',
mixins: [ClassNameMixin],
propTypes: {
src: React.PropTypes.string.isRequired,
circle: React.PropTypes.bool,
radius: React.PropTypes.bool,
round: React.PropTypes.bool,
responsive: React.PropTypes.bool,
thumbnail: React.PropTypes.bool,
placeholder: React.PropTypes.string,
threshold: React.PropTypes.number,
callback: React.PropTypes.func,
asBgImage: React.PropTypes.bool
},
render: function render() {
var classSet = {};
classSet[constants.CLASSES.radius] = this.props.radius;
classSet[constants.CLASSES.round] = this.props.round;
classSet[constants.CLASSES.circle] = this.props.circle;
classSet[this.setClassNamespace('img-responsive')] = this.props.responsive;
classSet[this.setClassNamespace('img-thumbnail')] = this.props.thumbnail;
return React.createElement('img', _extends({}, this.props, {
className: classNames(this.props.className, classSet)
}));
}
});
module.exports = Image;
/*
TODO:
- srcset/sizes 支持
- http://caniuse.com/#feat=srcset
- http://www.w3.org/html/wg/drafts/html/master/semantics.html#attr-img-srcset
- https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/
- lazyload
- asBackground ?
*/
/*
http://odin.s0.no/web/srcset/polyfill.htm
https://github.com/borismus/srcset-polyfill
https://github.com/JimBobSquarePants/srcset-polyfill
http://www.html5rocks.com/en/mobile/high-dpi/
http://www.html5rocks.com/en/tutorials/responsive/picture-element/
https://ericportis.com/posts/2014/srcset-sizes/
gif 占位符
http://proger.i-forge.net/The_smallest_transparent_pixel/eBQ
http://stackoverflow.com/questions/9126105/blank-image-encoded-as-data-uri
*/
/***/ },
/* 26 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var omit = __webpack_require__(10);
var Thumbnail = React.createClass({
displayName: 'Thumbnail',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
standalone: React.PropTypes.bool,
caption: React.PropTypes.node,
component: React.PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'thumbnail',
component: 'figure'
};
},
renderImg: function renderImg(classes, props) {
props = props || {};
return props.src ? React.createElement('img', _extends({}, props, {
className: classes
})) : null;
},
render: function render() {
var classes = classNames(this.getClassSet(), this.props.className);
if (this.props.standalone) {
return this.renderImg(classes, this.props);
}
var Component = this.props.href ? 'a' : this.props.component;
var imgProps = {
alt: this.props.alt,
src: this.props.src,
width: this.props.width,
height: this.props.height
};
var props = omit(this.props, ['alt', 'src', 'width', 'height']);
var caption = this.props.caption;
return React.createElement(
Component,
_extends({}, props, {
className: classes
}),
this.renderImg(null, imgProps),
caption || this.props.children ? React.createElement(
Thumbnail.Caption,
{
component: typeof caption === 'string' ? 'figcaption' : 'div'
},
this.props.caption || this.props.children
) : null
);
}
});
Thumbnail.Caption = React.createClass({
displayName: 'Caption',
mixins: [ClassNameMixin],
propTypes: {
component: React.PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
component: 'div'
};
},
render: function render() {
var Component = this.props.component;
var classes = classNames(this.props.className, this.setClassNamespace('thumbnail-caption'));
return React.createElement(
Component,
_extends({}, this.props, {
className: classes
}),
this.props.children
);
}
});
module.exports = Thumbnail;
/***/ },
/* 27 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var AvgGrid = __webpack_require__(8);
var omit = __webpack_require__(10);
var Thumbnails = React.createClass({
displayName: 'Thumbnails',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'thumbnails'
};
},
render: function render() {
var classes = classNames(this.getClassSet(), this.props.className);
var props = omit(this.props, 'classPrefix');
return React.createElement(
AvgGrid,
_extends({}, props, {
className: classes
}),
React.Children.map(this.props.children, function (child, i) {
return React.createElement(
'li',
{ key: i },
child
);
})
);
}
});
module.exports = Thumbnails;
/***/ },
/* 28 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Table = React.createClass({
displayName: 'Table',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
bordered: React.PropTypes.bool,
compact: React.PropTypes.bool,
hover: React.PropTypes.bool,
striped: React.PropTypes.bool,
radius: React.PropTypes.bool,
responsive: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'table'
};
},
render: function render() {
var classSet = this.getClassSet();
var responsive = this.props.responsive;
classSet[this.prefixClass('bordered')] = this.props.bordered;
classSet[this.prefixClass('compact')] = this.props.compact;
classSet[this.prefixClass('hover')] = this.props.hover;
classSet[this.prefixClass('striped')] = this.props.striped;
classSet[this.prefixClass('radius')] = this.props.radius;
// add `.am-text-nowrap` to responsive table
classSet[this.setClassNamespace('text-nowrap')] = responsive;
var table = React.createElement(
'table',
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
this.props.children
);
return responsive ? React.createElement(
'div',
{ className: this.setClassNamespace('scrollable-horizontal') },
table
) : table;
}
});
module.exports = Table;
/***/ },
/* 29 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Nav = React.createClass({
displayName: 'Nav',
mixins: [ClassNameMixin],
propTypes: {
justify: React.PropTypes.bool,
pills: React.PropTypes.bool,
tabs: React.PropTypes.bool,
component: React.PropTypes.node.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'nav',
component: 'ul'
};
},
render: function render() {
var classes = this.getClassSet();
var Component = this.props.component;
// set classes
classes[this.prefixClass('pills')] = this.props.pills || this.props.topbar;
classes[this.prefixClass('tabs')] = this.props.tabs;
classes[this.prefixClass('justify')] = this.props.justify;
// topbar class
classes[this.setClassNamespace('topbar-nav')] = this.props.topbar;
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
this.props.children
);
}
});
module.exports = Nav;
/***/ },
/* 30 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var assign = __webpack_require__(31);
var omit = __webpack_require__(10);
var ClassNameMixin = __webpack_require__(4);
var NavItem = React.createClass({
displayName: 'NavItem',
mixins: [ClassNameMixin],
propTypes: {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
header: React.PropTypes.bool,
divider: React.PropTypes.bool,
href: React.PropTypes.any,
component: React.PropTypes.any,
linkComponent: React.PropTypes.any,
linkProps: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'nav',
component: 'li'
};
},
render: function render() {
var classes = this.getClassSet();
var props = this.props;
var Component = props.component;
// del am-nav
classes[this.setClassNamespace(props.classPrefix)] = false;
// set classes
classes[this.prefixClass('header')] = props.header;
classes[this.prefixClass('divider')] = props.divider;
if (props.href || props.linkComponent) {
return this.renderAnchor(classes);
}
return React.createElement(
Component,
_extends({}, props, {
className: classNames(classes, props.className)
}),
this.props.children
);
},
renderAnchor: function renderAnchor(classes) {
var Component = this.props.component;
var linkComponent = this.props.linkComponent || 'a';
var style = {};
this.props.disabled && (style.pointerEvents = 'none');
var linkProps = {
href: this.props.href,
title: this.props.tilte,
target: this.props.target,
style: style
};
return React.createElement(
Component,
_extends({}, omit(this.props, ['href', 'target', 'title', 'disabled']), {
className: classNames(classes, this.props.className)
}),
React.createElement(linkComponent, assign(linkProps, this.props.linkProps), this.props.children)
);
}
});
module.exports = NavItem;
// TODO: DropDown Tab 处理
/***/ },
/* 31 */
/***/ 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;
};
/***/ },
/* 32 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var assign = __webpack_require__(31);
var ClassNameMixin = __webpack_require__(4);
var Breadcrumb = React.createClass({
displayName: 'Breadcrumb',
mixins: [ClassNameMixin],
propTypes: {
slash: React.PropTypes.bool,
component: React.PropTypes.node.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'breadcrumb',
component: 'ul'
};
},
render: function render() {
var classes = this.getClassSet();
var Component = this.props.component;
classes[this.prefixClass('slash')] = this.props.slash;
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
this.props.children
);
}
});
Breadcrumb.Item = React.createClass({
displayName: 'Item',
mixins: [ClassNameMixin],
propTypes: {
active: React.PropTypes.bool,
href: React.PropTypes.string,
title: React.PropTypes.string,
target: React.PropTypes.string,
component: React.PropTypes.any,
linkComponent: React.PropTypes.any,
linkProps: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
component: 'li'
};
},
renderAnchor: function renderAnchor(classes) {
var Component = this.props.component;
var linkComponent = this.props.linkComponent || 'a';
return React.createElement(
Component,
_extends({}, this.props, {
className: classes
}),
React.createElement(linkComponent, assign({
href: this.props.href,
title: this.props.title,
target: this.props.target
}, this.props.linkProps), this.props.children)
);
},
render: function render() {
var classes = classNames(this.props.className);
var Component = this.props.component;
if (this.props.href || this.props.linkComponent) {
return this.renderAnchor(classes);
}
return React.createElement(
Component,
_extends({}, this.props, {
className: classes
}),
this.props.children
);
}
});
module.exports = Breadcrumb;
/***/ },
/* 33 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var assign = __webpack_require__(31);
var omit = __webpack_require__(10);
var ClassNameMixin = __webpack_require__(4);
var Pagination = React.createClass({
displayName: 'Pagination',
mixins: [ClassNameMixin],
PropTypes: {
component: React.PropTypes.node.isRequired,
centered: React.PropTypes.bool,
right: React.PropTypes.bool,
theme: React.PropTypes.oneOf(['default', 'select']),
data: React.PropTypes.object,
onSelect: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'pagination',
component: 'ul'
};
},
renderItem: function renderItem(type) {
var data = this.props.data;
return data && data[type + 'Title'] && data[type + 'Link'] ? React.createElement(
Pagination.Item,
{
onClick: this.props.onSelect && this.props.onSelect.bind(this, data[type + 'Link']),
key: type,
href: data[type + 'Link'],
className: this.prefixClass(type)
},
data[type + 'Title']
) : null;
},
handleChange: function handleChange(e) {
if (this.props.onSelect) {
var select = ReactDOM.findDOMNode(this.refs.select);
this.props.onSelect.call(this, select && select.value, e);
}
},
renderPages: function renderPages() {
var data = this.props.data;
if (data.pages) {
return this.props.theme === 'select' ? React.createElement(
'li',
{ className: this.prefixClass('select') },
React.createElement(
'select',
{
onChange: this.handleChange,
ref: 'select'
},
data.pages.map(function (page, i) {
return React.createElement(
'option',
{ value: page.link, key: i },
page.title,
' / ',
data.pages.length
);
})
)
) : data.pages.map(function (page, i) {
return React.createElement(
Pagination.Item,
{
key: i,
onClick: this.props.onSelect && this.props.onSelect.bind(this, page.link),
active: page.active,
disabled: page.disabled,
href: page.link
},
page.title
);
}.bind(this));
}
},
render: function render() {
var props = this.props;
var Component = props.component;
var classSet = this.getClassSet();
var notSelect = props.theme !== 'select';
// .am-pagination-right
classSet[this.prefixClass('right')] = props.right;
// .am-pagination-centered
classSet[this.prefixClass('centered')] = props.centered;
return props.data ? React.createElement(
Component,
_extends({}, props, {
className: classNames(classSet, props.className)
}),
notSelect && this.renderItem('first'),
this.renderItem('prev'),
this.renderPages(),
this.renderItem('next'),
notSelect && this.renderItem('last')
) : React.createElement(
Component,
_extends({}, props, {
className: classNames(classSet, props.className)
}),
this.props.children
);
}
});
Pagination.Item = React.createClass({
displayName: 'Item',
mixins: [ClassNameMixin],
propTypes: {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
prev: React.PropTypes.bool,
next: React.PropTypes.bool,
href: React.PropTypes.string,
component: React.PropTypes.any,
linkComponent: React.PropTypes.any,
linkProps: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'pagination',
component: 'li'
};
},
render: function render() {
var Component = this.props.component;
var classSet = this.getClassSet(true);
var props = this.props;
var linkComponent = this.props.linkComponent || (this.props.href ? 'a' : null);
// .am-pagination-prev
classSet[this.prefixClass('prev')] = props.prev;
// .am-pagination-next
classSet[this.prefixClass('next')] = props.next;
return React.createElement(
Component,
_extends({}, omit(this.props, ['href', 'title', 'target']), {
className: classNames(classSet, this.props.className)
}),
linkComponent ? React.createElement(linkComponent, assign({
href: this.props.href,
title: this.props.title,
target: this.props.target,
ref: 'anchor'
}, this.props.linkProps), this.props.children) : this.props.children
);
}
});
module.exports = Pagination;
/***/ },
/* 34 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var assign = __webpack_require__(31);
var ClassNameMixin = __webpack_require__(4);
var createChainedFunction = __webpack_require__(35);
var Icon = __webpack_require__(23);
var Button = __webpack_require__(9);
var Topbar = React.createClass({
displayName: 'Topbar',
mixins: [ClassNameMixin],
propTypes: {
component: React.PropTypes.node,
brand: React.PropTypes.node,
brandLink: React.PropTypes.string,
inverse: React.PropTypes.bool,
fixedTop: React.PropTypes.bool,
fixedBottom: React.PropTypes.bool,
toggleBtn: React.PropTypes.node,
toggleNavKey: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
onToggle: React.PropTypes.func,
navExpanded: React.PropTypes.bool,
defaultNavExpanded: React.PropTypes.bool,
fluid: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'topbar',
component: 'header'
};
},
getInitialState: function getInitialState() {
return {
navExpanded: this.props.defaultNavExpanded
};
},
shouldComponentUpdate: function shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleToggle: function handleToggle() {
if (this.props.onToggle) {
this._isChanging = true;
this.props.onToggle();
this._isChanging = false;
}
this.setState({
navExpanded: !this.state.navExpanded
});
},
isNavExpanded: function isNavExpanded() {
return this.props.navExpanded != null ? this.props.navExpanded : this.state.navExpanded;
},
renderBrand: function renderBrand() {
var brand = this.props.brand;
var brandClassName = this.prefixClass('brand');
if (React.isValidElement(brand)) {
return React.cloneElement(brand, assign({}, brand.props, {
className: classNames(brand.props.className, brandClassName),
onClick: createChainedFunction(this.handleToggle, brand.props.onClick)
}));
}
return brand ? React.createElement(
'h1',
{ className: brandClassName },
this.props.brandLink ? React.createElement(
'a',
{ href: this.props.brandLink },
this.props.brand
) : this.props.brand
) : null;
},
renderToggleButton: function renderToggleButton() {
var toggleBtn = this.props.toggleBtn;
var toggleBtnClassName = this.prefixClass('toggle');
if (React.isValidElement(toggleBtn)) {
return React.cloneElement(toggleBtn, assign({}, toggleBtn.props, {
className: classNames(toggleBtn.props.className, toggleBtnClassName),
onClick: createChainedFunction(this.handleToggle, toggleBtn.props.onClick)
}));
}
return React.createElement(
Button,
{
amSize: 'sm',
onClick: this.handleToggle,
className: classNames(this.prefixClass('btn'), this.prefixClass('toggle'), this.setClassNamespace('show-sm-only'))
},
React.createElement(
'span',
{ className: this.setClassNamespace('sr-only') },
'导航切换'
),
React.createElement(Icon, { icon: 'bars' })
);
},
renderChild: function renderChild(child, i) {
return React.cloneElement(child, assign({}, child.props, {
topbar: true,
collapsible: this.props.toggleNavKey != null && this.props.toggleNavKey === child.props.eventKey,
expanded: this.props.toggleNavKey != null && this.props.toggleNavKey === child.props.eventKey && this.isNavExpanded(),
key: child.key ? child.key : i,
className: classNames(child.props.className, child.props.right ? this.prefixClass('right') : null)
}));
},
render: function render() {
var classes = this.getClassSet();
var Component = this.props.component;
// set classes
classes[this.prefixClass('inverse')] = this.props.inverse;
classes[this.prefixClass('fixed-top')] = this.props.fixedTop;
classes[this.prefixClass('fixed-bottom')] = this.props.fixedBottom;
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
React.createElement(
'div',
{
className: !this.props.fluid ? this.setClassNamespace('container') : null
},
this.renderBrand(),
this.renderToggleButton(),
React.Children.map(this.props.children, this.renderChild)
)
);
}
});
module.exports = Topbar;
/***/ },
/* 35 */
/***/ function(module, exports) {
/**
* modified version of:
* https://github.com/react-bootstrap/react-bootstrap/blob/master/src/utils/createChainedFunction.js
*/
'use strict';
/**
* Safe chained function
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*
* @param {function} one
* @param {function} two
* @returns {function|null}
*/
function createChainedFunction(one, two) {
var hasOne = typeof one === 'function';
var hasTwo = typeof two === 'function';
if (!hasOne && !hasTwo) {
return null;
}
if (!hasOne) {
return two;
}
if (!hasTwo) {
return one;
}
return function chainedFunction() {
one.apply(this, arguments) === false || two.apply(this, arguments);
};
}
module.exports = createChainedFunction;
/***/ },
/* 36 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var omit = __webpack_require__(10);
var ClassNameMixin = __webpack_require__(4);
var Nav = __webpack_require__(29);
var NavItem = __webpack_require__(30);
var Tabs = React.createClass({
displayName: 'Tabs',
mixins: [ClassNameMixin],
propTypes: {
theme: React.PropTypes.oneOf(['default', 'd2']),
onSelect: React.PropTypes.func,
animation: React.PropTypes.oneOf(['slide', 'fade']),
defaultActiveKey: React.PropTypes.any,
justify: React.PropTypes.bool,
data: React.PropTypes.array
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'tabs',
animation: 'fade'
};
},
getInitialState: function getInitialState() {
var defaultActiveKey = this.props.defaultActiveKey != null ? this.props.defaultActiveKey : this.getDefaultActiveKey(this.props.children);
return {
activeKey: defaultActiveKey,
previousActiveKey: null
};
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.activeKey != null && nextProps.activeKey !== this.props.activeKey) {
this.setState({
previousActiveKey: this.props.activeKey
});
}
},
getDefaultActiveKey: function getDefaultActiveKey(children) {
var defaultActiveKey = null;
if (this.props.data) {
this.props.data.every(function (item, i) {
if (item.active) {
defaultActiveKey = i;
return false;
}
return true;
});
return defaultActiveKey == null ? 0 : defaultActiveKey;
}
React.Children.forEach(children, function (child) {
if (defaultActiveKey == null) {
defaultActiveKey = child.props.eventKey;
}
});
return defaultActiveKey;
},
handleClick: function handleClick(key, disabled, e) {
e.preventDefault();
var activeKey = this.state.activeKey;
if (disabled) {
return null;
}
if (this.props.onSelect) {
this.props.onSelect(key);
}
if (activeKey !== key) {
this.setState({
activeKey: key,
previousActiveKey: activeKey
});
}
},
renderNav: function renderNav() {
var activeKey = this.state.activeKey;
return React.Children.map(this.props.children, function (child, index) {
var key = child.props.eventKey || index;
var disabled = child.props.disabled;
return React.createElement(
NavItem,
{
href: '#',
ref: 'ref' + key,
key: key,
onClick: this.handleClick.bind(this, key, disabled),
active: child.props.eventKey === activeKey,
disabled: disabled
},
child.props.title
);
}.bind(this));
},
renderTabPanels: function renderTabPanels() {
var activeKey = this.state.activeKey;
return React.Children.map(this.props.children, function (child, index) {
return React.createElement(
Tabs.Item,
{
active: child.props.eventKey === activeKey,
key: index
},
child.props.children
);
});
},
// for Amaze UI tabs widget
renderData: function renderData() {
var activeKey = this.state.activeKey;
var navs = [];
var panels = [];
this.props.data.forEach(function (item, key) {
navs.push(React.createElement(
NavItem,
{
href: '#',
ref: 'ref' + key,
key: key,
onClick: this.handleClick.bind(this, key, item.disabled),
active: key === activeKey,
disabled: item.disabled
},
item.title
));
panels.push(React.createElement(
Tabs.Item,
{
eventKey: key
// active={item.active}
, active: key === activeKey,
key: key },
item.content
));
}.bind(this));
return {
navs: navs,
panels: panels
};
},
renderWrapper: function renderWrapper(children) {
var classSet = this.getClassSet();
var props = omit(this.props, 'data');
return React.createElement(
'div',
_extends({}, props, {
'data-am-widget': this.props.theme ? this.props.classPrefix : null,
className: classNames(classSet, this.props.className)
}),
children
);
},
renderNavWrapper: function renderNavWrapper(children) {
var TabsNav = this.props.theme ? 'ul' : Nav;
return React.createElement(
TabsNav,
{
key: 'tabsNav',
tabs: true,
className: classNames(this.prefixClass('nav'), this.setClassNamespace('cf')),
justify: this.props.justify
},
children
);
},
renderBodyWrapper: function renderBodyWrapper(children) {
var animationClass = this.prefixClass(this.props.animation);
return React.createElement(
'div',
{
key: 'tabsBody',
className: classNames(this.prefixClass('bd'), animationClass)
},
children
);
},
render: function render() {
var children = this.props.data ? this.renderData() : {};
return this.renderWrapper([this.renderNavWrapper(children.navs || this.renderNav()), this.renderBodyWrapper(children.panels || this.renderTabPanels())]);
}
});
Tabs.Item = React.createClass({
displayName: 'Item',
mixins: [ClassNameMixin],
propTypes: {
title: React.PropTypes.string,
disabled: React.PropTypes.bool,
eventKey: React.PropTypes.any,
active: React.PropTypes.bool
},
render: function render() {
var classSet = {};
classSet[this.setClassNamespace('tab-panel')] = true;
classSet[this.setClassNamespace('fade')] = true;
classSet[this.setClassNamespace('active')] = this.props.active;
classSet[this.setClassNamespace('in')] = this.props.active;
return React.createElement(
'div',
{ className: classNames(classSet) },
this.props.children
);
}
});
module.exports = Tabs;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/*
* https://github.com/react-bootstrap/react-bootstrap/blob/master/src/CollapsibleNav.js
* */
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var CollapseMixin = __webpack_require__(38);
var createChainedFunction = __webpack_require__(35);
var CollapsibleNav = React.createClass({
displayName: 'CollapsibleNav',
mixins: [ClassNameMixin, CollapseMixin],
propTypes: {
collapsible: React.PropTypes.bool,
onSelect: React.PropTypes.func,
activeHref: React.PropTypes.string,
activeKey: React.PropTypes.any,
expanded: React.PropTypes.bool,
eventKey: React.PropTypes.any
},
handleToggle: function handleToggle() {
this.setState({ expanded: !this.state.expanded });
},
getCollapsibleDimensionValue: function getCollapsibleDimensionValue() {
var height = 0;
var nodes = this.refs;
for (var key in nodes) {
if (nodes.hasOwnProperty(key)) {
var n = ReactDOM.findDOMNode(nodes[key]);
var h = n.offsetHeight;
var computedStyles = getComputedStyle(n, null);
height += h + parseInt(computedStyles.marginTop, 10) + parseInt(computedStyles.marginBottom, 10);
}
}
return height;
},
getCollapsibleDOMNode: function getCollapsibleDOMNode() {
return ReactDOM.findDOMNode(this);
},
getChildActiveProp: function getChildActiveProp(child) {
if (child.props.active) {
return true;
}
if (this.props.activeKey != null) {
if (child.props.eventKey === this.props.activeKey) {
return true;
}
}
if (this.props.activeHref != null) {
if (child.props.href === this.props.activeHref) {
return true;
}
}
return child.props.active;
},
renderChildren: function renderChildren(child, index) {
var key = child.key ? child.key : index;
return React.cloneElement(child, {
activeKey: this.props.activeKey,
activeHref: this.props.activeHref,
ref: 'nocollapse_' + key,
key: key,
navItem: true
});
},
renderCollapsibleNavChildren: function renderCollapsibleNavChildren(child, index) {
var key = child.key ? child.key : index;
return React.cloneElement(child, {
active: this.getChildActiveProp(child),
activeKey: this.props.activeKey,
activeHref: this.props.activeHref,
onSelect: createChainedFunction(child.props.onSelect, this.props.onSelect),
ref: 'collapsible_' + key,
key: key
});
},
render: function render() {
var collapsible = this.props.collapsible;
var classSet = collapsible ? this.getCollapsibleClassSet() : {};
classSet[this.setClassNamespace('topbar-collapse')] = this.props.topbar;
return React.createElement(
'div',
{
eventKey: this.props.eventKey,
className: classNames(classSet, this.props.className)
},
React.Children.map(this.props.children, collapsible ? this.renderCollapsibleNavChildren : this.renderChildren)
);
}
});
module.exports = CollapsibleNav;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
/**
* modified version of:
* https://github.com/react-bootstrap/react-bootstrap/blob/master/src/CollapsibleMixin.js
*/
'use strict';
var React = __webpack_require__(1);
var TransitionEvents = __webpack_require__(39);
var CollapseMixin = {
propTypes: {
defaultExpanded: React.PropTypes.bool,
expanded: React.PropTypes.bool
},
getInitialState: function getInitialState() {
var defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : this.props.expanded != null ? this.props.expanded : false;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillUpdate: function componentWillUpdate(nextProps, nextState) {
var willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
var node = this.getCollapsibleDOMNode();
var dimension = this.dimension();
var value = '0';
if (!willExpanded) {
// get height
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate: function componentDidUpdate(prevProps, prevState) {
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate: function _afterWillUpdate() {},
_checkStartAnimation: function _checkStartAnimation() {
if (!this.state.collapsing) {
return;
}
var node = this.getCollapsibleDOMNode();
var dimension = this.dimension();
var value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
var result;
if (this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing: function _checkToggleCollapsing(prevProps, prevState) {
var wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
var isExpanded = this.isExpanded();
if (wasExpanded !== isExpanded) {
if (wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand: function _handleExpand() {
var node = this.getCollapsibleDOMNode();
var dimension = this.dimension();
var complete = function () {
this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
this.setState({
collapsing: false
});
}.bind(this);
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse: function _handleCollapse() {
var node = this.getCollapsibleDOMNode();
var _this = this;
var complete = function complete() {
_this._removeEndEventListener(node, complete);
_this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener: function _addEndEventListener(node, complete) {
TransitionEvents.on(node, complete);
},
// helps enable test stubs
_removeEndEventListener: function _removeEndEventListener(node, complete) {
TransitionEvents.off(node, complete);
},
dimension: function dimension() {
return typeof this.getCollapsibleDimension === 'function' ? this.getCollapsibleDimension() : 'height';
},
isExpanded: function isExpanded() {
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet: function getCollapsibleClassSet(className) {
var classSet = {};
if (typeof className === 'string') {
className.split(' ').forEach(function (subClass) {
if (subClass) {
classSet[subClass] = true;
}
});
}
classSet[this.setClassNamespace('collapsing')] = this.state.collapsing;
classSet[this.setClassNamespace('collapse')] = !this.state.collapsing;
classSet[this.setClassNamespace('in')] = this.isExpanded() && !this.state.collapsing;
return classSet;
}
};
module.exports = CollapseMixin;
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*
* modified version of:
* https://github.com/facebook/react/blob/0.13-stable/src/addons/transitions/ReactTransitionEvents.js
* https://github.com/facebook/react/blob/5696ccfcd72189f4fea13d8b0f084a0e3c9b8147/src/renderers/dom/client/utils/getVendorPrefixedEventName.js
*/
'use strict';
var CSSCore = __webpack_require__(16);
var canUseDOM = __webpack_require__(40);
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
var support = {};
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
support[baseEventName] = false;
for (var styleName in baseEvents) {
if (styleName in style) {
support[baseEventName] = baseEvents[styleName];
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (canUseDOM) {
detectEvents();
}
if (support.animationend) {
CSSCore.addClass(document.documentElement, 'cssanimations');
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var TransitionEvents = {
on: function on(node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
off: function off(node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
},
support: support
};
module.exports = TransitionEvents;
/***/ },
/* 40 */
/***/ function(module, exports) {
'use strict';
module.exports = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/***/ },
/* 41 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Article = React.createClass({
displayName: 'Article',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
title: React.PropTypes.node,
meta: React.PropTypes.node,
lead: React.PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'article'
};
},
render: function render() {
var classSet = this.getClassSet();
return React.createElement(
'article',
_extends({}, this.props, {
className: classNames(classSet, this.props.className)
}),
React.createElement(
'header',
{ className: this.prefixClass('hd') },
this.props.title ? React.createElement(
Article.Child,
{ role: 'title' },
this.props.title
) : null,
this.props.meta ? React.createElement(
Article.Child,
{ role: 'meta' },
this.props.meta
) : null
),
React.createElement(
'div',
{ className: this.prefixClass('bd') },
this.props.lead ? React.createElement(
Article.Child,
{ role: 'lead' },
this.props.lead
) : null,
this.props.children
)
);
}
});
Article.Child = React.createClass({
displayName: 'Child',
mixins: [ClassNameMixin],
propTypes: {
role: React.PropTypes.string.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
role: 'title'
};
},
render: function render() {
var role = this.props.role;
var Component;
var classes = classNames(this.props.className, this.setClassNamespace('article-' + role));
switch (role) {
case 'meta':
case 'lead':
Component = 'p';
break;
case 'title':
Component = 'h1';
break;
default:
Component = 'div';
}
return role === 'divider' ? React.createElement('hr', _extends({}, this.props, {
className: classes
})) : React.createElement(
Component,
_extends({}, this.props, {
className: classes
}),
this.props.children
);
}
});
module.exports = Article;
/***/ },
/* 42 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Badge = React.createClass({
displayName: 'Badge',
mixins: [ClassNameMixin],
propTypes: {
component: React.PropTypes.node,
href: React.PropTypes.string,
round: React.PropTypes.bool,
radius: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'badge',
component: 'span'
};
},
renderAnchor: function renderAnchor(classSet) {
var Component = this.props.component || 'a';
var href = this.props.href || '#';
return React.createElement(
Component,
_extends({}, this.props, {
href: href,
className: classNames(classSet, this.props.className),
role: 'badge'
}),
this.props.children
);
},
render: function render() {
var classSet = this.getClassSet();
var Component = this.props.component;
var renderAnchor = this.props.href;
if (renderAnchor) {
return this.renderAnchor(classSet);
}
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(classSet, this.props.className)
}),
this.props.children
);
}
});
module.exports = Badge;
/***/ },
/* 43 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Icon = __webpack_require__(23);
var Close = React.createClass({
displayName: 'Close',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
component: React.PropTypes.node,
spin: React.PropTypes.bool,
alt: React.PropTypes.bool,
icon: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'close',
type: 'button'
};
},
render: function render() {
var Component = this.props.component || 'button';
var classSet = this.getClassSet();
var props = this.props;
// transfer type
if (Component !== 'button') {
props.type = undefined;
}
// className am-close-alt am-close-spin
classSet[this.prefixClass('alt')] = this.props.alt;
classSet[this.prefixClass('spin')] = this.props.spin;
return React.createElement(
Component,
_extends({}, props, {
className: classNames(classSet, this.props.className),
role: 'close'
}),
this.props.icon ? React.createElement(Icon, { icon: 'times' }) : '×'
);
}
});
module.exports = Close;
/***/ },
/* 44 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var List = React.createClass({
displayName: 'List',
mixins: [ClassNameMixin],
propTypes: {
bordered: React.PropTypes.bool,
striped: React.PropTypes.bool,
static: React.PropTypes.bool,
component: React.PropTypes.node.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'list',
component: 'ul'
};
},
render: function render() {
var classes = this.getClassSet();
var Component = this.props.component;
var props = this.props;
var prefixClass = this.prefixClass;
// am-list-border
classes[prefixClass('border')] = props.border || props.bordered;
// am-list-striped
classes[prefixClass('striped')] = props.striped;
// am-list-static
classes[prefixClass('static')] = props.static;
return React.createElement(
Component,
_extends({}, props, {
className: classNames(classes, props.className)
}),
props.children
);
}
});
module.exports = List;
/***/ },
/* 45 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var assign = __webpack_require__(31);
var ClassNameMixin = __webpack_require__(4);
var ListItem = React.createClass({
displayName: 'ListItem',
mixins: [ClassNameMixin],
propTypes: {
href: React.PropTypes.string,
truncate: React.PropTypes.bool,
component: React.PropTypes.any.isRequired,
linkComponent: React.PropTypes.any,
linkProps: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
component: 'li'
};
},
render: function render() {
var classes = {};
var Component = this.props.component;
// set .am-text-truncate
classes['am-text-truncate'] = this.props.truncate;
// render Anchor
if (this.props.href || this.props.linkComponent) {
return this.renderAnchor(classes);
}
return React.createElement(
Component,
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
this.props.children
);
},
renderAnchor: function renderAnchor(classes) {
var props = this.props;
var Component = props.component;
var truncate = props.truncate ? 'am-text-truncate' : '';
var linkComponent = this.props.linkComponent || 'a';
return React.createElement(
Component,
_extends({}, props, {
className: classNames(classes, this.props.className)
}),
React.createElement(linkComponent, assign({
className: truncate,
href: this.props.href,
title: this.props.title,
target: this.props.target
}, this.props.linkProps), this.props.children)
);
}
});
module.exports = ListItem;
/***/ },
/* 46 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var CollapseMixin = __webpack_require__(38);
var Panel = React.createClass({
displayName: 'Panel',
mixins: [ClassNameMixin, CollapseMixin],
propTypes: {
collapsible: React.PropTypes.bool,
header: React.PropTypes.node,
footer: React.PropTypes.node,
id: React.PropTypes.string,
amStyle: React.PropTypes.string,
onSelect: React.PropTypes.func,
eventKey: React.PropTypes.any
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'panel',
amStyle: 'default'
};
},
handleClick: function handleClick(e) {
e.selected = true;
if (this.props.onSelect) {
this.props.onSelect(e, this.props.eventKey);
} else {
e.preventDefault();
}
if (e.selected) {
this.handleToggle();
}
},
handleToggle: function handleToggle() {
this.setState({ expanded: !this.state.expanded });
},
getCollapsibleDimensionValue: function getCollapsibleDimensionValue() {
return ReactDOM.findDOMNode(this.refs.panel).scrollHeight;
},
getCollapsibleDOMNode: function getCollapsibleDOMNode() {
if (!this.isMounted() || !this.refs || !this.refs.panel) {
return null;
}
return ReactDOM.findDOMNode(this.refs.panel);
},
renderHeader: function renderHeader() {
if (!this.props.header) {
return null;
}
var header = this.props.header;
return React.createElement(
'div',
{ className: this.prefixClass('hd') },
this.props.collapsible ? React.createElement(
'h4',
{
'data-am-collapse': true // just for `pointer` style
, className: classNames(this.prefixClass('title'), this.isExpanded() ? null : this.setClassNamespace('collapsed')),
onClick: this.handleClick
},
header
) : header
);
},
renderBody: function renderBody() {
var bodyClass = this.prefixClass('bd');
var bodyChildren = this.props.children;
var bodyElements = [];
var panelBodyChildren = [];
function getProps() {
return {
key: bodyElements.length
};
}
function addFillChild(child) {
bodyElements.push(React.cloneElement(child, getProps()));
}
function addPanelBody(child) {
bodyElements.push(React.createElement(
'div',
_extends({ className: bodyClass }, getProps, { key: 'panelBody' }),
child
));
}
function maybeRenderPanelBody() {
if (panelBodyChildren.length === 0) {
return;
}
addPanelBody(panelBodyChildren);
panelBodyChildren = [];
}
if (Array.isArray(bodyChildren)) {
bodyChildren.forEach(function (child) {
// props fill and isValidElement
if (this.shouldRenderFill(child)) {
maybeRenderPanelBody();
addFillChild(child);
} else {
panelBodyChildren.push(child);
}
}.bind(this));
maybeRenderPanelBody();
} else {
if (this.shouldRenderFill(bodyChildren)) {
addFillChild(bodyChildren);
} else {
addPanelBody(bodyChildren);
}
}
return bodyElements;
},
renderCollapsibleBody: function renderCollapsibleBody() {
var collapseClass = this.prefixClass('collapse');
return React.createElement(
'div',
{
className: classNames(this.getCollapsibleClassSet(collapseClass)),
id: this.props.id,
ref: 'panel'
},
this.renderBody()
);
},
shouldRenderFill: function shouldRenderFill(child) {
return React.isValidElement(child) && child.props.fill;
},
renderFooter: function renderFooter() {
if (!this.props.footer) {
return null;
}
return React.createElement(
'div',
{ className: this.prefixClass('footer') },
this.props.footer
);
},
render: function render() {
var classes = this.getClassSet();
var collapsible = this.props.collapsible;
return React.createElement(
'div',
_extends({}, this.props, {
id: collapsible ? null : this.props.id,
className: classNames(classes, this.props.className)
}),
this.renderHeader(),
collapsible ? this.renderCollapsibleBody() : this.renderBody(),
this.renderFooter()
);
}
});
module.exports = Panel;
/***/ },
/* 47 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var PanelGroup = React.createClass({
displayName: 'PanelGroup',
mixins: [ClassNameMixin],
propTypes: {
amStyle: React.PropTypes.string,
activeKey: React.PropTypes.any,
defaultActiveKey: React.PropTypes.any,
onSelect: React.PropTypes.func,
accordion: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'panel-group'
};
},
getInitialState: function getInitialState() {
return {
activeKey: this.props.defaultActiveKey
};
},
shouldComponentUpdate: function shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleSelect: function handleSelect(e, key) {
e.preventDefault();
if (this.props.onSelect) {
this._isChanging = true;
this.props.onSelect(key);
this._isChanging = false;
}
if (this.state.activeKey === key) {
key = null;
}
this.setState({
activeKey: key
});
},
renderPanel: function renderPanel(child, index) {
var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey;
var props = {
amStyle: child.props.amStyle || this.props.amStyle,
key: child.key ? child.key : index,
ref: child.ref
};
if (this.props.accordion) {
props.collapsible = true;
props.expanded = child.props.eventKey === activeKey;
props.onSelect = this.handleSelect;
}
return React.cloneElement(child, props);
},
render: function render() {
var classes = this.getClassSet();
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
React.Children.map(this.props.children, this.renderPanel)
);
}
});
module.exports = PanelGroup;
/***/ },
/* 48 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Progress = React.createClass({
displayName: 'Progress',
mixins: [ClassNameMixin],
propTypes: {
now: React.PropTypes.number,
label: React.PropTypes.string,
active: React.PropTypes.bool,
striped: React.PropTypes.bool,
amSize: React.PropTypes.string,
amStyle: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'progress'
};
},
renderProgressBar: function renderProgressBar() {
var styleSheet = {
width: this.props.now + '%'
};
var classes = {};
var prefix = this.prefixClass('bar');
var amStyle = this.props.amStyle;
// set am-progress-bar
classes[prefix] = true;
if (amStyle) {
classes[prefix + '-' + amStyle] = true;
}
return React.createElement(
'div',
{
className: classNames(classes),
style: styleSheet,
role: 'progressbar'
},
this.props.label
);
},
renderChildBar: function renderChildBar(child, index) {
return React.cloneElement(child, {
isChild: true,
key: child.key ? child.key : index
});
},
render: function render() {
var classes = this.getClassSet();
// set class
classes[this.prefixClass('striped')] = this.props.striped;
if (this.props.active) {
classes[this.prefixClass('striped')] = true;
}
if (!this.props.children) {
if (!this.props.isChild) {
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
this.renderProgressBar()
);
} else {
return this.renderProgressBar();
}
} else {
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(classes, this.props.className)
}),
React.Children.map(this.props.children, this.renderChildBar)
);
}
}
});
module.exports = Progress;
// Todo: 删除无用 class
// : key ref 处理问题
/***/ },
/* 49 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Alert = React.createClass({
displayName: 'Alert',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
amStyle: React.PropTypes.oneOf(['secondary', 'success', 'warning', 'danger']),
onClose: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'alert'
};
},
renderCloseBtn: function renderCloseBtn() {
return React.createElement(
'button',
{
type: 'button',
className: this.setClassNamespace('close'),
onClick: this.props.onClose
},
'×'
);
},
render: function render() {
var classSet = this.getClassSet();
var isCloseable = !!this.props.onClose;
if (this.props.amStyle) {
classSet[this.prefixClass(this.props.amStyle)] = true;
}
classSet[this.prefixClass('closeable')] = isCloseable;
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(this.props.className, classSet)
}),
isCloseable ? this.renderCloseBtn() : null,
this.props.children
);
}
});
module.exports = Alert;
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = {
DateTimeInput: __webpack_require__(51),
DateTimePicker: __webpack_require__(55)
};
/***/ },
/* 51 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var fecha = __webpack_require__(52);
var Events = __webpack_require__(53);
var isNodeInTree = __webpack_require__(54);
var Input = __webpack_require__(21);
var DateTimePicker = __webpack_require__(55);
var DateTimeInput = React.createClass({
displayName: 'DateTimeInput',
propTypes: {
format: React.PropTypes.string,
dateTime: React.PropTypes.string,
onSelect: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
dateTime: '',
format: 'YYYY-MM-DD HH:mm'
};
},
getInitialState: function getInitialState() {
return {
value: this.props.dateTime || fecha.format(new Date(), this.props.format),
showPicker: false
};
},
handleOuterClick: function handleOuterClick(event) {
var picker = ReactDOM.findDOMNode(this.refs.DateTimePicker);
if (!isNodeInTree(event.target, picker)) {
this.handleClose();
}
},
bindOuterHandlers: function bindOuterHandlers() {
Events.on(document, 'click', this.handleOuterClick);
},
unbindOuterHandlers: function unbindOuterHandlers() {
Events.off(document, 'click', this.handleOuterClick);
},
handleClose: function handleClose() {
this.unbindOuterHandlers();
return this.setState({
showPicker: false
});
},
handleClick: function handleClick() {
this.bindOuterHandlers();
var positionNode = ReactDOM.findDOMNode(this.refs.dateInput);
// fixes #57
// @see http://stackoverflow.com/questions/1044988/getting-offsettop-of-element-in-a-table
var rect = positionNode.getBoundingClientRect();
var offset = {
top: rect.top + positionNode.offsetHeight,
left: rect.left
};
var styles = {
display: 'block',
top: offset.top,
left: offset.left,
position: 'fixed',
zIndex: 1120
};
this.setState({
showPicker: true,
pickerStyle: styles
});
},
handleChange: function handleChange(event) {
this.setState({
value: event.target.value
});
},
handleSelect: function handleSelect(date) {
this.setState({
value: date
});
this.props.onSelect && this.props.onSelect.call(this, date);
},
renderPicker: function renderPicker() {
if (this.state.showPicker) {
return React.createElement(DateTimePicker, {
style: this.state.pickerStyle,
ref: 'DateTimePicker',
showDatePicker: this.props.showDatePicker,
showTimePicker: this.props.showTimePicker,
onSelect: this.handleSelect,
onClose: this.handleClose,
amStyle: this.props.amStyle,
dateTime: this.state.value,
viewMode: this.props.viewMode,
minViewMode: this.props.minViewMode,
daysOfWeekDisabled: this.props.daysOfWeekDisabled,
weekStart: this.props.weekStart,
format: this.props.format,
locale: this.props.locale,
maxDate: this.props.maxDate,
minDate: this.props.minDate
});
}
},
render: function render() {
return React.createElement(
'div',
null,
React.createElement(Input, _extends({}, this.props, {
type: 'text',
value: this.state.value,
onClick: this.handleClick,
onChange: this.handleChange,
onSelect: null,
ref: 'dateInput'
})),
this.renderPicker()
);
}
});
module.exports = DateTimeInput;
// TODO: 动画
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;(function (main) {
'use strict';
/**
* Parse or format dates
* @class fecha
*/
var fecha = {};
var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g;
var twoDigits = /\d\d?/;
var threeDigits = /\d{3}/;
var fourDigits = /\d{4}/;
var word = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i;
var noop = function () {
};
function shorten(arr, sLen) {
var newArr = [];
for (var i = 0, len = arr.length; i < len; i++) {
newArr.push(arr[i].substr(0, sLen));
}
return newArr;
}
function monthUpdate(arrName) {
return function (d, v, i18n) {
var index = i18n[arrName].indexOf(v.charAt(0).toUpperCase() + v.substr(1).toLowerCase());
if (~index) {
d.month = index;
}
};
}
function pad(val, len) {
val = String(val);
len = len || 2;
while (val.length < len) {
val = '0' + val;
}
return val;
}
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var monthNamesShort = shorten(monthNames, 3);
var dayNamesShort = shorten(dayNames, 3);
fecha.i18n = {
dayNamesShort: dayNamesShort,
dayNames: dayNames,
monthNamesShort: monthNamesShort,
monthNames: monthNames,
amPm: ['am', 'pm'],
DoFn: function DoFn(D) {
return D + ['th', 'st', 'nd', 'rd'][D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10];
}
};
var formatFlags = {
D: function(dateObj) {
return dateObj.getDate();
},
DD: function(dateObj) {
return pad(dateObj.getDate());
},
Do: function(dateObj, i18n) {
return i18n.DoFn(dateObj.getDate());
},
d: function(dateObj) {
return dateObj.getDay();
},
dd: function(dateObj) {
return pad(dateObj.getDay());
},
ddd: function(dateObj, i18n) {
return i18n.dayNamesShort[dateObj.getDay()];
},
dddd: function(dateObj, i18n) {
return i18n.dayNames[dateObj.getDay()];
},
M: function(dateObj) {
return dateObj.getMonth() + 1;
},
MM: function(dateObj) {
return pad(dateObj.getMonth() + 1);
},
MMM: function(dateObj, i18n) {
return i18n.monthNamesShort[dateObj.getMonth()];
},
MMMM: function(dateObj, i18n) {
return i18n.monthNames[dateObj.getMonth()];
},
YY: function(dateObj) {
return String(dateObj.getFullYear()).substr(2);
},
YYYY: function(dateObj) {
return dateObj.getFullYear();
},
h: function(dateObj) {
return dateObj.getHours() % 12 || 12;
},
hh: function(dateObj) {
return pad(dateObj.getHours() % 12 || 12);
},
H: function(dateObj) {
return dateObj.getHours();
},
HH: function(dateObj) {
return pad(dateObj.getHours());
},
m: function(dateObj) {
return dateObj.getMinutes();
},
mm: function(dateObj) {
return pad(dateObj.getMinutes());
},
s: function(dateObj) {
return dateObj.getSeconds();
},
ss: function(dateObj) {
return pad(dateObj.getSeconds());
},
S: function(dateObj) {
return Math.round(dateObj.getMilliseconds() / 100);
},
SS: function(dateObj) {
return pad(Math.round(dateObj.getMilliseconds() / 10), 2);
},
SSS: function(dateObj) {
return pad(dateObj.getMilliseconds(), 3);
},
a: function(dateObj, i18n) {
return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];
},
A: function(dateObj, i18n) {
return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase();
},
ZZ: function(dateObj) {
var o = dateObj.getTimezoneOffset();
return (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4);
}
};
var parseFlags = {
D: [twoDigits, function (d, v) {
d.day = v;
}],
M: [twoDigits, function (d, v) {
d.month = v - 1;
}],
YY: [twoDigits, function (d, v) {
var da = new Date(), cent = +('' + da.getFullYear()).substr(0, 2);
d.year = '' + (v > 68 ? cent - 1 : cent) + v;
}],
h: [twoDigits, function (d, v) {
d.hour = v;
}],
m: [twoDigits, function (d, v) {
d.minute = v;
}],
s: [twoDigits, function (d, v) {
d.second = v;
}],
YYYY: [fourDigits, function (d, v) {
d.year = v;
}],
S: [/\d/, function (d, v) {
d.millisecond = v * 100;
}],
SS: [/\d{2}/, function (d, v) {
d.millisecond = v * 10;
}],
SSS: [threeDigits, function (d, v) {
d.millisecond = v;
}],
d: [twoDigits, noop],
ddd: [word, noop],
MMM: [word, monthUpdate('monthNamesShort')],
MMMM: [word, monthUpdate('monthNames')],
a: [word, function (d, v, i18n) {
var val = v.toLowerCase();
if (val === i18n.amPm[0]) {
d.isPm = false;
} else if (val === i18n.amPm[1]) {
d.isPm = true;
}
}],
ZZ: [/[\+\-]\d\d:?\d\d/, function (d, v) {
var parts = (v + '').match(/([\+\-]|\d\d)/gi), minutes;
if (parts) {
minutes = +(parts[1] * 60) + parseInt(parts[2], 10);
d.timezoneOffset = parts[0] === '+' ? minutes : -minutes;
}
}]
};
parseFlags.dd = parseFlags.d;
parseFlags.dddd = parseFlags.ddd;
parseFlags.Do = parseFlags.DD = parseFlags.D;
parseFlags.mm = parseFlags.m;
parseFlags.hh = parseFlags.H = parseFlags.HH = parseFlags.h;
parseFlags.MM = parseFlags.M;
parseFlags.ss = parseFlags.s;
parseFlags.A = parseFlags.a;
// Some common format strings
fecha.masks = {
'default': 'ddd MMM DD YYYY HH:mm:ss',
shortDate: 'M/D/YY',
mediumDate: 'MMM D, YYYY',
longDate: 'MMMM D, YYYY',
fullDate: 'dddd, MMMM D, YYYY',
shortTime: 'HH:mm',
mediumTime: 'HH:mm:ss',
longTime: 'HH:mm:ss.SSS'
};
/***
* Format a date
* @method format
* @param {Date|number} dateObj
* @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
*/
fecha.format = function (dateObj, mask, i18nSettings) {
var i18n = i18nSettings || fecha.i18n;
if (typeof dateObj === 'number') {
dateObj = new Date(dateObj);
}
if (Object.prototype.toString.call(dateObj) !== '[object Date]' || isNaN(dateObj.getTime())) {
throw new Error('Invalid Date in fecha.format');
}
mask = fecha.masks[mask] || mask || fecha.masks['default'];
return mask.replace(token, function ($0) {
return $0 in formatFlags ? formatFlags[$0](dateObj, i18n) : $0.slice(1, $0.length - 1);
});
};
/**
* Parse a date string into an object, changes - into /
* @method parse
* @param {string} dateStr Date string
* @param {string} format Date parse format
* @returns {Date|boolean}
*/
fecha.parse = function (dateStr, format, i18nSettings) {
var i18n = i18nSettings || fecha.i18n;
if (typeof format !== 'string') {
throw new Error('Invalid format in fecha.parse');
}
format = fecha.masks[format] || format;
// Avoid regular expression denial of service, fail early for really long strings
// https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
if (dateStr.length > 1000) {
return false;
}
var isValid = true;
var dateInfo = {};
format.replace(token, function ($0) {
if (parseFlags[$0]) {
var info = parseFlags[$0];
var index = dateStr.search(info[0]);
if (!~index) {
isValid = false;
} else {
dateStr.replace(info[0], function (result) {
info[1](dateInfo, result, i18n);
dateStr = dateStr.substr(index + result.length);
return result;
});
}
}
return parseFlags[$0] ? '' : $0.slice(1, $0.length - 1);
});
if (!isValid) {
return false;
}
var today = new Date();
if (dateInfo.isPm === true && dateInfo.hour != null && +dateInfo.hour !== 12) {
dateInfo.hour = +dateInfo.hour + 12;
} else if (dateInfo.isPm === false && +dateInfo.hour === 12) {
dateInfo.hour = 0;
}
var date;
if (dateInfo.timezoneOffset != null) {
dateInfo.minute = +(dateInfo.minute || 0) - +dateInfo.timezoneOffset;
date = new Date(Date.UTC(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1,
dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0));
} else {
date = new Date(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1,
dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0);
}
return date;
};
/* istanbul ignore next */
if (typeof module !== 'undefined' && module.exports) {
module.exports = fecha;
} else if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return fecha;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
main.fecha = fecha;
}
})(this);
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var canUseDOM = __webpack_require__(40);
var one = function one() {};
var on = function on() {};
var off = function off() {};
if (canUseDOM) {
var bind = window.addEventListener ? 'addEventListener' : 'attachEvent';
var unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent';
var prefix = bind !== 'addEventListener' ? 'on' : '';
one = function one(node, eventNames, eventListener) {
var typeArray = eventNames.split(' ');
var recursiveFunction = function recursiveFunction(e) {
e.target.removeEventListener(e.type, recursiveFunction);
return eventListener(e);
};
for (var i = typeArray.length - 1; i >= 0; i--) {
this.on(node, typeArray[i], recursiveFunction);
}
};
/**
* Bind `node` event `eventName` to `eventListener`.
*
* @param {Element} node
* @param {String} eventName
* @param {Function} eventListener
* @param {Boolean} capture
* @return {Obejct}
* @api public
*/
on = function on(node, eventName, eventListener, capture) {
node[bind](prefix + eventName, eventListener, capture || false);
return {
off: function off() {
node[unbind](prefix + eventName, eventListener, capture || false);
}
};
};
/**
* Unbind `node` event `eventName`'s callback `eventListener`.
*
* @param {Element} node
* @param {String} eventName
* @param {Function} eventListener
* @param {Boolean} capture
* @return {Function}
* @api public
*/
off = function off(node, eventName, eventListener, capture) {
node[unbind](prefix + eventName, eventListener, capture || false);
return eventListener;
};
}
module.exports = {
one: one,
on: on,
off: off
};
/***/ },
/* 54 */
/***/ function(module, exports) {
'use strict';
module.exports = function (node, tree) {
while (node) {
if (node === tree) {
return true;
}
node = node.parentNode;
}
return false;
};
/***/ },
/* 55 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var fecha = __webpack_require__(52);
var ClassNameMixin = __webpack_require__(4);
var Icon = __webpack_require__(23);
var DatePicker = __webpack_require__(56);
var TimePicker = __webpack_require__(58);
var DateTimePicker = React.createClass({
displayName: 'DateTimePicker',
mixins: [ClassNameMixin],
propTypes: {
showTimePicker: React.PropTypes.bool,
showDatePicker: React.PropTypes.bool,
caretDisplayed: React.PropTypes.bool,
amStyle: React.PropTypes.oneOf(['success', 'danger', 'warning']),
viewMode: React.PropTypes.string,
minViewMode: React.PropTypes.string,
onSelect: React.PropTypes.func.isRequired,
onClose: React.PropTypes.func,
daysOfWeekDisabled: React.PropTypes.array,
format: React.PropTypes.string,
dateTime: React.PropTypes.string,
locale: React.PropTypes.string,
weekStart: React.PropTypes.number,
minDate: React.PropTypes.string,
maxDate: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker',
dateTime: '',
format: 'YYYY-MM-DD HH:mm',
showTimePicker: true,
showDatePicker: true,
caretDisplayed: true
};
},
getInitialState: function getInitialState() {
var showToggle;
var showTimePicker;
if (this.props.showTimePicker && this.props.showDatePicker) {
showToggle = true;
showTimePicker = false;
}
if (!showToggle && !this.props.showDatePicker) {
showTimePicker = true;
}
// `fecha.parse` return `false` when passed invalid parameter
// fixes: https://github.com/amazeui/amazeui-react/issues/119
var date = fecha.parse(this.props.dateTime, this.props.format);
!date && (date = new Date());
return {
showTimePicker: showTimePicker,
showDatePicker: this.props.showDatePicker,
caretDisplayed: this.props.caretDisplayed,
showToggle: showToggle,
date: date,
toggleDisplay: {
toggleTime: {
display: 'block'
},
toggleDate: {
display: 'none'
}
}
};
},
handleToggleTime: function handleToggleTime() {
this.setState({
showDatePicker: false,
showTimePicker: true,
toggleDisplay: {
toggleTime: {
display: 'none'
},
toggleDate: {
display: 'block'
}
}
});
},
handleToggleDate: function handleToggleDate() {
this.setState({
showDatePicker: true,
showTimePicker: false,
toggleDisplay: {
toggleTime: {
display: 'block'
},
toggleDate: {
display: 'none'
}
}
});
},
handleSelect: function handleSelect(date) {
this.setState({
date: date
});
this.props.onSelect(fecha.format(date, this.props.format));
},
renderToggleTime: function renderToggleTime() {
if (this.state.showToggle) {
return React.createElement(
'div',
{
style: this.state.toggleDisplay.toggleTime,
className: this.prefixClass('toggle'),
onClick: this.handleToggleTime
},
React.createElement(Icon, { icon: 'clock-o' })
);
}
},
renderToggleDate: function renderToggleDate() {
if (this.state.showToggle) {
return React.createElement(
'div',
{
style: this.state.toggleDisplay.toggleDate,
className: this.prefixClass('toggle'),
onClick: this.handleToggleDate
},
React.createElement(Icon, { icon: 'calendar' })
);
}
},
renderDatePicker: function renderDatePicker() {
if (this.state.showDatePicker) {
return React.createElement(DatePicker, {
onSelect: this.handleSelect,
onClose: this.props.onClose,
weekStart: this.props.weekStart,
viewMode: this.props.viewMode,
minViewMode: this.props.minViewMode,
daysOfWeekDisabled: this.props.daysOfWeekDisabled,
format: this.props.format,
date: this.state.date,
locale: this.props.locale,
minDate: this.props.minDate,
maxDate: this.props.maxDate
});
}
},
renderTimePicker: function renderTimePicker() {
if (this.state.showTimePicker) {
return React.createElement(TimePicker, {
onSelect: this.handleSelect,
date: this.state.date,
format: this.props.format
});
}
},
renderCaret: function renderCaret() {
if (this.state.caretDisplayed) {
return React.createElement('div', { className: this.prefixClass('caret') });
}
},
render: function render() {
var classSet = this.getClassSet();
this.props.amStyle && (classSet[this.prefixClass(this.props.amStyle)] = true);
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(classSet, this.props.className)
}),
this.renderCaret(),
React.createElement(
'div',
{ className: this.prefixClass('date') },
this.renderDatePicker()
),
React.createElement(
'div',
{ className: this.prefixClass('time') },
this.renderTimePicker()
),
this.renderToggleTime(),
this.renderToggleDate()
);
}
});
module.exports = DateTimePicker;
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var classNames = __webpack_require__(3);
var fecha = __webpack_require__(52);
var ClassNameMixin = __webpack_require__(4);
var dateUtils = __webpack_require__(57);
var DatePicker = React.createClass({
displayName: 'DatePicker',
mixins: [ClassNameMixin],
propTypes: {
onSelect: React.PropTypes.func.isRequired,
onClose: React.PropTypes.func,
viewMode: React.PropTypes.string,
minViewMode: React.PropTypes.string,
daysOfWeekDisabled: React.PropTypes.array,
format: React.PropTypes.string,
date: React.PropTypes.object,
weekStart: React.PropTypes.number,
minDate: React.PropTypes.string,
maxDate: React.PropTypes.string,
locale: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker',
date: new Date(),
daysOfWeekDisabled: [],
viewMode: 'days',
minViewMode: 'days',
format: 'YYYY-MM-DD',
displayed: {
days: { display: 'block' },
months: { display: 'none' },
years: { display: 'none' }
}
};
},
getInitialState: function getInitialState() {
var displayed;
switch (this.props.viewMode) {
case 'days':
displayed = {
days: { display: 'block' },
months: { display: 'none' },
years: { display: 'none' }
};
break;
case 'months':
displayed = {
days: { display: 'none' },
months: { display: 'block' },
years: { display: 'none' }
};
break;
case 'years':
displayed = {
days: { display: 'none' },
months: { display: 'none' },
years: { display: 'block' }
};
break;
}
return {
locale: dateUtils.getLocale(this.props.locale),
viewDate: this.props.date,
selectedDate: this.props.date,
displayed: displayed
};
},
// DaysPicker props function
subtractMonth: function subtractMonth() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setMonth(viewDate.getMonth() - 1);
this.setState({
viewDate: newDate
});
},
addMonth: function addMonth() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setMonth(viewDate.getMonth() + 1);
this.setState({
viewDate: newDate
});
},
setSelectedDate: function setSelectedDate(event) {
if (/disabled/ig.test(event.target.className)) {
return;
}
var viewDate = this.state.viewDate;
if (/new/ig.test(event.target.className)) {
viewDate.setMonth(viewDate.getMonth() + 1);
} else if (/old/ig.test(event.target.className)) {
viewDate.setMonth(viewDate.getMonth() - 1);
}
viewDate.setDate(event.target.innerHTML);
this.setViewDate(viewDate);
},
setViewDate: function setViewDate(viewDate) {
this.setState({
viewDate: viewDate,
selectedDate: new Date(viewDate.valueOf())
}, function () {
this.props.onSelect(this.state.selectedDate);
this.props.onClose && this.props.onClose();
});
},
showMonths: function showMonths() {
return this.setState({
displayed: {
days: { display: 'none' },
months: { display: 'block' },
years: { display: 'none' }
}
});
},
// MonthsPicker props function
subtractYear: function subtractYear() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() - 1);
return this.setState({
viewDate: newDate
});
},
addYear: function addYear() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() + 1);
return this.setState({
viewDate: newDate
});
},
showYears: function showYears() {
return this.setState({
displayed: {
days: { display: 'none' },
months: { display: 'none' },
years: { display: 'block' }
}
});
},
setViewMonth: function setViewMonth(event) {
var viewDate = this.state.viewDate;
var month = event.target.innerHTML;
var months = this.state.locale.monthsShort;
var i = 0;
var len = months.length;
for (; i < len; i++) {
if (month === months[i]) {
viewDate.setMonth(i);
}
}
if (this.props.minViewMode === 'months') {
this.setViewDate(viewDate);
}
this.setState({
viewDate: viewDate,
displayed: {
days: { display: 'block' },
months: { display: 'none' },
years: { display: 'none' }
}
});
},
// YearsPicker props function
setViewYear: function setViewYear(event) {
var year = event.target.innerHTML;
var viewDate = this.state.viewDate;
viewDate.setFullYear(year);
if (this.props.minViewMode === 'years') {
this.setViewDate(viewDate);
}
this.setState({
viewDate: viewDate,
displayed: {
days: { display: 'none' },
months: { display: 'block' },
years: { display: 'none' }
}
});
},
addDecade: function addDecade() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() + 10);
this.setState({
viewDate: newDate
});
},
subtractDecade: function subtractDecade() {
var viewDate = this.state.viewDate;
var newDate = new Date(viewDate.valueOf());
newDate.setFullYear(viewDate.getFullYear() - 10);
this.setState({
viewDate: newDate
});
},
// render children
renderDays: function renderDays() {
return React.createElement(DaysPicker, {
style: this.state.displayed.days,
selectedDate: this.state.selectedDate,
viewDate: this.state.viewDate,
subtractMonth: this.subtractMonth,
addMonth: this.addMonth,
setSelectedDate: this.setSelectedDate,
showMonths: this.showMonths,
format: this.props.format,
locale: this.state.locale,
weekStart: this.props.weekStart,
daysOfWeekDisabled: this.props.daysOfWeekDisabled,
minDate: this.props.minDate,
maxDate: this.props.maxDate
});
},
renderMonths: function renderMonths() {
return React.createElement(MonthsPicker, {
style: this.state.displayed.months,
locale: this.state.locale,
addYear: this.addYear,
subtractYear: this.subtractYear,
viewDate: this.state.viewDate,
selectedDate: this.state.selectedDate,
showYears: this.showYears,
setViewMonth: this.setViewMonth });
},
renderYears: function renderYears() {
return React.createElement(YearsPicker, {
style: this.state.displayed.years,
viewDate: this.state.viewDate,
selectDate: this.state.selectedDate,
setViewYear: this.setViewYear,
addDecade: this.addDecade,
subtractDecade: this.subtractDecade });
},
render: function render() {
return React.createElement(
'div',
{ className: this.prefixClass('body') },
this.renderDays(),
this.renderMonths(),
this.renderYears()
);
}
});
var DaysPicker = React.createClass({
displayName: 'DaysPicker',
mixins: [ClassNameMixin],
propTypes: {
subtractMonth: React.PropTypes.func.isRequired,
addMonth: React.PropTypes.func.isRequired,
setSelectedDate: React.PropTypes.func.isRequired,
selectedDate: React.PropTypes.object.isRequired,
viewDate: React.PropTypes.object.isRequired,
showMonths: React.PropTypes.func.isRequired,
locale: React.PropTypes.object,
weekStart: React.PropTypes.number,
daysOfWeekDisabled: React.PropTypes.array,
minDate: React.PropTypes.string,
maxDate: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
renderDays: function renderDays() {
var row;
var i;
var _ref;
var _i;
var _len;
var prevY;
var prevM;
var classes = {};
var html = [];
var cells = [];
var weekStart = this.props.weekStart || this.props.locale.weekStart;
var weekEnd = (weekStart + 6) % 7;
var d = this.props.viewDate;
var year = d.getFullYear();
var month = d.getMonth();
var selectedDate = this.props.selectedDate;
var currentDate = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), selectedDate.getDate(), 0, 0, 0, 0).valueOf();
var prevMonth = new Date(year, month - 1, 28, 0, 0, 0, 0);
var day = dateUtils.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
prevMonth.setDate(day);
prevMonth.setDate(day - (prevMonth.getDay() - weekStart + 7) % 7);
var nextMonth = new Date(prevMonth);
nextMonth.setDate(nextMonth.getDate() + 42);
nextMonth = nextMonth.valueOf();
var minDate = this.props.minDate && fecha.parse(this.props.minDate);
var maxDate = this.props.maxDate && fecha.parse(this.props.maxDate);
while (prevMonth.valueOf() < nextMonth) {
classes[this.prefixClass('day')] = true;
prevY = prevMonth.getFullYear();
prevM = prevMonth.getMonth();
// set className old new
if (prevM < month && prevY === year || prevY < year) {
classes[this.prefixClass('old')] = true;
} else if (prevM > month && prevY === year || prevY > year) {
classes[this.prefixClass('new')] = true;
}
// set className active
if (prevMonth.valueOf() === currentDate) {
classes[this.setClassNamespace('active')] = true;
}
// set className disabled
if (minDate && prevMonth.valueOf() < minDate || maxDate && prevMonth.valueOf() > maxDate) {
classes[this.setClassNamespace('disabled')] = true;
}
// week disabled
if (this.props.daysOfWeekDisabled) {
_ref = this.props.daysOfWeekDisabled;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
if (prevMonth.getDay() === this.props.daysOfWeekDisabled[i]) {
classes[this.setClassNamespace('disabled')] = true;
break;
}
}
}
cells.push(React.createElement(
'td',
{
key: prevMonth.getMonth() + '-' + prevMonth.getDate(),
className: classNames(classes),
onClick: this.props.setSelectedDate
},
prevMonth.getDate()
));
// add tr
if (prevMonth.getDay() === weekEnd) {
row = React.createElement(
'tr',
{ key: prevMonth.getMonth() + '-' + prevMonth.getDate() },
cells
);
html.push(row);
cells = [];
}
classes = {};
prevMonth.setDate(prevMonth.getDate() + 1);
}
return html;
},
renderWeek: function renderWeek() {
var ths = [];
var locale = this.props.locale;
var weekStart = this.props.weekStart || this.props.locale.weekStart;
var weekEnd = weekStart + 7;
while (weekStart < weekEnd) {
ths.push(React.createElement(
'th',
{ key: weekStart, className: this.prefixClass('dow') },
locale.daysMin[weekStart++ % 7]
));
}
return React.createElement(
'tr',
null,
ths
);
},
render: function render() {
var viewDate = this.props.viewDate;
var prefixClass = this.prefixClass;
var locale = this.props.locale;
return React.createElement(
'div',
{
className: prefixClass('days'),
style: this.props.style },
React.createElement(
'table',
{ className: prefixClass('table') },
React.createElement(
'thead',
null,
React.createElement(
'tr',
{ className: prefixClass('header') },
React.createElement(
'th',
{ className: prefixClass('prev'), onClick: this.props.subtractMonth },
React.createElement('i', { className: prefixClass('prev-icon') })
),
React.createElement(
'th',
{
className: prefixClass('switch'),
colSpan: '5',
onClick: this.props.showMonths
},
React.createElement(
'div',
{ className: this.prefixClass('select') },
locale.monthsShort[viewDate.getMonth()],
viewDate.getFullYear()
)
),
React.createElement(
'th',
{ className: prefixClass('next'), onClick: this.props.addMonth },
React.createElement('i', { className: prefixClass('next-icon') })
)
),
this.renderWeek()
),
React.createElement(
'tbody',
null,
this.renderDays()
)
)
);
}
});
var MonthsPicker = React.createClass({
displayName: 'MonthsPicker',
mixins: [ClassNameMixin],
propTypes: {
locale: React.PropTypes.object,
subtractYear: React.PropTypes.func.isRequired,
addYear: React.PropTypes.func.isRequired,
viewDate: React.PropTypes.object.isRequired,
selectedDate: React.PropTypes.object.isRequired,
showYears: React.PropTypes.func.isRequired,
setViewMonth: React.PropTypes.func.isRequired,
minDate: React.PropTypes.string,
maxDate: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
renderMonths: function renderMonths() {
var classes = {};
var month = this.props.selectedDate.getMonth();
var year = this.props.selectedDate.getFullYear();
var i = 0;
var months = [];
var minDate = this.props.minDate && fecha.parse(this.props.minDate);
var maxDate = this.props.maxDate && fecha.parse(this.props.maxDate);
var prevMonth = new Date(year, month);
// TODO: minDate maxDate months
while (i < 12) {
classes[this.prefixClass('month')] = true;
if (this.props.viewDate.getFullYear() === this.props.selectedDate.getFullYear() && i === month) {
classes[this.setClassNamespace('active')] = true;
}
// set className disabled
if (minDate && prevMonth.valueOf() < minDate || maxDate && prevMonth.valueOf() > maxDate) {
classes[this.setClassNamespace('disabled')] = true;
}
months.push(React.createElement(
'span',
{
className: classNames(classes),
onClick: this.props.setViewMonth,
key: i },
this.props.locale.monthsShort[i]
));
classes = {};
i++;
}
return months;
},
render: function render() {
return React.createElement(SubPicker, {
displayName: 'months',
style: this.props.style,
subtract: this.props.subtractYear,
add: this.props.addYear,
showFunc: this.props.showYears,
showText: this.props.viewDate.getFullYear(),
body: this.renderMonths() });
}
});
var YearsPicker = React.createClass({
displayName: 'YearsPicker',
mixins: [ClassNameMixin],
propTypes: {
viewDate: React.PropTypes.object.isRequired,
selectDate: React.PropTypes.object.isRequired,
subtractDecade: React.PropTypes.func.isRequired,
addDecade: React.PropTypes.func.isRequired,
setViewYear: React.PropTypes.func.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
renderYears: function renderYears() {
var classes = {};
var years = [];
var i = -1;
var year = parseInt(this.props.viewDate.getFullYear() / 10, 10) * 10;
year--;
while (i < 11) {
classes[this.prefixClass('year')] = true;
if (i === -1 || i === 10) {
classes[this.prefixClass('old')] = true;
}
if (this.props.selectDate.getFullYear() === year) {
classes[this.setClassNamespace('active')] = true;
}
years.push(React.createElement(
'span',
{
className: classNames(classes),
onClick: this.props.setViewYear,
key: year },
year
));
classes = {};
year++;
i++;
}
return years;
},
render: function render() {
var year = parseInt(this.props.viewDate.getFullYear() / 10, 10) * 10;
var addYear = year + 9;
var showYear = year + '-' + addYear;
return React.createElement(SubPicker, {
displayName: 'years',
style: this.props.style,
subtract: this.props.subtractDecade,
add: this.props.addDecade,
showText: showYear,
body: this.renderYears() });
}
});
var SubPicker = React.createClass({
displayName: 'SubPicker',
mixins: [ClassNameMixin],
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
render: function render() {
var prefixClass = this.prefixClass;
return React.createElement(
'div',
{
className: prefixClass(this.props.displayName),
style: this.props.style },
React.createElement(
'table',
{ className: prefixClass('table') },
React.createElement(
'thead',
null,
React.createElement(
'tr',
{ className: prefixClass('header') },
React.createElement(
'th',
{ className: prefixClass('prev'), onClick: this.props.subtract },
React.createElement('i', { className: prefixClass('prev-icon') })
),
React.createElement(
'th',
{
className: prefixClass('switch'),
colSpan: '5',
onClick: this.props.showFunc },
React.createElement(
'div',
{ className: this.prefixClass('select') },
this.props.showText
)
),
React.createElement(
'th',
{ className: prefixClass('next'), onClick: this.props.add },
React.createElement('i', { className: prefixClass('next-icon') })
)
)
),
React.createElement(
'tbody',
null,
React.createElement(
'tr',
null,
React.createElement(
'td',
{ colSpan: '7' },
this.props.body
)
)
)
)
);
}
});
module.exports = DatePicker;
/***/ },
/* 57 */
/***/ function(module, exports) {
'use strict';
var locales = {
'en_US': {
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
daysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
daysMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
today: 'Today',
weekStart: 0
},
'zh_CN': {
days: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
daysShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
daysMin: ['日', '一', '二', '三', '四', '五', '六'],
months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
monthsShort: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
today: '今天',
weekStart: 0
}
};
var dateUtils = {
isLeapYear: function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
},
getDaysInMonth: function getDaysInMonth(year, month) {
return [31, this.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
getLocale: function getLocale(locale) {
if (!locale && navigator && navigator.language) {
locale = navigator.language.split('-');
locale[1] = locale[1].toUpperCase();
locale = locale.join('_');
}
return locales[locale] || locales['zh_CN'];
}
};
module.exports = dateUtils;
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var TimePicker = React.createClass({
displayName: 'TimePicker',
mixins: [ClassNameMixin],
propTypes: {
onSelect: React.PropTypes.func.isRequired,
date: React.PropTypes.object,
format: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker',
format: 'HH:mm'
};
},
getInitialState: function getInitialState() {
return {
viewDate: this.props.date,
selectedDate: this.props.date,
displayed: {
times: { display: 'block' },
minutes: { display: 'none' },
hours: { display: 'none' }
}
};
},
// Minutes
addMinute: function addMinute() {
var viewDate = this.state.viewDate;
viewDate.setMinutes(viewDate.getMinutes() + 1);
this.setTime(viewDate);
},
subtractMinute: function subtractMinute() {
var viewDate = this.state.viewDate;
viewDate.setMinutes(viewDate.getMinutes() - 1);
this.setTime(viewDate);
},
setTime: function setTime(viewDate) {
this.setState({
viewDate: viewDate,
selectedDate: new Date(viewDate.valueOf())
}, function () {
this.props.onSelect(this.state.selectedDate);
});
},
// set Minutes
setSelectedMinute: function setSelectedMinute(event) {
var viewDate = this.state.viewDate;
var minute = parseInt(event.target.innerHTML.split(':')[1]);
viewDate.setMinutes(minute);
this.setTime(viewDate);
this.setState({
displayed: {
times: { display: 'block' },
minutes: { display: 'none' },
hours: { display: 'none' }
}
});
},
showMinutes: function showMinutes() {
this.setState({
displayed: {
times: { display: 'none' },
minutes: { display: 'block' },
hours: { display: 'none' }
}
});
},
// Hours
showHours: function showHours() {
this.setState({
displayed: {
times: { display: 'none' },
minutes: { display: 'none' },
hours: { display: 'block' }
}
});
},
setSelectedHour: function setSelectedHour(event) {
var viewDate = this.state.viewDate;
var hour = parseInt(event.target.innerHTML);
viewDate.setHours(hour);
this.setTime(viewDate);
this.setState({
displayed: {
times: { display: 'block' },
minutes: { display: 'none' },
hours: { display: 'none' }
}
});
},
addHour: function addHour() {
var viewDate = this.state.viewDate;
viewDate.setHours(viewDate.getHours() + 1);
this.setTime(viewDate);
},
subtractHour: function subtractHour() {
var viewDate = this.state.viewDate;
viewDate.setHours(viewDate.getHours() - 1);
this.setTime(viewDate);
},
showTimeText: function showTimeText() {
var hour = this.state.viewDate.getHours();
var minute = this.state.viewDate.getMinutes();
if (minute < 10) {
minute = '0' + minute;
}
if (hour < 10) {
hour = '0' + hour;
}
return {
hour: hour,
minute: minute
};
},
renderHours: function renderHours() {
var time = this.showTimeText().hour + ':' + this.showTimeText().minute;
return React.createElement(HoursPicker, {
style: this.state.displayed.hours,
setSelectedHour: this.setSelectedHour,
selectedDate: this.state.selectedDate,
addHour: this.addHour,
subtractHour: this.subtractHour,
showTime: time
});
},
renderMinutes: function renderMinutes() {
var time = this.showTimeText().hour + ':' + this.showTimeText().minute;
return React.createElement(MinutesPicker, {
style: this.state.displayed.minutes,
setSelectedMinute: this.setSelectedMinute,
selectedDate: this.state.selectedDate,
addMinute: this.addMinute,
subtractMinute: this.subtractMinute,
showTime: time
});
},
render: function render() {
var time = this.showTimeText();
var content = React.createElement(
'div',
{ className: this.prefixClass('time-box') },
React.createElement(
'strong',
{ onClick: this.showHours },
time.hour
),
React.createElement(
'em',
null,
':'
),
React.createElement(
'strong',
{ onClick: this.showMinutes },
time.minute
)
);
return React.createElement(
'div',
{ className: this.prefixClass('body') },
React.createElement(SubPicker, {
style: this.state.displayed.times,
displayName: 'time-wrapper',
body: content,
add: this.addMinute,
subtract: this.subtractMinute,
showFunc: this.props.showDate,
showText: 'today'
}),
this.renderHours(),
this.renderMinutes()
);
}
});
var HoursPicker = React.createClass({
displayName: 'HoursPicker',
mixins: [ClassNameMixin],
propTypes: {
setSelectedHour: React.PropTypes.func.isRequired,
selectedDate: React.PropTypes.object.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
renderHour: function renderHour() {
var classes;
var hour = this.props.selectedDate.getHours();
var i = 0;
var hours = [];
while (i < 24) {
classes = {};
classes[this.prefixClass('hour')] = true;
if (i === hour) {
classes[this.setClassNamespace('active')] = true;
}
hours.push(React.createElement(
'span',
{
className: classNames(classes),
onClick: this.props.setSelectedHour,
key: i
},
i < 10 ? '0' + i + ':00' : i + ':00'
));
i++;
}
return hours;
},
render: function render() {
return React.createElement(SubPicker, {
displayName: 'hours',
style: this.props.style,
subtract: this.props.subtractHour,
add: this.props.addHour,
showText: this.props.showTime,
body: this.renderHour()
});
}
});
var MinutesPicker = React.createClass({
displayName: 'MinutesPicker',
mixins: [ClassNameMixin],
propTypes: {
setSelectedMinute: React.PropTypes.func.isRequired,
selectedDate: React.PropTypes.object.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
renderMinute: function renderMinute() {
var classes;
var minute = this.props.selectedDate.getMinutes();
var hour = this.props.selectedDate.getHours();
var i = 0;
var minutes = [];
while (i < 60) {
classes = {};
classes[this.prefixClass('minute')] = true;
if (i === minute) {
classes[this.setClassNamespace('active')] = true;
}
if (i % 5 === 0) {
minutes.push(React.createElement(
'span',
{
className: classNames(classes),
onClick: this.props.setSelectedMinute,
key: i
},
i < 10 ? hour + ':0' + i : hour + ':' + i
));
}
i++;
}
return minutes;
},
render: function render() {
return React.createElement(SubPicker, {
displayName: 'minutes',
style: this.props.style,
subtract: this.props.subtractMinute,
add: this.props.addMinute,
showText: this.props.showTime,
body: this.renderMinute()
});
}
});
var SubPicker = React.createClass({
displayName: 'SubPicker',
mixins: [ClassNameMixin],
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'datepicker'
};
},
render: function render() {
var prefixClass = this.prefixClass;
return React.createElement(
'div',
{
className: prefixClass(this.props.displayName),
style: this.props.style },
React.createElement(
'table',
{ className: prefixClass('table') },
React.createElement(
'thead',
null,
React.createElement(
'tr',
{ className: prefixClass('header') },
React.createElement(
'th',
{ className: prefixClass('prev'), onClick: this.props.subtract },
React.createElement('i', { className: prefixClass('prev-icon') })
),
React.createElement(
'th',
{
className: prefixClass('switch'),
colSpan: '5',
onClick: this.props.showFunc
},
React.createElement(
'div',
{ className: this.prefixClass('select') },
this.props.showText
)
),
React.createElement(
'th',
{ className: prefixClass('next'), onClick: this.props.add },
React.createElement('i', { className: prefixClass('next-icon') })
)
)
),
React.createElement(
'tbody',
null,
React.createElement(
'tr',
null,
React.createElement(
'td',
{ colSpan: '7' },
this.props.body
)
)
)
)
);
}
});
module.exports = TimePicker;
/***/ },
/* 59 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var assign = __webpack_require__(31);
var ClassNameMixin = __webpack_require__(4);
var constants = __webpack_require__(5);
var Button = __webpack_require__(9);
var Icon = __webpack_require__(23);
var Events = __webpack_require__(53);
var isNodeInTree = __webpack_require__(54);
var createChainedFunction = __webpack_require__(35);
var canUseDOM = __webpack_require__(40);
var Dropdown = React.createClass({
displayName: 'Dropdown',
mixins: [ClassNameMixin],
propTypes: {
title: React.PropTypes.node.isRequired,
dropup: React.PropTypes.bool,
navItem: React.PropTypes.bool,
btnStyle: React.PropTypes.string,
btnSize: React.PropTypes.string,
btnInlineStyle: React.PropTypes.object,
contentInlineStyle: React.PropTypes.object,
contentComponent: React.PropTypes.node,
toggleClassName: React.PropTypes.string,
caretClassName: React.PropTypes.string,
contentClassName: React.PropTypes.string,
onOpen: React.PropTypes.func, // open callback
onClose: React.PropTypes.func // close callback
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'dropdown',
contentComponent: 'ul'
};
},
getInitialState: function getInitialState() {
return {
open: false
};
},
componentWillMount: function componentWillMount() {
this.unbindOuterHandlers();
},
componentWillUnmount: function componentWillUnmount() {
this.unbindOuterHandlers();
},
/**
* setDropdown
* @param {bool} isOpen - Dropdown state, `true` -> open, `close` -> false
* @param {function} [callback]
*/
setDropdown: function setDropdown(isOpen, callback) {
if (isOpen) {
this.bindOuterHandlers();
} else {
this.unbindOuterHandlers();
}
this.setState({
open: isOpen
}, function () {
callback && callback();
isOpen && this.props.onOpen && this.props.onOpen();
!isOpen && this.props.onClose && this.props.onClose();
});
},
// close dropdown on `esc` keyup
handleKeyup: function handleKeyup(e) {
e.keyCode === 27 && this.setDropdown(false);
},
// close dropdown when click outer dropdown
handleOuterClick: function handleOuterClick(e) {
if (isNodeInTree(e.target, ReactDOM.findDOMNode(this))) {
return false;
}
this.setDropdown(false);
},
bindOuterHandlers: function bindOuterHandlers() {
if (canUseDOM) {
Events.on(document, 'click', this.handleOuterClick);
Events.on(document, 'keyup', this.handleKeyup);
}
},
unbindOuterHandlers: function unbindOuterHandlers() {
if (canUseDOM) {
Events.off(document, 'click', this.handleOuterClick);
Events.off(document, 'keyup', this.handleKeyup);
}
},
handleDropdownClick: function handleDropdownClick(e) {
e.preventDefault();
this.setDropdown(!this.state.open);
},
renderChildren: function renderChildren() {
var _this = this;
return React.Children.map(this.props.children, function (child, index) {
if (React.isValidElement(child)) {
var closeOnClick = child.props.closeOnClick;
var onClick = child.props.onClick;
var handleClick = closeOnClick ? createChainedFunction(onClick, function () {
_this.setDropdown(false);
}) : onClick;
return React.cloneElement(child, assign({}, child.props, {
key: 'dropdownItem-' + index,
onClick: handleClick
}));
}
});
},
render: function render() {
var classSet = this.getClassSet();
var Component = this.props.navItem ? 'li' : 'div';
var btnClassPrefix = this.props.navItem ? '' : 'btn';
var btnComponent = this.props.navItem ? 'a' : null;
var caret = React.createElement(Icon, {
className: this.props.caretClassName,
icon: 'caret-' + (this.props.dropup ? 'up' : 'down')
});
var animation = this.state.open ? this.setClassNamespace('animation-slide-top-fixed') : this.setClassNamespace('dropdown-animation');
var ContentComponent = this.props.contentComponent;
classSet[constants.CLASSES.active] = this.state.open;
classSet[this.prefixClass('up')] = this.props.dropup;
return React.createElement(
Component,
{
btnStyle: null,
className: classNames(this.props.className, classSet)
},
React.createElement(
Button,
{
onClick: this.handleDropdownClick,
amStyle: this.props.btnStyle,
amSize: this.props.btnSize,
style: this.props.btnInlineStyle,
className: classNames(this.prefixClass('toggle'), this.props.toggleClassName),
classPrefix: btnClassPrefix,
component: btnComponent,
ref: 'dropdownToggle'
},
this.props.title,
' ',
caret
),
React.createElement(
ContentComponent,
{
ref: 'dropdownContent',
style: this.props.contentInlineStyle,
className: classNames(this.prefixClass('content'), animation, this.props.contentClassName)
},
this.renderChildren()
)
);
}
});
Dropdown.Item = React.createClass({
displayName: 'Item',
mixins: [ClassNameMixin],
propTypes: {
closeOnClick: React.PropTypes.bool,
href: React.PropTypes.string,
target: React.PropTypes.string,
title: React.PropTypes.string,
header: React.PropTypes.bool,
divider: React.PropTypes.bool,
linkComponent: React.PropTypes.any,
linkProps: React.PropTypes.object
},
render: function render() {
var classSet = this.getClassSet();
var children = null;
classSet[this.setClassNamespace('dropdown-header')] = this.props.header;
if (this.props.header) {
children = this.props.children;
} else if (!this.props.divider) {
var Component = this.props.linkComponent || 'a';
children = React.createElement(
Component,
_extends({
onClick: this.handleClick,
href: this.props.href,
target: this.props.target,
title: this.props.title
}, this.props.linkProps),
this.props.children
);
}
return React.createElement(
'li',
_extends({}, this.props, {
title: null,
href: null,
className: classNames(this.props.className, classSet)
}),
children
);
}
});
module.exports = Dropdown;
/*
* TODO:
* 1. 关闭动画
* 2. 位置检测/宽度适应
* */
/***/ },
/* 60 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var DimmerMixin = __webpack_require__(61);
var Events = __webpack_require__(53);
var Close = __webpack_require__(43);
var Icon = __webpack_require__(23);
var Modal = React.createClass({
displayName: 'Modal',
mixins: [ClassNameMixin, DimmerMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
type: React.PropTypes.oneOf(['alert', 'confirm', 'prompt', 'loading', 'actions', 'popup']),
title: React.PropTypes.node,
confirmText: React.PropTypes.string,
cancelText: React.PropTypes.string,
closeIcon: React.PropTypes.bool,
closeViaDimmer: React.PropTypes.bool,
onRequestClose: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'modal',
closeIcon: true,
confirmText: '确定',
cancelText: '取消',
onRequestClose: function onRequestClose() {}
};
},
getInitialState: function getInitialState() {
return {
transitioning: false
};
},
componentDidMount: function componentDidMount() {
this._documentKeyupListener = Events.on(document, 'keyup', this.handleDocumentKeyUp, false);
this.setDimmerContainer();
// TODO: 何为添加动画效果的最佳时机? render 完成以后添加动画 Class?
this.setState({
transitioning: true
});
},
componentWillUnmount: function componentWillUnmount() {
this._documentKeyupListener.off();
this.resetDimmerContainer();
},
handleDimmerClick: function handleDimmerClick() {
if (this.props.closeViaDimmer) {
this.props.onRequestClose();
}
},
handleBackdropClick: function handleBackdropClick(e) {
if (e.target !== e.currentTarget) {
return;
}
this.props.onRequestClose();
},
handleDocumentKeyUp: function handleDocumentKeyUp(e) {
if (!this.props.keyboard && e.keyCode === 27) {
this.props.onRequestClose();
}
},
isPopup: function isPopup() {
return this.props.type === 'popup';
},
isActions: function isActions() {
return this.props.type === 'actions';
},
// Get input data for prompt modal
getPromptData: function getPromptData() {
var data = [];
var inputs = ReactDOM.findDOMNode(this).querySelectorAll('input');
if (inputs) {
var i = 0;
for (; i < inputs.length; i++) {
data.push(inputs[i].value);
}
}
return data.length === 0 ? null : data.length === 1 ? data[0] : data;
},
handleConfirm: function handleConfirm(e) {
var data = e;
if (this.props.type === 'prompt') {
data = this.getPromptData();
}
this.props.onConfirm(data);
},
renderActions: function renderActions() {
return React.createElement(
'div',
{
style: { display: 'block' },
className: classNames(this.props.className, this.setClassNamespace('modal-actions'), this.setClassNamespace('modal-active'))
},
this.props.children
);
},
renderPopup: function renderPopup() {
return React.createElement(
'div',
{
style: { display: 'block' },
className: classNames(this.props.className, this.setClassNamespace('popup'), this.setClassNamespace('modal-active'))
},
React.createElement(
'div',
{ className: this.setClassNamespace('popup-inner') },
React.createElement(
'div',
{ className: this.setClassNamespace('popup-hd') },
this.props.title ? React.createElement(
'h4',
{ className: this.setClassNamespace('popup-title') },
this.props.title
) : null,
React.createElement(Close, { onClick: this.props.onRequestClose })
),
React.createElement(
'div',
{ className: this.setClassNamespace('popup-bd') },
this.props.children
)
)
);
},
renderHeader: function renderHeader() {
var title = this.props.title;
var closeIcon = this.props.closeIcon && !this.props.type ? React.createElement(Close, {
spin: true,
onClick: this.props.onRequestClose
}) : null;
return this.props.title || closeIcon ? React.createElement(
'div',
{ className: this.prefixClass('hd') },
title ? React.createElement(
'h4',
{
className: this.setClassNamespace('margin-bottom-sm')
},
title
) : null,
closeIcon
) : null;
},
// Render alert/confirm/prompt buttons
renderFooter: function renderFooter() {
var buttons;
var btnClass = this.prefixClass('btn');
var props = this.props;
switch (this.props.type) {
case 'alert':
buttons = React.createElement(
'span',
{
onClick: this.props.onConfirm,
className: btnClass
},
this.props.confirmText
);
break;
case 'confirm':
case 'prompt':
buttons = [props.cancelText, props.confirmText].map(function (text, i) {
return React.createElement(
'span',
{
key: i,
onClick: i === 0 ? this.props.onCancel : this.handleConfirm,
className: btnClass
},
text
);
}.bind(this));
break;
default:
buttons = null;
}
return buttons ? React.createElement(
'div',
{ className: this.prefixClass('footer') },
buttons
) : null;
},
render: function render() {
if (this.isActions()) {
return this.renderDimmer(this.renderActions());
}
if (this.isPopup()) {
return this.renderDimmer(this.renderPopup());
}
var classSet = this.getClassSet();
var props = this.props;
var footer = this.renderFooter();
var style = {
display: 'block'
};
// marginLeft: props.marginLeft,
// marginTop: props.marginTop
var dialogDimension = {
width: props.modalWidth,
height: props.modalHeight
};
classSet[this.prefixClass('active')] = this.state.transitioning;
// .am-modal-no-btn -> refactor this style using `~` selector
classSet[this.prefixClass('no-btn')] = !footer;
props.type && (classSet[this.prefixClass(props.type)] = true);
var modal = React.createElement(
'div',
_extends({}, props, {
style: style,
ref: 'modal',
title: null,
className: classNames(classSet, props.className)
}),
React.createElement(
'div',
{
className: this.prefixClass('dialog'),
style: dialogDimension
},
this.renderHeader(),
React.createElement(
'div',
{
className: this.prefixClass('bd'),
ref: 'modalBody'
},
props.type === 'loading' ? props.children ? props.children : React.createElement(Icon, { icon: 'spinner', spin: true }) : props.children
),
footer
)
);
return this.renderDimmer(modal);
}
});
module.exports = Modal;
// TODO: Modal 动画效果实现
// -> 如何关闭 Loading Modal?
// -> 关闭 Modal 以后窗口滚动会原来滚动条所在位置
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var getScrollbarWidth = __webpack_require__(62);
var ownerDocument = __webpack_require__(63).ownerDocument;
var CSSCore = __webpack_require__(16);
module.exports = {
propTypes: {
container: React.PropTypes.node
},
_getContainer: function _getContainer() {
var node = this.refs.modal;
var doc = ownerDocument(node);
return this.props.container && ReactDOM.findDOMNode(this.props.container) || doc.body;
},
_getDimmerActiveClassName: function _getDimmerActiveClassName() {
return this.setClassNamespace('dimmer-active');
},
setDimmerContainer: function setDimmerContainer() {
var container = this._getContainer();
var bodyPaddingRight = parseInt(container.style.paddingRight || 0, 10);
var barWidth = getScrollbarWidth();
if (barWidth) {
container.style.paddingRight = bodyPaddingRight + barWidth + 'px';
}
CSSCore.addClass(container, this._getDimmerActiveClassName());
},
resetDimmerContainer: function resetDimmerContainer(nextProps, nextState) {
var container = this._getContainer();
CSSCore.removeClass(container, this._getDimmerActiveClassName());
container.style.paddingRight = '';
},
renderDimmer: function renderDimmer(children) {
var onClick = this.handleDimmerClick || null;
var classSet = {};
classSet[this.setClassNamespace('dimmer')] = true;
classSet[this.setClassNamespace('active')] = true;
return React.createElement(
'div',
null,
React.createElement('div', {
onClick: onClick,
ref: 'dimmer',
style: { display: 'block' },
className: classNames(classSet)
}),
children
);
}
};
/***/ },
/* 62 */
/***/ function(module, exports) {
'use strict';
/**
* getScrollbarWidth
*
* @desc via http://davidwalsh.name/detect-scrollbar-width
* @returns {number}
*/
function getScrollbarWidth() {
if (document.body.clientWidth >= window.innerWidth) {
return 0;
}
// Create the measurement node
var measure = document.createElement('div');
measure.className = 'am-scrollbar-measure';
document.body.appendChild(measure);
// Get the scrollbar width
var scrollbarWidth = measure.offsetWidth - measure.clientWidth;
// Delete the DIV
document.body.removeChild(measure);
return scrollbarWidth;
}
module.exports = getScrollbarWidth;
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
/**
* Get ownerDocument
* @param {ReactComponent|HTMLElement} componentOrElement
* @returns {HTMLDocument}
*/
function ownerDocument(componentOrElement) {
var element = ReactDOM.findDOMNode(componentOrElement);
return element && element.ownerDocument || document;
}
/**
* Get ownerWindow
* @param {HTMLElement} element
* @returns {DocumentView|Window}
* @refer https://github.com/jquery/jquery/blob/6df669f0fb87cd9975a18bf6bbe3c3548afa4fee/src/event.js#L294-L297
*/
function ownerWindow(element) {
var doc = ownerDocument(element);
return doc.defaultView || doc.parentWindow || window;
}
module.exports = {
ownerDocument: ownerDocument,
ownerWindow: ownerWindow,
scrollTop: function scrollTop(element, value) {
if (!element) {
return;
}
var hasScrollTop = 'scrollTop' in element;
if (value === undefined) {
return hasScrollTop ? element.scrollTop : element.pageYOffset;
}
hasScrollTop ? element.scrollTop = value : element.scrollTo(element.scrollX, value);
},
offset: function offset(element) {
if (element) {
var rect = element.getBoundingClientRect();
var body = document.body;
var clientTop = element.clientTop || body.clientTop || 0;
var clientLeft = element.clientLeft || body.clientLeft || 0;
var scrollTop = window.pageYOffset || element.scrollTop;
var scrollLeft = window.pageXOffset || element.scrollLeft;
return {
top: rect.top + scrollTop - clientTop,
left: rect.left + scrollLeft - clientLeft
};
}
return null;
},
position: function position(element) {
return {
left: element.offsetLeft,
top: element.offsetTop
};
}
};
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var cloneElement = React.cloneElement;
var OverlayMixin = __webpack_require__(65);
var DimmerMixin = __webpack_require__(61);
var createChainedFunction = __webpack_require__(35);
var ModalTrigger = React.createClass({
displayName: 'ModalTrigger',
mixins: [OverlayMixin, DimmerMixin],
propTypes: {
modal: React.PropTypes.node.isRequired,
onConfirm: React.PropTypes.func,
onCancel: React.PropTypes.func,
title: React.PropTypes.string,
show: React.PropTypes.bool,
onClose: React.PropTypes.func
},
getInitialState: function getInitialState() {
return {
isModalActive: false,
modalWidth: null,
modalMarginLeft: null,
modalHeight: null,
modalMarginTop: null
};
},
componentDidMount: function componentDidMount() {
if (this.props.show) {
this.open();
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.show && nextProps.show !== this.props.show) {
this.open();
}
},
open: function open() {
this.setState({
isModalActive: true
}, this.setModalStyle);
},
close: function close() {
this.setState({
isModalActive: false
});
if (this.props.onClose) {
this.props.onClose();
}
},
toggle: function toggle() {
if (this.state.isModalActive) {
this.close();
} else {
this.open();
}
},
setModalStyle: function setModalStyle() {
if (!this.isMounted()) {
return;
}
// TODO: selector
var modal = this.getOverlayDOMNode().querySelector('.am-modal');
if (!modal) {
return;
}
var style = {};
if (this.props.modalHeight) {
style.modalHeight = this.props.modalHeight;
// @since 1.1.0, requires Amaze UI 2.6.0+
// style.modalMarginTop = -this.props.height / 2;
}
/*
else {
style.modalMarginTop = -modal.offsetHeight / 2;
}
*/
if (this.props.modalWidth) {
style.modalWidth = this.props.modalWidth;
// style.modalMarginLeft = -this.props.modalWidth / 2;
}
this.setState(style);
},
// overlay is the modal
renderOverlay: function renderOverlay() {
if (!this.state.isModalActive) {
return React.createElement('span', null);
}
return cloneElement(this.props.modal, {
onRequestClose: this.close,
marginTop: this.state.modalMarginTop,
marginLeft: this.state.modalMarginLeft,
modalWidth: this.state.modalWidth,
modalHeight: this.state.modalHeight,
title: this.props.modal.props.title || this.props.title,
onConfirm: createChainedFunction(this.props.onConfirm, this.close),
onCancel: createChainedFunction(this.props.onCancel, this.close)
});
},
render: function render() {
// if "show" is defined, use "show" to control the modal
if (typeof this.props.show !== 'undefined') {
return React.createElement(
'div',
null,
' ',
this.props.children,
' '
);
}
var child = React.Children.only(this.props.children);
var props = {};
props.onClick = createChainedFunction(child.props.onClick, this.toggle);
props.onMouseOver = createChainedFunction(child.props.onMouseOver, this.props.onMouseOver);
props.onMouseOut = createChainedFunction(child.props.onMouseOut, this.props.onMouseOut);
props.onFocus = createChainedFunction(child.props.onFocus, this.props.onFocus);
props.onBlur = createChainedFunction(child.props.onBlur, this.props.onBlur);
return cloneElement(child, props);
}
});
module.exports = ModalTrigger;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
/**
* Overlay Mixin
*
* @desc `overlay` is something like Popover, Modal, etc.
* */
module.exports = {
propTypes: {
container: React.PropTypes.node
},
componentDidMount: function componentDidMount() {
this._renderOverlay();
},
componentDidUpdate: function componentDidUpdate() {
this._renderOverlay();
},
// Remove Overlay related DOM node
componentWillUnmount: function componentWillUnmount() {
this._unmountOverlay();
if (this._overlayWrapper) {
this.getContainerDOMNode().removeChild(this._overlayWrapper);
this._overlayWrapper = null;
}
},
// Create Overlay wrapper
_mountOverlayWrapper: function _mountOverlayWrapper() {
this._overlayWrapper = document.createElement('div');
this.getContainerDOMNode().appendChild(this._overlayWrapper);
},
// Render Overlay to wrapper
_renderOverlay: function _renderOverlay() {
if (!this._overlayWrapper) {
this._mountOverlayWrapper();
}
var overlay = this.renderOverlay();
if (overlay !== null) {
this._overlayInstance = ReactDOM.render(overlay, this._overlayWrapper);
} else {
// Unmount if the component is null for transitions to null
this._unmountOverlay();
}
},
// Remove a mounted Overlay from wrapper
_unmountOverlay: function _unmountOverlay() {
ReactDOM.unmountComponentAtNode(this._overlayWrapper);
this._overlayInstance = null;
},
getOverlayDOMNode: function getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to' + ' have a DOM node.');
}
if (this._overlayInstance) {
return ReactDOM.findDOMNode(this._overlayInstance);
}
return null;
},
getContainerDOMNode: function getContainerDOMNode() {
return ReactDOM.findDOMNode(this.props.container) || document.body;
}
};
/***/ },
/* 66 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Popover = React.createClass({
displayName: 'Popover',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
positionLeft: React.PropTypes.number,
positionTop: React.PropTypes.number,
amSize: React.PropTypes.oneOf(['sm', 'lg']),
amStyle: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'popover'
};
},
render: function render() {
var classSet = this.getClassSet();
var style = {
left: this.props.positionLeft,
top: this.props.positionTop,
display: 'block'
};
classSet[this.setClassNamespace('active')] = true;
classSet[this.prefixClass(this.props.placement)] = true;
return React.createElement(
'div',
_extends({}, this.props, {
style: style,
className: classNames(classSet, this.props.className)
}),
React.createElement(
'div',
{ className: this.prefixClass('inner') },
this.props.children
),
React.createElement('div', { className: this.prefixClass('caret') })
);
}
});
module.exports = Popover;
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var cloneElement = React.cloneElement;
var OverlayMixin = __webpack_require__(65);
var assign = __webpack_require__(31);
var dom = __webpack_require__(63);
var createChainedFunction = __webpack_require__(35);
function isOneOf(one, of) {
if (Array.isArray(of)) {
return of.indexOf(one) >= 0;
}
return one === of;
}
var PopoverTrigger = React.createClass({
displayName: 'PopoverTrigger',
mixins: [OverlayMixin],
propTypes: {
trigger: React.PropTypes.oneOfType([React.PropTypes.oneOf(['click', 'hover', 'focus']), React.PropTypes.arrayOf(React.PropTypes.oneOf(['click', 'hover', 'focus']))]),
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
delay: React.PropTypes.number,
delayOpen: React.PropTypes.number,
delayClose: React.PropTypes.number,
defaultPopoverActive: React.PropTypes.bool,
popover: React.PropTypes.node.isRequired
},
getDefaultProps: function getDefaultProps() {
return {
placement: 'right',
trigger: ['hover', 'focus']
};
},
getInitialState: function getInitialState() {
return {
isPopoverActive: this.props.defaultPopoverActive == null ? false : this.props.defaultPopoverActive,
popoverLeft: null,
popoverTop: null
};
},
componentDidMount: function componentDidMount() {
if (this.props.defaultPopoverActive) {
this.updatePopoverPosition();
}
},
componentWillUnmount: function componentWillUnmount() {
clearTimeout(this._hoverDelay);
},
open: function open() {
this.setState({
isPopoverActive: true
}, function () {
this.updatePopoverPosition();
});
},
close: function close() {
this.setState({
isPopoverActive: false
});
},
toggle: function toggle() {
this.state.isPopoverActive ? this.close() : this.open();
},
handleDelayedOpen: function handleDelayedOpen() {
if (this._hoverDelay != null) {
clearTimeout(this._hoverDelay);
this._hoverDelay = null;
return;
}
var delay = this.props.delayOpen != null ? this.props.delayOpen : this.props.delay;
if (!delay) {
this.open();
return;
}
this._hoverDelay = setTimeout(function () {
this._hoverDelay = null;
this.open();
}.bind(this), delay);
},
handleDelayedClose: function handleDelayedClose() {
if (this._hoverDelay != null) {
clearTimeout(this._hoverDelay);
this._hoverDelay = null;
return;
}
var delay = this.props.delayClose != null ? this.props.delayClose : this.props.delay;
if (!delay) {
this.close();
return;
}
this._hoverDelay = setTimeout(function () {
this._hoverDelay = null;
this.close();
}.bind(this), delay);
},
updatePopoverPosition: function updatePopoverPosition() {
if (!this.isMounted()) {
return;
}
var position = this.calcPopoverPosition();
this.setState({
popoverLeft: position.left,
popoverTop: position.top
});
},
calcPopoverPosition: function calcPopoverPosition() {
var childOffset = this.getPosition();
var popoverNode = this.getOverlayDOMNode();
var popoverHeight = popoverNode.offsetHeight;
var popoverWidth = popoverNode.offsetWidth;
var caretSize = 8;
switch (this.props.placement) {
case 'right':
return {
top: childOffset.top + childOffset.height / 2 - popoverHeight / 2,
left: childOffset.left + childOffset.width + caretSize
};
case 'left':
return {
top: childOffset.top + childOffset.height / 2 - popoverHeight / 2,
left: childOffset.left - popoverWidth - caretSize
};
case 'top':
return {
top: childOffset.top - popoverHeight - caretSize,
left: childOffset.left + childOffset.width / 2 - popoverWidth / 2
};
case 'bottom':
return {
top: childOffset.top + childOffset.height + caretSize,
left: childOffset.left + childOffset.width / 2 - popoverWidth / 2
};
default:
throw new Error('calcPopoverPosition(): No such placement of [' + this.props.placement + '] found.');
}
},
getPosition: function getPosition() {
var node = ReactDOM.findDOMNode(this);
var container = this.getContainerDOMNode();
var offset = container.tagName === 'BODY' ? dom.offset(node) : dom.position(node, container);
return assign({}, offset, {
height: node.offsetHeight,
width: node.offsetWidth
});
},
// used by Mixin
renderOverlay: function renderOverlay() {
if (!this.state.isPopoverActive) {
return React.createElement('span', null);
}
var popover = this.props.popover;
return cloneElement(this.props.popover, {
onRequestHide: this.close,
placement: this.props.placement,
positionLeft: this.state.popoverLeft,
positionTop: this.state.popoverTop,
amStyle: popover.props.amStyle || this.props.amStyle,
amSize: popover.props.amSize || this.props.amSize
});
},
render: function render() {
var child = React.Children.only(this.props.children);
var props = {};
props.onClick = createChainedFunction(child.props.onClick, this.props.onClick);
if (isOneOf('click', this.props.trigger)) {
props.onClick = createChainedFunction(this.toggle, props.onClick);
}
if (isOneOf('hover', this.props.trigger)) {
props.onMouseOver = createChainedFunction(this.handleDelayedOpen, this.props.onMouseOver);
props.onMouseOut = createChainedFunction(this.handleDelayedClose, this.props.onMouseOut);
}
if (isOneOf('focus', this.props.trigger)) {
props.onFocus = createChainedFunction(this.handleDelayedOpen, this.props.onFocus);
props.onBlur = createChainedFunction(this.handleDelayedClose, this.props.onBlur);
}
return cloneElement(child, props);
}
});
module.exports = PopoverTrigger;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
/**
* React version of NProgress
* https://github.com/rstacruz/nprogress/
*/
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var ClassNameMixin = __webpack_require__(4);
function clamp(n, min, max) {
if (n < min) {
return min;
}
if (n > max) {
return max;
}
return n;
}
function toBarPercentage(n) {
return (-1 + n) * 100;
}
var NProgress = React.createClass({
displayName: 'NProgress',
mixins: [ClassNameMixin],
propTypes: {
minimum: React.PropTypes.number,
easing: React.PropTypes.string,
speed: React.PropTypes.number,
spinner: React.PropTypes.bool,
trickle: React.PropTypes.bool,
trickleRate: React.PropTypes.number,
trickleSpeed: React.PropTypes.number
},
getInitialState: function getInitialState() {
return {
status: null
};
},
getDefaultProps: function getDefaultProps() {
return {
minimum: 0.08,
easing: 'ease',
speed: 200,
trickle: true,
trickleRate: 0.02,
trickleSpeed: 800
};
},
start: function start() {
var _this = this;
var n = this.state.status; // this.set() is not sync to affected this.state.status
if (!this.state.status) {
this.set(this.props.minimum);
n = this.props.minimum;
}
var work = function work() {
setTimeout(function () {
if (!n || n === 1) {
return;
}
_this.trickle();
work();
}, _this.props.trickleSpeed);
};
this.props.trickle && work();
},
set: function set(n) {
var _this = this;
n = clamp(n, this.props.minimum, 1);
this.setState({
status: n
});
if (n === 1) {
var progress = ReactDOM.findDOMNode(this.refs.progress);
progress.style.opacity = 1;
progress.style.transition = 'none';
progress.offsetWidth;
setTimeout(function () {
progress.style.opacity = 0;
progress.style.transition = 'all ' + _this.props.speed + 'ms linear';
setTimeout(function () {
_this.reset();
}, _this.props.speed + 100);
}, _this.props.speed);
}
},
reset: function reset() {
this.setState({
status: null
});
},
done: function done() {
if (this.state.status) {
this.inc(0.3 + 0.5 * Math.random());
this.set(1);
}
},
inc: function inc(amount) {
var n = this.state.status;
if (!n) {
return this.start();
} else {
if (typeof amount !== 'number') {
amount = (1 - n) * clamp(Math.random() * n, 0.1, 0.95);
}
n = clamp(n + amount, 0, 0.994);
return this.set(n);
}
},
trickle: function trickle() {
if (this.state.status < 1) {
this.inc(Math.random() * this.props.trickleRate);
}
},
render: function render() {
var props = this.props;
var percent = this.state.status === null ? '-100' : toBarPercentage(this.state.status);
var barStyle = {
transition: 'all ' + props.speed + 'ms ' + props.easing,
transform: 'translate(' + percent + '%,0)'
};
var spinner = props.spinner ? React.createElement(
'div',
{ className: 'nprogress-spinner', ref: 'spinner' },
React.createElement('div', { className: 'nprogress-spinner-icon' })
) : null;
return this.state.status ? React.createElement(
'div',
{ id: 'nprogress', ref: 'progress' },
React.createElement(
'div',
{ className: 'nprogress-bar', ref: 'bar', style: barStyle },
React.createElement('div', { className: 'nprogress-peg' })
),
spinner
) : null;
}
});
module.exports = NProgress;
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var cloneElement = React.cloneElement;
var assign = __webpack_require__(31);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var isInViewport = __webpack_require__(70);
var Events = __webpack_require__(53);
var TransitionEvents = __webpack_require__(39);
var requestAnimationFrame = __webpack_require__(71);
var debounce = __webpack_require__(72);
var canUseDOM = __webpack_require__(40);
var domUtils = __webpack_require__(63);
var ScrollSpy = React.createClass({
displayName: 'ScrollSpy',
mixins: [ClassNameMixin],
propTypes: {
animation: React.PropTypes.string,
delay: React.PropTypes.number,
repeat: React.PropTypes.bool,
// container which has scrollbar
container: React.PropTypes.any
},
getDefaultProps: function getDefaultProps() {
return {
animation: 'fade',
delay: 0,
repeat: false
};
},
getInitialState: function getInitialState() {
return {
inViewport: false
};
},
componentDidMount: function componentDidMount() {
if (canUseDOM) {
this.checkRAF();
var node = ReactDOM.findDOMNode(this);
var doc = domUtils.ownerDocument(node);
// var scrollContainer = ReactDOM.findDOMNode(this.props.container || doc.body);
var debounced = debounce(this.checkRAF, 100).bind(this);
this._scrollListener = Events.on(doc, 'scroll', debounced);
this._resizeListener = Events.on(window, 'resize', debounced);
this._orientationListener = Events.on(window, 'orientationchange', debounced);
}
},
componentWillUnmount: function componentWillUnmount() {
this._removeEventLister();
},
_removeEventLister: function _removeEventLister() {
this._scrollListener && this._scrollListener.off();
this._resizeListener && this._resizeListener.off();
this._orientationListener && this._orientationListener.off();
clearTimeout(this._timer);
},
checkIsInView: function checkIsInView() {
if (!TransitionEvents.support.animationend) {
return;
}
if (this.isMounted()) {
var isInView = isInViewport(ReactDOM.findDOMNode(this));
if (isInView && !this.state.inViewport) {
if (this._timer) {
clearTimeout(this._timer);
}
this._timer = setTimeout(function () {
this.setState({
inViewport: true
});
}.bind(this), this.props.delay);
}
if (this.props.repeat && !isInView) {
this.setState({
inViewport: false
});
}
}
},
checkRAF: function checkRAF() {
requestAnimationFrame(this.checkIsInView);
},
render: function render() {
var animation = this.state.inViewport ? this.setClassNamespace('animation-' + this.props.animation) : null;
var child = React.Children.only(this.props.children);
// transfer child's props to cloned element
return cloneElement(child, assign({}, child.props, {
className: classNames(child.props.className, animation),
'data-am-scrollspy': 'animation', // style helper
delay: this.props.delay,
componentWillMount: this._removeEventLister
}));
}
});
module.exports = ScrollSpy;
/***/ },
/* 70 */
/***/ function(module, exports) {
'use strict';
/**
* isInViewport
*
* @desc determine if any part of the element is visible in the viewport
* @reference https://github.com/Josh-Miller/isInViewport
* @see http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
* @param {HTMLElement} element
* @returns {boolean}
*/
function isInViewport(element) {
var top = element.offsetTop;
var left = element.offsetLeft;
var width = element.offsetWidth;
var height = element.offsetHeight;
while (element.offsetParent) {
element = element.offsetParent;
top += element.offsetTop;
left += element.offsetLeft;
}
return top < window.pageYOffset + window.innerHeight && left < window.pageXOffset + window.innerWidth && top + height > window.pageYOffset && left + width > window.pageXOffset;
}
module.exports = isInViewport;
// TODO: 考虑滚动条不在窗口上的情形
/***/ },
/* 71 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* modified version of:
* https://github.com/facebook/react/blob/0.13-stable/src/vendor/core/requestAnimationFrame.js
*/
'use strict';
var nativeRAF = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame;
var lastTime = 0;
var requestAnimationFrame = nativeRAF || function (callback) {
var currTime = Date.now();
var timeDelay = Math.max(0, 16 - (currTime - lastTime));
lastTime = currTime + timeDelay;
return global.setTimeout(function () {
callback(Date.now());
}, timeDelay);
};
// Works around a rare bug in Safari 6 where the first request is never invoked.
requestAnimationFrame(function () {});
module.exports = requestAnimationFrame;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 72 */
/***/ function(module, exports) {
'use strict';
/**
* Debounce function
* @param {function} fn Function to be debounced
* @param {number} wait Function execution threshold in milliseconds
* @param {bool} immediate Whether the function should be called at
* the beginning of the delay instead of the
* end. Default is false.
* @desc Executes a function when it stops being invoked for n seconds
* @via _.debounce() http://underscorejs.org
*/
module.exports = function (fn, wait, immediate) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function later() {
timeout = null;
if (!immediate) {
fn.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
fn.apply(context, args);
}
};
};
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var cloneElement = React.cloneElement;
var assign = __webpack_require__(31);
var classNames = __webpack_require__(3);
var SmoothScrollMixin = __webpack_require__(74);
var isInViewport = __webpack_require__(70);
var Events = __webpack_require__(53);
var requestAnimationFrame = __webpack_require__(71);
var debounce = __webpack_require__(72);
var CSSCore = __webpack_require__(16);
var domUtils = __webpack_require__(63);
var createChainedFunction = __webpack_require__(35);
var canUseDOM = __webpack_require__(40);
var constants = __webpack_require__(5);
var ScrollSpyNav = React.createClass({
displayName: 'ScrollSpyNav',
mixins: [SmoothScrollMixin],
propTypes: {
activeClass: React.PropTypes.string,
offsetTop: React.PropTypes.number,
container: React.PropTypes.any
},
getDefaultProps: function getDefaultProps() {
return {
activeClass: constants.CLASSES.active
};
},
componentDidMount: function componentDidMount() {
if (canUseDOM) {
this._init();
this.checkRAF();
var debounced = debounce(this.checkRAF, 100).bind(this);
this._scrollListener = Events.on(window, 'scroll', this.checkRAF);
this._resizeListener = Events.on(window, 'resize', debounced);
this._orientationListener = Events.on(window, 'orientationchange', debounced);
}
},
componentWillUnmount: function componentWillUnmount() {
this._scrollListener && this._scrollListener.off();
this._resizeListener && this._resizeListener.off();
this._orientationListener && this._orientationListener.off();
},
_init: function _init() {
this._linkNodes = ReactDOM.findDOMNode(this).querySelectorAll('a[href^="#"]');
this._anchorNodes = [];
Array.prototype.forEach.call(this._linkNodes, function (link) {
var anchor = document.getElementById(link.getAttribute('href').substr(1));
if (anchor) {
this._anchorNodes.push(anchor);
}
}.bind(this));
},
checkIsInView: function checkIsInView() {
if (this.isMounted()) {
var inViewsNodes = [];
this._anchorNodes.forEach(function (anchor) {
if (isInViewport(anchor)) {
inViewsNodes.push(anchor);
}
});
if (inViewsNodes.length) {
var targetNode;
inViewsNodes.every(function (node) {
if (domUtils.offset(node).top >= domUtils.scrollTop(window)) {
targetNode = node;
return false; // break loop
}
return true;
});
if (!targetNode) {
return;
}
Array.prototype.forEach.call(this._linkNodes, function (link) {
CSSCore.removeClass(link, this.props.activeClass);
}.bind(this));
var targetLink = ReactDOM.findDOMNode(this).querySelector('a[href="#' + targetNode.id + '"]');
targetLink && CSSCore.addClass(targetLink, this.props.activeClass);
}
}
},
checkRAF: function checkRAF() {
requestAnimationFrame(this.checkIsInView);
},
// Smooth scroll
handleClick: function handleClick(e) {
e.preventDefault();
if (e.target && e.target.nodeName === 'A') {
var targetNode = document.getElementById(e.target.getAttribute('href').substr(1));
// TODO: set scroll element if `container` prop set
targetNode && this.smoothScroll(window, {
position: domUtils.offset(targetNode).top - this.props.offsetTop || 0
});
}
},
render: function render() {
var child = React.Children.only(this.props.children);
// transfer child's props to cloned element
return cloneElement(child, assign({}, this.props, child.props, {
onClick: createChainedFunction(this.handleClick, child.props.onClick),
className: classNames(this.props.className, child.props.className)
}));
}
});
module.exports = ScrollSpyNav;
// TODO: improve in view logic
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
/**
* modified version of:
* http://mir.aculo.us/2014/01/19/scrolling-dom-elements-to-the-top-a-zepto-plugin/
*/
'use strict';
var React = __webpack_require__(1);
var Events = __webpack_require__(53);
var dom = __webpack_require__(63);
var rAF = __webpack_require__(71);
var scrollInProgress = false;
var SmoothScrollMixin = {
smoothScroll: function smoothScroll(element, options) {
options = options || {};
var scrollTarget = element || window;
var targetY = options.position && parseInt(options.position, 10) || 0;
var initialY = dom.scrollTop(scrollTarget);
var lastY = initialY;
var delta = targetY - initialY;
// duration in ms, make it a bit shorter for short distances
// this is not scientific and you might want to adjust this for
// your preferences
var speed = options.speed || Math.min(750, Math.min(1500, Math.abs(initialY - targetY)));
// temp variables (t will be a position between 0 and 1, y is the calculated scrollTop)
var start;
var t;
var y;
var cancelScroll = function cancelScroll() {
abort();
};
// abort if already in progress or nothing to scroll
if (scrollInProgress) {
// console.log(scrollInProgress);
return;
}
if (delta === 0) {
return;
}
// quint ease-in-out smoothing, from
// https://github.com/madrobby/scripty2/blob/master/src/effects/transitions/penner.js#L127-L136
function smooth(pos) {
if ((pos /= 0.5) < 1) {
return 0.5 * Math.pow(pos, 5);
}
return 0.5 * (Math.pow(pos - 2, 5) + 2);
}
function abort() {
Events.off(scrollTarget, 'touchstart', cancelScroll);
scrollInProgress = false;
}
// when there's a touch detected while scrolling is in progress, abort
// the scrolling (emulates native scrolling behavior)
Events.on(scrollTarget, 'touchstart', cancelScroll);
scrollInProgress = true;
// start rendering away! note the function given to frame
// is named "render" so we can reference it again further down
rAF(function render(now) {
if (!scrollInProgress) {
return;
}
if (!start) {
start = now;
}
// calculate t, position of animation in [0..1]
t = Math.min(1, Math.max((now - start) / speed, 0));
// calculate the new scrollTop position (don't forget to smooth)
y = Math.round(initialY + delta * smooth(t));
// bracket scrollTop so we're never over-scrolling
if (delta > 0 && y > targetY) {
y = targetY;
}
if (delta < 0 && y < targetY) {
y = targetY;
}
// only actually set scrollTop if there was a change front he last frame
if (lastY !== y) {
dom.scrollTop(scrollTarget, y);
}
lastY = y;
// if we're not done yet, queue up an other frame to render,
// or clean up
if (y !== targetY) {
rAF(render);
} else {
abort();
}
});
}
};
module.exports = SmoothScrollMixin;
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Dropdown = __webpack_require__(59);
var Icon = __webpack_require__(23);
var Input = __webpack_require__(21);
var Selected = React.createClass({
displayName: 'Selected',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
data: React.PropTypes.array.isRequired,
placeholder: React.PropTypes.string,
value: React.PropTypes.string,
multiple: React.PropTypes.bool,
searchBox: React.PropTypes.bool,
name: React.PropTypes.string,
onChange: React.PropTypes.func,
optionFilter: React.PropTypes.func,
dropup: React.PropTypes.bool,
btnWidth: React.PropTypes.number,
btnStyle: React.PropTypes.string,
btnSize: React.PropTypes.string,
maxHeight: React.PropTypes.number,
// delimiter to use to join multiple values
delimiter: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'selected',
placeholder: '点击选择...',
onChange: function onChange() {},
value: '',
delimiter: ',',
optionFilter: function optionFilter(filterText, option) {
return option.label.toLowerCase().indexOf(filterText) > -1;
}
};
},
getInitialState: function getInitialState() {
return {
value: this.props.value,
dropdownWidth: null,
filterText: null
};
},
componentDidMount: function componentDidMount() {
this.setDropdownWidth();
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({
value: nextProps.value
});
},
setDropdownWidth: function setDropdownWidth() {
if (this.isMounted()) {
var toggleButton = ReactDOM.findDOMNode(this.refs.dropdown.refs.dropdownToggle);
toggleButton && this.setState({ dropdownWidth: toggleButton.offsetWidth });
}
},
getValueArray: function getValueArray() {
return this.state.value ? this.state.value.split(this.props.delimiter) : [];
},
hasValue: function hasValue(value) {
return this.getValueArray().indexOf(value) > -1;
},
setValue: function setValue(value, callback) {
this.setState({
value: value
}, function () {
this.props.onChange(value);
callback && callback();
});
},
handleCheck: function handleCheck(option, e) {
e.preventDefault();
var clickedValue = option.value;
// multiple select
if (this.props.multiple) {
var values = this.getValueArray();
if (this.hasValue(clickedValue)) {
values.splice(values.indexOf(clickedValue), 1);
} else {
values.push(clickedValue);
}
this.setValue(values.join(this.props.delimiter));
} else {
this.setValue(clickedValue);
this.refs.dropdown.setDropdown(false);
}
},
handleUserInput: function handleUserInput(e) {
e.preventDefault();
this.setState({
filterText: ReactDOM.findDOMNode(this.refs.filterInput).value
});
},
// clear filter
clearFilterInput: function clearFilterInput() {
if (this.props.multiple && this.props.searchBox) {
this.setState({
filterText: null
});
ReactDOM.findDOMNode(this.refs.filterInput).value = null;
}
},
// API for getting component value
getValue: function getValue() {
return this.state.value;
},
render: function render() {
var classSet = this.getClassSet();
var selectedLabel = [];
var items = [];
var filterText = this.state.filterText;
var groupHeader;
this.props.data.forEach(function (option, i) {
var checked = this.hasValue(option.value);
var checkedClass = checked ? this.setClassNamespace('checked') : null;
var checkedIcon = checked ? React.createElement(Icon, { icon: 'check' }) : null;
checked && selectedLabel.push(option.label);
// add group header
if (option.group && groupHeader !== option.group) {
groupHeader = option.group;
items.push(React.createElement(
'li',
{
className: this.prefixClass('list-header'),
key: 'header' + i
},
groupHeader
));
}
if (filterText && !this.props.optionFilter(filterText, option)) {
return;
}
items.push(React.createElement(
'li',
{
className: checkedClass,
onClick: this.handleCheck.bind(this, option),
key: i
},
React.createElement(
'span',
{ className: this.prefixClass('text') },
option.label
),
checkedIcon
));
}.bind(this));
var status = React.createElement(
'span',
{
className: classNames(this.prefixClass('status'), this.setClassNamespace('fl'))
},
selectedLabel.length ? selectedLabel.join(', ') : React.createElement(
'span',
{ className: this.prefixClass('placeholder ') },
this.props.placeholder
)
);
var optionsStyle = {};
if (this.props.maxHeight) {
optionsStyle = {
maxHeight: this.props.maxHeight,
overflowY: 'scroll'
};
}
return React.createElement(
Dropdown,
{
className: classNames(this.props.className, classSet),
title: status,
onClose: this.clearFilterInput,
btnStyle: this.props.btnStyle,
btnSize: this.props.btnSize,
btnInlineStyle: { width: this.props.btnWidth },
contentInlineStyle: { minWidth: this.state.dropdownWidth },
toggleClassName: this.prefixClass('btn'),
caretClassName: this.prefixClass('icon'),
contentClassName: this.prefixClass('content'),
contentTag: 'div',
dropup: this.props.dropup,
ref: 'dropdown'
},
this.props.searchBox ? React.createElement(
'div',
{ className: this.prefixClass('search') },
React.createElement(Input, {
onChange: this.handleUserInput,
autoComplete: 'off',
standalone: true,
ref: 'filterInput'
})
) : null,
React.createElement(
'ul',
{
style: optionsStyle,
className: this.prefixClass('list')
},
items
),
React.createElement('input', {
name: this.props.name,
type: 'hidden',
ref: 'selectedField',
value: this.state.value
})
);
}
});
module.exports = Selected;
/***/ },
/* 76 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var TransitionEvents = __webpack_require__(39);
//React.initializeTouchEvents(true);
var Slider = React.createClass({
displayName: 'Slider',
mixins: [ClassNameMixin],
propTypes: {
theme: React.PropTypes.oneOf(['default', 'a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3', 'c4', 'd1', 'd2', 'd3']),
directionNav: React.PropTypes.bool, // prev/next icon
controlNav: React.PropTypes.bool,
animation: React.PropTypes.string, // not working
slide: React.PropTypes.bool,
autoPlay: React.PropTypes.bool,
slideSpeed: React.PropTypes.number, // interval
loop: React.PropTypes.bool, // loop slide
pauseOnHover: React.PropTypes.bool,
touch: React.PropTypes.bool, // TODO: add touch support
onSelect: React.PropTypes.func,
onSlideEnd: React.PropTypes.func,
activeIndex: React.PropTypes.number,
defaultActiveIndex: React.PropTypes.number,
direction: React.PropTypes.oneOf(['prev', 'next'])
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'slider',
theme: 'default',
directionNav: true,
controlNav: true,
slide: true,
autoPlay: true,
loop: true,
slideSpeed: 5000,
pauseOnHover: true
};
},
getInitialState: function getInitialState() {
return {
activeIndex: this.props.defaultActiveIndex == null ? 0 : this.props.defaultActiveIndex,
previousActiveIndex: null,
direction: null
};
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
var activeIndex = this.getActiveIndex();
if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) {
clearTimeout(this.timeout);
this.setState({
previousActiveIndex: activeIndex,
direction: nextProps.direction != null ? nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex)
});
}
},
componentDidMount: function componentDidMount() {
this.props.autoPlay && this.waitForNext();
},
componentWillUnmount: function componentWillUnmount() {
clearTimeout(this.timeout);
},
getDirection: function getDirection(prevIndex, index) {
if (prevIndex === index) {
return null;
}
return prevIndex > index ? 'prev' : 'next';
},
next: function next(e) {
e && e.preventDefault();
var index = this.getActiveIndex() + 1;
var count = React.Children.count(this.props.children);
if (index > count - 1) {
if (!this.props.loop) {
return;
}
index = 0;
}
this.handleSelect(index, 'next');
},
prev: function prev(e) {
e && e.preventDefault();
var index = this.getActiveIndex() - 1;
if (index < 0) {
if (!this.props.loop) {
return;
}
index = React.Children.count(this.props.children) - 1;
}
this.handleSelect(index, 'prev');
},
pause: function pause() {
this.isPaused = true;
clearTimeout(this.timeout);
},
play: function play() {
this.isPaused = false;
this.waitForNext();
},
waitForNext: function waitForNext() {
if (!this.isPaused && this.props.slide && this.props.slideSpeed && this.props.activeIndex == null) {
this.timeout = setTimeout(this.next, this.props.slideSpeed);
}
},
handleMouseOver: function handleMouseOver() {
if (this.props.pauseOnHover) {
this.pause();
}
},
handleMouseOut: function handleMouseOut() {
if (this.isPaused) {
this.play();
}
},
getActiveIndex: function getActiveIndex() {
return this.props.activeIndex != null ? this.props.activeIndex : this.state.activeIndex;
},
handleItemAnimateOutEnd: function handleItemAnimateOutEnd() {
this.setState({
previousActiveIndex: null,
direction: null
}, function () {
this.waitForNext();
if (this.props.onSlideEnd) {
this.props.onSlideEnd();
}
});
},
handleSelect: function handleSelect(index, direction, e) {
e && e.preventDefault();
clearTimeout(this.timeout);
var previousActiveIndex = this.getActiveIndex();
direction = direction || this.getDirection(previousActiveIndex, index);
if (this.props.onSelect) {
this.props.onSelect(index, direction);
}
if (this.props.activeIndex == null && index !== previousActiveIndex) {
if (this.state.previousActiveIndex != null) {
// If currently animating don't activate the new index.
// TODO: look into queuing this canceled call and
// animating after the current animation has ended.
return;
}
this.setState({
activeIndex: index,
previousActiveIndex: previousActiveIndex,
direction: direction
});
}
},
renderDirectionNav: function renderDirectionNav() {
return this.props.directionNav ? React.createElement(
'ul',
{ className: this.setClassNamespace('direction-nav') },
React.createElement(
'li',
null,
React.createElement(
'a',
{
onClick: this.prev,
className: this.setClassNamespace('prev'),
href: '#prev' },
'Previous'
)
),
React.createElement(
'li',
null,
React.createElement(
'a',
{
onClick: this.next,
className: this.setClassNamespace('next'),
href: '#next' },
'Next'
)
)
) : null;
},
renderControlNav: function renderControlNav() {
if (this.props.controlNav) {
var isThumbnailNav = false;
var children = React.Children.map(this.props.children, function (child, i) {
var className = i === this.getActiveIndex() ? this.setClassNamespace('active') : null;
if (!isThumbnailNav) {
isThumbnailNav = !!child.props.thumbnail;
}
var thumb = child.props.thumbnail;
return React.createElement(
'li',
{
onClick: this.handleSelect.bind(this, i, null),
key: i
},
thumb ? React.createElement('img', { className: className, src: thumb }) : React.createElement('a', { href: '#' + i, className: className }),
React.createElement('i', null)
);
}.bind(this));
var controlClass = this.setClassNamespace('control-' + (isThumbnailNav ? 'thumbs' : 'paging'));
return React.createElement(
'ol',
{
className: classNames(this.setClassNamespace('control-nav'), controlClass) },
children
);
}
return null;
},
renderItem: function renderItem(child, index) {
var activeIndex = this.getActiveIndex();
var isActive = index === activeIndex;
var isPreviousActive = this.state.previousActiveIndex != null && this.state.previousActiveIndex === index && this.props.slide;
return React.cloneElement(child, {
active: isActive,
ref: child.ref,
key: child.key ? child.key : index,
index: index,
animateOut: isPreviousActive,
animateIn: isActive && this.state.previousActiveIndex != null && this.props.slide,
direction: this.state.direction,
onAnimateOutEnd: isPreviousActive ? this.handleItemAnimateOutEnd : null
});
},
render: function render() {
var classSet = this.getClassSet();
var viewportStyle = {
overflow: 'hidden',
position: 'relative',
width: '100%'
};
// React version slider style
classSet[this.prefixClass('slide')] = true;
return React.createElement(
'div',
_extends({}, this.props, {
className: classNames(classSet, this.props.className),
onMouseOver: this.handleMouseOver,
onMouseOut: this.handleMouseOut
}),
React.createElement(
'div',
{
className: this.setClassNamespace('viewport'),
style: viewportStyle
},
React.createElement(
'ul',
{ className: this.setClassNamespace('slides') },
React.Children.map(this.props.children, this.renderItem)
)
),
this.renderDirectionNav(),
this.renderControlNav()
);
}
});
Slider.Item = React.createClass({
displayName: 'Item',
propTypes: {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
caption: React.PropTypes.node,
index: React.PropTypes.number,
thumbnail: React.PropTypes.string
},
getInitialState: function getInitialState() {
return {
direction: null
};
},
getDefaultProps: function getDefaultProps() {
return {
animation: true
};
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate: function componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
TransitionEvents.on(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
handleAnimateOutEnd: function handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
startAnimation: function startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
},
render: function render() {
var classSet = {
active: this.props.active && !this.props.animateIn || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classSet[this.state.direction] = true;
}
return React.createElement(
'li',
{
className: classNames(this.props.className, classSet)
},
this.props.children
);
}
});
module.exports = Slider;
/***/ },
/* 77 */
/***/ 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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var React = __webpack_require__(1);
var ReactDOM = __webpack_require__(22);
var assign = __webpack_require__(31);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Events = __webpack_require__(53);
var debounce = __webpack_require__(72);
var domUtils = __webpack_require__(63);
var canUseDOM = __webpack_require__(40);
var Sticky = React.createClass({
displayName: 'Sticky',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
media: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
top: React.PropTypes.number,
animation: React.PropTypes.string,
bottom: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.func])
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'sticky',
top: 0
};
},
getInitialState: function getInitialState() {
return {
sticked: false,
holderStyle: null,
initialized: false,
stickerStyle: null
};
},
componentDidMount: function componentDidMount() {
if (canUseDOM) {
this._init();
this.checkPosition();
var ownerWindow = domUtils.ownerWindow(ReactDOM.findDOMNode(this.refs.sticker));
this._scrollListener = Events.on(ownerWindow, 'scroll', debounce(this.checkPosition, 10).bind(this));
this._resizeListener = Events.on(ownerWindow, 'resize', debounce(this.checkPosition, 50).bind(this));
}
},
componentWillUnmount: function componentWillUnmount() {
this._scrollListener && this._scrollListener.off();
this._resizeListener && this._resizeListener.off();
},
_init: function _init() {
if (this.state.initialized || !this.isMounted() || !this.checkMedia()) {
return;
}
var sticker = ReactDOM.findDOMNode(this.refs.sticker);
var elStyle = getComputedStyle(sticker);
var outerHeight = parseInt(elStyle.height, 10) + parseInt(elStyle.marginTop, 10) + parseInt(elStyle.marginBottom, 10);
var style = {
height: elStyle.position !== 'absolute' ? outerHeight : '',
float: elStyle.float !== 'none' ? elStyle.float : '',
margin: elStyle.margin
};
this.setState({
initialized: true,
holderStyle: style,
stickerStyle: {
margin: 0
}
});
},
checkPosition: function checkPosition() {
if (this.isMounted) {
var scrollTop = domUtils.scrollTop(window);
var offsetTop = this.props.top;
var offsetBottom = this.props.bottom;
var holder = ReactDOM.findDOMNode(this);
if (typeof offsetBottom === 'function') {
offsetBottom = offsetBottom();
}
var checkResult = scrollTop > domUtils.offset(holder).top;
if (checkResult && !this.state.sticked) {
this.setState({
stickerStyle: {
top: offsetTop,
left: domUtils.offset(holder).left,
width: holder.offsetWidth
}
});
}
if (this.state.sticked && !checkResult) {
this.resetSticker();
}
this.setState({
sticked: checkResult
});
}
},
checkMedia: function checkMedia() {
// TODO: add element visible detector
/*if (!this.$element.is(':visible')) {
return false;
}*/
var media = this.props.media;
if (media) {
switch (typeof media === 'undefined' ? 'undefined' : _typeof(media)) {
case 'number':
if (window.innerWidth < media) {
return false;
}
break;
case 'string':
if (window.matchMedia && !window.matchMedia(media).matches) {
return false;
}
break;
}
}
return true;
},
resetSticker: function resetSticker() {
this.setState({
stickerStyle: {
position: '',
top: '',
width: '',
left: '',
margin: 0
}
});
},
// Smooth scroll
handleClick: function handleClick(e) {
e.preventDefault();
if (e.target && e.target.nodeName === 'A') {
var targetNode = document.getElementById(e.target.getAttribute('href').substr(1));
targetNode && this.smoothScroll(window, {
position: domUtils.offset(targetNode).top - this.props.offsetTop || 0
});
}
},
render: function render() {
var stickyClass = this.getClassSet();
var child = React.Children.only(this.props.children);
var animation = this.props.animation && this.state.sticked ? this.setClassNamespace('animation-' + this.props.animation) : null;
// transfer child's props to cloned element
return React.createElement(
'div',
_extends({}, this.props, {
style: this.state.holderStyle,
className: classNames(this.props.className, this.prefixClass('placeholder'))
}),
React.cloneElement(child, assign({}, child.props, {
style: this.state.stickerStyle,
ref: 'sticker',
className: classNames(child.props.className, this.state.sticked ? stickyClass : null, animation)
}))
);
}
});
module.exports = Sticky;
/***/ },
/* 78 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var CollapseMixin = __webpack_require__(38);
var Accordion = React.createClass({
displayName: 'Accordion',
mixins: [ClassNameMixin],
propTypes: {
theme: React.PropTypes.oneOf(['default', 'basic', 'gapped']),
data: React.PropTypes.array,
activeKey: React.PropTypes.any,
defaultActiveKey: React.PropTypes.any
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'accordion',
theme: 'default'
};
},
getInitialState: function getInitialState() {
return {
activeKey: this.props.defaultActiveKey
};
},
handleSelect: function handleSelect(e, key) {
e.preventDefault();
if (this.state.activeKey === key) {
key = null;
}
this.setState({
activeKey: key
});
},
render: function render() {
var classSet = this.getClassSet();
classSet[this.prefixClass(this.props.theme)] = true;
return React.createElement(
'section',
_extends({}, this.props, {
'data-am-widget': this.props.classPrefix,
className: classNames(classSet, this.props.className)
}),
this.props.data.map(function (item, index) {
return React.createElement(
Accordion.Item,
{
title: item.title,
expanded: item.active && item.disabled,
defaultExpanded: item.active && !item.disabled,
eventKey: index,
key: index
},
item.content
);
})
);
}
});
Accordion.Item = React.createClass({
displayName: 'Item',
mixins: [ClassNameMixin, CollapseMixin],
propTypes: {
title: React.PropTypes.node,
expanded: React.PropTypes.bool
},
handleToggle: function handleToggle() {
this.setState({
expanded: !this.state.expanded
});
},
getCollapsibleDimensionValue: function getCollapsibleDimensionValue() {
return ReactDOM.findDOMNode(this.refs.panel).scrollHeight;
},
getCollapsibleDOMNode: function getCollapsibleDOMNode() {
if (!this.isMounted() || !this.refs || !this.refs.panel) {
return null;
}
return ReactDOM.findDOMNode(this.refs.panel);
},
render: function render() {
return React.createElement(
'dl',
{
className: classNames(this.setClassNamespace('accordion-item'), this.isExpanded() ? this.setClassNamespace('active') : null, this.props.expanded ? this.setClassNamespace('disabled') : null)
},
React.createElement(
'dt',
{
onClick: this.handleToggle,
className: this.setClassNamespace('accordion-title')
},
this.props.title
),
React.createElement(
'dd',
{
className: classNames(this.getCollapsibleClassSet()),
ref: 'panel' },
React.createElement('div', {
className: this.setClassNamespace('accordion-content'),
dangerouslySetInnerHTML: { __html: this.props.children }
})
)
);
}
});
module.exports = Accordion;
/***/ },
/* 79 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Divider = React.createClass({
displayName: 'Divider',
mixins: [ClassNameMixin],
propTypes: {
theme: React.PropTypes.oneOf(['default', 'dotted', 'dashed']),
classPrefix: React.PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'divider',
theme: 'default'
};
},
render: function render() {
var classSet = this.getClassSet();
return React.createElement('hr', _extends({}, this.props, {
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}));
}
});
module.exports = Divider;
/***/ },
/* 80 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Footer = React.createClass({
displayName: 'Footer',
mixins: [ClassNameMixin],
propTypes: {
theme: React.PropTypes.oneOf(['default']),
classPrefix: React.PropTypes.string,
mobileTitle: React.PropTypes.string,
mobileLink: React.PropTypes.string,
desktopTitle: React.PropTypes.string,
desktopLink: React.PropTypes.string,
onRequestMobile: React.PropTypes.func,
onRequestDesktop: React.PropTypes.func,
data: React.PropTypes.array
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'footer',
theme: 'default',
mobileTitle: '适配版',
desktopTitle: '电脑版'
};
},
render: function render() {
var classSet = this.getClassSet();
var MobileTag = this.props.mobileLink ? 'a' : 'span';
return React.createElement(
'footer',
_extends({}, this.props, {
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}),
React.createElement(
'div',
{ className: this.prefixClass('switch') },
React.createElement(
MobileTag,
{
className: this.prefixClass('ysp'),
onClick: this.props.onRequestMobile,
href: this.props.mobileLink,
'data-rel': 'mobile'
},
this.props.mobileTitle
),
React.createElement(
'span',
{ className: this.prefixClass('divider') },
'|'
),
React.createElement(
'a',
{
'data-rel': 'desktop',
href: this.props.desktopLink,
onClick: this.props.onRequestDesktop,
className: this.prefixClass('desktop')
},
this.props.desktopTitle
)
),
React.createElement(
'div',
{ className: this.prefixClass('miscs') },
this.props.data ? this.props.data.map(function (item, i) {
return React.createElement(
'p',
{ key: i },
item
);
}) : this.props.children
)
);
}
});
module.exports = Footer;
/***/ },
/* 81 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var AvgGrid = __webpack_require__(8);
var omit = __webpack_require__(10);
var Gallery = React.createClass({
displayName: 'Gallery',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default', 'overlay', 'bordered', 'imgbordered']),
data: React.PropTypes.array,
sm: React.PropTypes.number,
md: React.PropTypes.number,
lg: React.PropTypes.number
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'gallery',
theme: 'default',
data: []
};
},
renderItem: function renderItem(item) {
var img = item.img ? React.createElement('img', {
src: item.img,
key: 'galeryImg',
alt: item.alt || item.title || null
}) : null;
var title = item.title ? React.createElement(
'h3',
{
key: 'galleryTitle',
className: this.prefixClass('title')
},
item.title
) : null;
var desc = item.desc ? React.createElement(
'div',
{
key: 'galleryDesc',
className: this.prefixClass('desc')
},
item.desc
) : null;
var galleryItem = item.link ? React.createElement(
'a',
{ href: item.link },
img,
title,
desc
) : [img, title, desc];
return React.createElement(
'div',
{
className: classNames(this.props.className, this.prefixClass('item'))
},
galleryItem
);
},
render: function render() {
var classSet = this.getClassSet();
var props = omit(this.props, ['classPrefix', 'data', 'theme']);
return React.createElement(
AvgGrid,
_extends({}, props, {
sm: this.props.sm || 2,
md: this.props.md || 3,
lg: this.props.lg || 4,
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}),
this.props.data.map(function (item, i) {
return React.createElement(
'li',
{ key: i },
this.renderItem(item)
);
}.bind(this))
);
}
});
module.exports = Gallery;
/***/ },
/* 82 */
/***/ 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__(1);
var ReactDOM = __webpack_require__(22);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var SmoothScrollMixin = __webpack_require__(74);
var Events = __webpack_require__(53);
var debounce = __webpack_require__(72);
var dom = __webpack_require__(63);
var CSSCore = __webpack_require__(16);
var Icon = __webpack_require__(23);
var GoTop = React.createClass({
displayName: 'GoTop',
mixins: [ClassNameMixin, SmoothScrollMixin],
propTypes: {
classPrefix: React.PropTypes.string.isRequired,
theme: React.PropTypes.oneOf(['default', 'fixed']),
title: React.PropTypes.string,
src: React.PropTypes.string,
icon: React.PropTypes.string,
autoHide: React.PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'gotop',
theme: 'default'
};
},
componentDidMount: function componentDidMount() {
if (this.isAutoHide()) {
var check = this.checkPosition;
check();
this._listener = Events.on(window, 'scroll', debounce(check, 100));
}
},
componentWillUnmount: function componentWillUnmount() {
this._listener && this._listener.off();
},
checkPosition: function checkPosition() {
var action = (dom.scrollTop(window) > 50 ? 'add' : 'remove') + 'Class';
CSSCore[action](ReactDOM.findDOMNode(this), this.setClassNamespace('active'));
},
isAutoHide: function isAutoHide() {
return this.props.theme === 'fixed' && this.props.autoHide;
},
handleClick: function handleClick(e) {
e.preventDefault();
this.smoothScroll();
},
renderIcon: function renderIcon() {
return this.props.src ? React.createElement('img', {
className: this.prefixClass('icon-custom'),
src: this.props.src,
alt: this.props.title
}) : React.createElement(Icon, {
className: this.prefixClass('icon'),
icon: this.props.icon || 'chevron-up'
});
},
render: function render() {
var classSet = this.getClassSet();
classSet[this.prefixClass(this.props.theme)] = true;
classSet[this.setClassNamespace('active')] = !this.isAutoHide();
return React.createElement(
'div',
_extends({}, this.props, {
'data-am-widget': this.props.classPrefix,
className: classNames(classSet, this.props.className)
}),
React.createElement(
'a',
{
href: '#top',
onClick: this.handleClick,
title: this.props.title
},
this.props.title ? React.createElement(
'span',
{ className: this.prefixClass('title') },
this.props.title
) : null,
this.renderIcon()
)
);
}
});
module.exports = GoTop;
/***/ },
/* 83 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Icon = __webpack_require__(23);
var omit = __webpack_require__(10);
var Header = React.createClass({
displayName: 'Header',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default']),
data: React.PropTypes.object,
fixed: React.PropTypes.bool,
title: React.PropTypes.node,
link: React.PropTypes.string,
onSelect: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'header',
theme: 'default',
onSelect: function onSelect() {}
};
},
renderTitle: function renderTitle() {
return this.props.title ? React.createElement(
'h1',
{
className: this.prefixClass('title'),
onClick: this.props.onSelect.bind(this, {
title: this.props.title,
link: this.props.link
})
},
this.props.link ? React.createElement(
'a',
{ href: this.props.link },
this.props.title
) : this.props.title
) : null;
},
renderNav: function renderNav(position) {
var data = this.props.data;
var renderItem = function (item, i) {
var handleClick = item.onSelect || this.props.onSelect;
return React.createElement(
'a',
{ href: item.link,
onClick: handleClick.bind(this, item),
key: 'headerNavItem' + i
},
item.title ? React.createElement(
'span',
{ className: this.prefixClass('nav-title') },
item.title
) : null,
item.customIcon ? React.createElement('img', { src: item.customIcon, alt: item.title || null }) : item.icon ? React.createElement(Icon, {
className: this.prefixClass('icon'),
icon: item.icon
}) : null
);
}.bind(this);
return data && data[position] ? React.createElement(
'div',
{
className: classNames(this.prefixClass('nav'), this.prefixClass(position))
},
data[position].map(function (item, i) {
return renderItem(item, i);
})
) : null;
},
render: function render() {
var classSet = this.getClassSet();
// am-header-fixed: fixed header
classSet[this.prefixClass('fixed')] = this.props.fixed;
return React.createElement(
'header',
_extends({}, omit(this.props, ['data', 'title']), {
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}),
this.renderNav('left'),
this.renderTitle(),
this.renderNav('right')
);
}
});
module.exports = Header;
/***/ },
/* 84 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Button = __webpack_require__(9);
var Col = __webpack_require__(6);
var ListNews = React.createClass({
displayName: 'ListNews',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default']),
data: React.PropTypes.object,
header: React.PropTypes.node,
footer: React.PropTypes.node,
morePosition: React.PropTypes.oneOf(['top', 'bottom']),
moreText: React.PropTypes.string,
thumbPosition: React.PropTypes.oneOf(['top', 'left', 'right', 'bottom-left', 'bottom-right'])
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'list-news',
theme: 'default',
moreText: '更多 »'
};
},
renderHeader: function renderHeader() {
var data = this.props.data;
return data && data.header && data.header.title ? React.createElement(
'div',
{
className: classNames(this.prefixClass('hd'), this.setClassNamespace('cf'))
},
data.header.link ? React.createElement(
'a',
{ href: data.header.link },
React.createElement(
'h2',
null,
data.header.title
),
this.props.morePosition === 'top' ? React.createElement(
'span',
{
className: classNames(this.prefixClass('more'), this.setClassNamespace('fr')) },
this.props.moreText
) : null
) : React.createElement(
'h2',
null,
data.header.title
)
) : null;
},
// `more` on bottom
renderFooter: function renderFooter() {
return this.props.morePosition === 'bottom' && this.props.data.header.link ? React.createElement(
'div',
{ className: this.prefixClass('ft') },
React.createElement(
Button,
{
className: this.prefixClass('more'),
href: this.props.data.header.link },
this.props.moreText
)
) : null;
},
getListItemClasses: function getListItemClasses(item) {
return classNames(this.setClassNamespace('g'), item.date ? this.setClassNamespace('list-item-dated') : false, item.desc ? this.setClassNamespace('list-item-desced') : false, item.img ? this.setClassNamespace('list-item-thumbed') : false, this.props.thumbPosition ? this.setClassNamespace('list-item-thumb-' + this.props.thumbPosition) : false);
},
renderBody: function renderBody(children) {
return React.createElement(
'div',
{ className: this.prefixClass('bd') },
React.createElement(
'ul',
{ className: this.setClassNamespace('list') },
children
)
);
},
renderList: function renderList() {
var position = this.props.thumbPosition;
var orderChildren = function (item, i) {
var thumb = this.renderItemThumb(item, i);
var main = this.renderItemMain(item, i);
return position === 'right' || position === 'bottom-right' ? [main, thumb] : [thumb, main];
}.bind(this);
return this.props.data.main.map(function (item, i) {
return React.createElement(
'li',
{
key: i,
className: this.getListItemClasses(item)
},
position === 'bottom-left' || position === 'bottom-right' ? this.renderThumbItemTitle(item) : null,
orderChildren(item, i)
);
}.bind(this));
},
renderItemMisc: function renderItemMisc(item, type) {
var Tag = type === 'date' ? 'span' : 'div';
var className;
switch (type) {
case 'date':
className = 'list-date';
break;
case 'desc':
className = 'list-item-text';
break;
case 'mainAddition':
className = 'list-news-addon';
break;
case 'thumbAddition':
className = 'list-thumb-addon';
}
return item[type] ? React.createElement(
Tag,
{ className: this.setClassNamespace(className) },
item[type]
) : null;
},
renderItemThumb: function renderItemThumb(item, i) {
var Link = item.component || 'a';
var cols = this.props.thumbPosition === 'top' ? 12 : 4;
return item.img ? React.createElement(
Col,
{
key: 'thumb' + i,
sm: cols,
className: this.setClassNamespace('list-thumb')
},
React.createElement(
Link,
{
href: item.link
},
React.createElement('img', { src: item.img, alt: item.title })
),
this.renderItemMisc(item, 'thumbAddition')
) : null;
},
renderItemMain: function renderItemMain(item, i) {
var Link = item.component || 'a';
var position = this.props.thumbPosition;
var date = this.renderItemMisc(item, 'date');
var desc = this.renderItemMisc(item, 'desc');
var addon = this.renderItemMisc(item, 'mainAddition');
// title of list without thumbnail
var itemWithoutThumbTitle = !position && item.title ? React.createElement(
Link,
{
key: 'title' + i,
className: this.setClassNamespace('list-item-hd'),
href: item.link
},
item.title
) : null;
var cols = position === 'top' ? 12 : item.img ? 8 : 12;
return position ? React.createElement(
Col,
{
sm: cols,
className: this.setClassNamespace('list-main'),
key: 'itemMain' + i
},
position !== 'bottom-left' && position !== 'bottom-right' ? this.renderThumbItemTitle(item) : null,
date,
desc,
addon
) : [itemWithoutThumbTitle, date, desc, addon];
},
renderThumbItemTitle: function renderThumbItemTitle(item) {
var Link = item.component || 'a';
return item.title ? React.createElement(
'h3',
{ className: this.setClassNamespace('list-item-hd') },
React.createElement(
Link,
{ href: item.link },
item.title
)
) : null;
},
render: function render() {
var classSet = this.getClassSet();
return React.createElement(
'div',
_extends({}, this.props, {
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}),
this.props.header || this.renderHeader(),
this.renderBody(this.renderList()),
this.props.footer || this.renderFooter()
);
}
});
module.exports = ListNews;
/***/ },
/* 85 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var omit = __webpack_require__(10);
var ClassNameMixin = __webpack_require__(4);
var Icon = __webpack_require__(23);
var AvgGrid = __webpack_require__(8);
var Menu = React.createClass({
displayName: 'Menu',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default', 'dropdown1', 'dropdown2', 'slide1', 'stack']),
data: React.PropTypes.array,
onSelect: React.PropTypes.func,
toggleTitle: React.PropTypes.string,
toggleCustomIcon: React.PropTypes.string,
toggleIcon: React.PropTypes.string,
cols: React.PropTypes.number
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'menu',
theme: 'default',
data: [],
onSelect: function onSelect() {}
};
},
getInitialState: function getInitialState() {
return {
data: this.props.data,
expanded: !this.isDropdown()
};
},
handleClick: function handleClick(nav, index, closeAll, e) {
if (nav && nav.subMenu) {
this.handleParentClick(nav, index, closeAll, e);
}
this.props.onSelect.call(this, nav, index, e);
},
/**
* handle nav with subMenu click
* @param {object} nav - clicked nav
* @param {number} index - clicked nav index
* @param {bool} closeAll - close all submenu
* @param {object} e
*/
handleParentClick: function handleParentClick(nav, index, closeAll, e) {
e && e.preventDefault();
var data = this.state.data.map(function (item, i) {
item.subActive = closeAll ? false : index === i ? !item.subActive : false;
return item;
});
this.setState({
data: data
});
},
closeAll: function closeAll() {
this.handleParentClick(null, null, true, undefined);
},
// handle toggle button click for dropdown/slide theme
handleToggle: function handleToggle(e) {
e && e.preventDefault();
this.setState({
expanded: !this.state.expanded
}, function () {
!this.state.expanded && this.closeAll();
}.bind(this));
},
isDropdown: function isDropdown() {
return ['dropdown1', 'dropdown2', 'slide1'].indexOf(this.props.theme) > -1;
},
renderMenuToggle: function renderMenuToggle() {
var title = this.props.toggleTitle ? React.createElement(
'span',
{
className: this.prefixClass('toggle-title')
},
this.props.toggleTitle
) : null;
var icon = this.props.toggleCustomIcon ? React.createElement('img', {
src: this.props.toggleCustomIcon,
alt: 'Menu Toggle'
}) : React.createElement(Icon, {
className: this.prefixClass('toggle-icon'),
icon: this.props.toggleIcon || 'bars'
});
return React.createElement(
'a',
{
href: '#',
onClick: this.handleToggle,
className: classNames(this.prefixClass('toggle'), this.state.expanded ? this.setClassNamespace('active') : null)
},
title,
icon
);
},
renderNavs: function renderNavs() {
var _this = this;
var openClassName = this.setClassNamespace('open');
var inClassName = this.setClassNamespace('in');
return this.state.data.map(function (nav, i) {
var Link = nav.component || 'a';
var LinkProps = nav.props || {};
return React.createElement(
'li',
{
key: i,
className: classNames(nav.subMenu ? _this.setClassNamespace('parent') : null, nav.subActive ? openClassName : null)
},
React.createElement(
Link,
_extends({
onClick: _this.handleClick.bind(_this, nav, i, false),
href: nav.link
}, LinkProps),
nav.title
),
nav.subMenu ? React.createElement(
AvgGrid,
{
sm: nav.subCols || 1,
className: classNames(_this.prefixClass('sub'), _this.setClassNamespace('collapse'), nav.subActive ? inClassName : null)
},
nav.subMenu.map(function (subNav, index) {
var SubLink = subNav.component || 'a';
var SubLinkProps = subNav.props || {};
return React.createElement(
'li',
{ key: index },
React.createElement(
SubLink,
_extends({
onClick: _this.handleClick.bind(_this, subNav, [i, index], false),
target: subNav.target,
href: subNav.link
}, SubLinkProps),
subNav.title
)
);
})
) : null
);
});
},
render: function render() {
var classSet = this.getClassSet();
var props = omit(this.props, 'data');
var hideTopLevel = !this.state.expanded ? this.setClassNamespace('collapse') : null;
return React.createElement(
'nav',
_extends({}, props, {
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}),
this.renderMenuToggle(),
React.createElement(
AvgGrid,
{
sm: this.props.cols,
className: classNames(this.prefixClass('nav'), hideTopLevel)
},
this.renderNavs()
)
);
}
});
module.exports = Menu;
/***/ },
/* 86 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var Icon = __webpack_require__(23);
var omit = __webpack_require__(10);
var Navbar = React.createClass({
displayName: 'Navbar',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default']),
data: React.PropTypes.array,
onSelect: React.PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'navbar',
theme: 'default',
data: [],
onSelect: function onSelect() {}
};
},
render: function render() {
var classSet = this.getClassSet();
var props = omit(this.props, 'data');
return React.createElement(
'div',
_extends({}, props, {
'data-am-widget': this.props.classPrefix,
cf: true,
className: classNames(this.props.className, classSet)
}),
React.createElement(
'ul',
{ className: this.prefixClass('nav') },
this.props.data.map(function (item, i) {
var Link = item.component || 'a';
var LinkProps = item.props || {};
return React.createElement(
'li',
{
key: i,
onClick: this.props.onSelect.bind(this, item.link)
},
React.createElement(
Link,
_extends({
href: item.link
}, LinkProps),
item.customIcon ? React.createElement('img', {
src: item.customIcon,
alt: item.title
}) : item.icon ? React.createElement(Icon, { icon: item.icon }) : null,
item.title ? React.createElement(
'span',
{ className: this.prefixClass('label') },
item.title
) : null
)
);
}.bind(this))
)
);
}
});
module.exports = Navbar;
/***/ },
/* 87 */
/***/ 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__(1);
var classNames = __webpack_require__(3);
var ClassNameMixin = __webpack_require__(4);
var AvgGrid = __webpack_require__(8);
var omit = __webpack_require__(10);
var Titlebar = React.createClass({
displayName: 'Titlebar',
mixins: [ClassNameMixin],
propTypes: {
classPrefix: React.PropTypes.string,
theme: React.PropTypes.oneOf(['default', 'multi', 'cols']),
nav: React.PropTypes.array,
title: React.PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
classPrefix: 'titlebar',
theme: 'default',
data: []
};
},
render: function render() {
var classSet = this.getClassSet();
var props = omit(this.props, ['classPrefix', 'nav', 'theme']);
return React.createElement(
'div',
_extends({}, props, {
'data-am-widget': this.props.classPrefix,
className: classNames(this.props.className, classSet)
}),
React.createElement(
'h2',
{ className: this.prefixClass('title') },
this.props.href ? React.createElement(
'a',
{ href: this.props.href },
this.props.title
) : this.props.title
),
this.props.nav ? React.createElement(
'nav',
{ className: this.prefixClass('nav') },
this.props.nav.map(function (item, i) {
return React.createElement(
'a',
{ href: item.link, key: i },
item.title
);
})
) : null
);
}
});
module.exports = Titlebar;
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
module.exports = {
ClassNameMixin: __webpack_require__(4),
CollapseMixin: __webpack_require__(38),
DimmerMixin: __webpack_require__(61),
OverlayMixin: __webpack_require__(65),
SmoothScrollMixin: __webpack_require__(74)
};
/***/ }
/******/ ])
});
; |
ajax/libs/angular-ui-select/0.14.8/select.js | AMoo-Miki/cdnjs | /*!
* ui-select
* http://github.com/angular-ui/ui-select
* Version: 0.14.8 - 2016-02-18T21:50:31.512Z
* License: MIT
*/
(function () {
"use strict";
var KEY = {
TAB: 9,
ENTER: 13,
ESC: 27,
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
SHIFT: 16,
CTRL: 17,
ALT: 18,
PAGE_UP: 33,
PAGE_DOWN: 34,
HOME: 36,
END: 35,
BACKSPACE: 8,
DELETE: 46,
COMMAND: 91,
MAP: { 91 : "COMMAND", 8 : "BACKSPACE" , 9 : "TAB" , 13 : "ENTER" , 16 : "SHIFT" , 17 : "CTRL" , 18 : "ALT" , 19 : "PAUSEBREAK" , 20 : "CAPSLOCK" , 27 : "ESC" , 32 : "SPACE" , 33 : "PAGE_UP", 34 : "PAGE_DOWN" , 35 : "END" , 36 : "HOME" , 37 : "LEFT" , 38 : "UP" , 39 : "RIGHT" , 40 : "DOWN" , 43 : "+" , 44 : "PRINTSCREEN" , 45 : "INSERT" , 46 : "DELETE", 48 : "0" , 49 : "1" , 50 : "2" , 51 : "3" , 52 : "4" , 53 : "5" , 54 : "6" , 55 : "7" , 56 : "8" , 57 : "9" , 59 : ";", 61 : "=" , 65 : "A" , 66 : "B" , 67 : "C" , 68 : "D" , 69 : "E" , 70 : "F" , 71 : "G" , 72 : "H" , 73 : "I" , 74 : "J" , 75 : "K" , 76 : "L", 77 : "M" , 78 : "N" , 79 : "O" , 80 : "P" , 81 : "Q" , 82 : "R" , 83 : "S" , 84 : "T" , 85 : "U" , 86 : "V" , 87 : "W" , 88 : "X" , 89 : "Y" , 90 : "Z", 96 : "0" , 97 : "1" , 98 : "2" , 99 : "3" , 100 : "4" , 101 : "5" , 102 : "6" , 103 : "7" , 104 : "8" , 105 : "9", 106 : "*" , 107 : "+" , 109 : "-" , 110 : "." , 111 : "/", 112 : "F1" , 113 : "F2" , 114 : "F3" , 115 : "F4" , 116 : "F5" , 117 : "F6" , 118 : "F7" , 119 : "F8" , 120 : "F9" , 121 : "F10" , 122 : "F11" , 123 : "F12", 144 : "NUMLOCK" , 145 : "SCROLLLOCK" , 186 : ";" , 187 : "=" , 188 : "," , 189 : "-" , 190 : "." , 191 : "/" , 192 : "`" , 219 : "[" , 220 : "\\" , 221 : "]" , 222 : "'"
},
isControl: function (e) {
var k = e.which;
switch (k) {
case KEY.COMMAND:
case KEY.SHIFT:
case KEY.CTRL:
case KEY.ALT:
return true;
}
if (e.metaKey) return true;
return false;
},
isFunctionKey: function (k) {
k = k.which ? k.which : k;
return k >= 112 && k <= 123;
},
isVerticalMovement: function (k){
return ~[KEY.UP, KEY.DOWN].indexOf(k);
},
isHorizontalMovement: function (k){
return ~[KEY.LEFT,KEY.RIGHT,KEY.BACKSPACE,KEY.DELETE].indexOf(k);
},
toSeparator: function (k) {
var sep = {ENTER:"\n",TAB:"\t",SPACE:" "}[k];
if (sep) return sep;
// return undefined for special keys other than enter, tab or space.
// no way to use them to cut strings.
return KEY[k] ? undefined : k;
}
};
/**
* Add querySelectorAll() to jqLite.
*
* jqLite find() is limited to lookups by tag name.
* TODO This will change with future versions of AngularJS, to be removed when this happens
*
* See jqLite.find - why not use querySelectorAll? https://github.com/angular/angular.js/issues/3586
* See feat(jqLite): use querySelectorAll instead of getElementsByTagName in jqLite.find https://github.com/angular/angular.js/pull/3598
*/
if (angular.element.prototype.querySelectorAll === undefined) {
angular.element.prototype.querySelectorAll = function(selector) {
return angular.element(this[0].querySelectorAll(selector));
};
}
/**
* Add closest() to jqLite.
*/
if (angular.element.prototype.closest === undefined) {
angular.element.prototype.closest = function( selector) {
var elem = this[0];
var matchesSelector = elem.matches || elem.webkitMatchesSelector || elem.mozMatchesSelector || elem.msMatchesSelector;
while (elem) {
if (matchesSelector.bind(elem)(selector)) {
return elem;
} else {
elem = elem.parentElement;
}
}
return false;
};
}
var latestId = 0;
var uis = angular.module('ui.select', [])
.constant('uiSelectConfig', {
theme: 'bootstrap',
searchEnabled: true,
sortable: false,
placeholder: '', // Empty by default, like HTML tag <select>
refreshDelay: 1000, // In milliseconds
closeOnSelect: true,
dropdownPosition: 'auto',
generateId: function() {
return latestId++;
},
appendToBody: false
})
// See Rename minErr and make it accessible from outside https://github.com/angular/angular.js/issues/6913
.service('uiSelectMinErr', function() {
var minErr = angular.$$minErr('ui.select');
return function() {
var error = minErr.apply(this, arguments);
var message = error.message.replace(new RegExp('\nhttp://errors.angularjs.org/.*'), '');
return new Error(message);
};
})
// Recreates old behavior of ng-transclude. Used internally.
.directive('uisTranscludeAppend', function () {
return {
link: function (scope, element, attrs, ctrl, transclude) {
transclude(scope, function (clone) {
element.append(clone);
});
}
};
})
/**
* Highlights text that matches $select.search.
*
* Taken from AngularUI Bootstrap Typeahead
* See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L340
*/
.filter('highlight', function() {
function escapeRegexp(queryToEscape) {
return ('' + queryToEscape).replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function(matchItem, query) {
return query && matchItem ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<span class="ui-select-highlight">$&</span>') : matchItem;
};
})
/**
* A read-only equivalent of jQuery's offset function: http://api.jquery.com/offset/
*
* Taken from AngularUI Bootstrap Position:
* See https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js#L70
*/
.factory('uisOffset',
['$document', '$window',
function ($document, $window) {
return function(element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
};
};
}]);
uis.directive('uiSelectChoices',
['uiSelectConfig', 'uisRepeatParser', 'uiSelectMinErr', '$compile', '$window',
function(uiSelectConfig, RepeatParser, uiSelectMinErr, $compile, $window) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Needed so the uiSelect can detect the transcluded content
tElement.addClass('ui-select-choices');
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
return theme + '/choices.tpl.html';
},
compile: function(tElement, tAttrs) {
if (!tAttrs.repeat) throw uiSelectMinErr('repeat', "Expected 'repeat' expression.");
return function link(scope, element, attrs, $select, transcludeFn) {
// var repeat = RepeatParser.parse(attrs.repeat);
var groupByExp = attrs.groupBy;
var groupFilterExp = attrs.groupFilter;
$select.parseRepeatAttr(attrs.repeat, groupByExp, groupFilterExp); //Result ready at $select.parserResult
$select.disableChoiceExpression = attrs.uiDisableChoice;
$select.onHighlightCallback = attrs.onHighlight;
$select.dropdownPosition = attrs.position ? attrs.position.toLowerCase() : uiSelectConfig.dropdownPosition;
if(groupByExp) {
var groups = element.querySelectorAll('.ui-select-choices-group');
if (groups.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-group but got '{0}'.", groups.length);
groups.attr('ng-repeat', RepeatParser.getGroupNgRepeatExpression());
}
var choices = element.querySelectorAll('.ui-select-choices-row');
if (choices.length !== 1) {
throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row but got '{0}'.", choices.length);
}
choices.attr('ng-repeat', $select.parserResult.repeatExpression(groupByExp))
.attr('ng-if', '$select.open'); //Prevent unnecessary watches when dropdown is closed
if ($window.document.addEventListener) { //crude way to exclude IE8, specifically, which also cannot capture events
choices.attr('ng-mouseenter', '$select.setActiveItem('+$select.parserResult.itemName +')')
.attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',false,$event)');
}
var rowsInner = element.querySelectorAll('.ui-select-choices-row-inner');
if (rowsInner.length !== 1) throw uiSelectMinErr('rows', "Expected 1 .ui-select-choices-row-inner but got '{0}'.", rowsInner.length);
rowsInner.attr('uis-transclude-append', ''); //Adding uisTranscludeAppend directive to row element after choices element has ngRepeat
if (!$window.document.addEventListener) { //crude way to target IE8, specifically, which also cannot capture events - so event bindings must be here
rowsInner.attr('ng-mouseenter', '$select.setActiveItem('+$select.parserResult.itemName +')')
.attr('ng-click', '$select.select(' + $select.parserResult.itemName + ',false,$event)');
}
$compile(element, transcludeFn)(scope); //Passing current transcludeFn to be able to append elements correctly from uisTranscludeAppend
scope.$watch('$select.search', function(newValue) {
if(newValue && !$select.open && $select.multiple) $select.activate(false, true);
$select.activeIndex = $select.tagging.isActivated ? -1 : 0;
if (!attrs.minimumInputLength || $select.search.length >= attrs.minimumInputLength) {
$select.refresh(attrs.refresh);
} else {
$select.items = [];
}
});
attrs.$observe('refreshDelay', function() {
// $eval() is needed otherwise we get a string instead of a number
var refreshDelay = scope.$eval(attrs.refreshDelay);
$select.refreshDelay = refreshDelay !== undefined ? refreshDelay : uiSelectConfig.refreshDelay;
});
};
}
};
}]);
/**
* Contains ui-select "intelligence".
*
* The goal is to limit dependency on the DOM whenever possible and
* put as much logic in the controller (instead of the link functions) as possible so it can be easily tested.
*/
uis.controller('uiSelectCtrl',
['$scope', '$element', '$timeout', '$filter', 'uisRepeatParser', 'uiSelectMinErr', 'uiSelectConfig', '$parse', '$injector',
function($scope, $element, $timeout, $filter, RepeatParser, uiSelectMinErr, uiSelectConfig, $parse, $injector) {
var ctrl = this;
var EMPTY_SEARCH = '';
ctrl.placeholder = uiSelectConfig.placeholder;
ctrl.searchEnabled = uiSelectConfig.searchEnabled;
ctrl.sortable = uiSelectConfig.sortable;
ctrl.refreshDelay = uiSelectConfig.refreshDelay;
ctrl.paste = uiSelectConfig.paste;
ctrl.removeSelected = false; //If selected item(s) should be removed from dropdown list
ctrl.closeOnSelect = true; //Initialized inside uiSelect directive link function
ctrl.search = EMPTY_SEARCH;
ctrl.activeIndex = 0; //Dropdown of choices
ctrl.items = []; //All available choices
ctrl.open = false;
ctrl.focus = false;
ctrl.disabled = false;
ctrl.selected = undefined;
ctrl.dropdownPosition = 'auto';
ctrl.focusser = undefined; //Reference to input element used to handle focus events
ctrl.resetSearchInput = true;
ctrl.multiple = undefined; // Initialized inside uiSelect directive link function
ctrl.disableChoiceExpression = undefined; // Initialized inside uiSelectChoices directive link function
ctrl.tagging = {isActivated: false, fct: undefined};
ctrl.taggingTokens = {isActivated: false, tokens: undefined};
ctrl.lockChoiceExpression = undefined; // Initialized inside uiSelectMatch directive link function
ctrl.clickTriggeredSelect = false;
ctrl.$filter = $filter;
// Use $injector to check for $animate and store a reference to it
ctrl.$animate = (function () {
try {
return $injector.get('$animate');
} catch (err) {
// $animate does not exist
return null;
}
})();
ctrl.searchInput = $element.querySelectorAll('input.ui-select-search');
if (ctrl.searchInput.length !== 1) {
throw uiSelectMinErr('searchInput', "Expected 1 input.ui-select-search but got '{0}'.", ctrl.searchInput.length);
}
ctrl.isEmpty = function() {
return angular.isUndefined(ctrl.selected) || ctrl.selected === null || ctrl.selected === '' || (ctrl.multiple && ctrl.selected.length === 0);
};
function _findIndex(collection, predicate, thisArg){
if (collection.findIndex){
return collection.findIndex(predicate, thisArg);
} else {
var list = Object(collection);
var length = list.length >>> 0;
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
}
}
// Most of the time the user does not want to empty the search input when in typeahead mode
function _resetSearchInput() {
if (ctrl.resetSearchInput || (ctrl.resetSearchInput === undefined && uiSelectConfig.resetSearchInput)) {
ctrl.search = EMPTY_SEARCH;
//reset activeIndex
if (ctrl.selected && ctrl.items.length && !ctrl.multiple) {
ctrl.activeIndex = _findIndex(ctrl.items, function(item){
return angular.equals(this, item);
}, ctrl.selected);
}
}
}
function _groupsFilter(groups, groupNames) {
var i, j, result = [];
for(i = 0; i < groupNames.length ;i++){
for(j = 0; j < groups.length ;j++){
if(groups[j].name == [groupNames[i]]){
result.push(groups[j]);
}
}
}
return result;
}
// When the user clicks on ui-select, displays the dropdown list
ctrl.activate = function(initSearchValue, avoidReset) {
if (!ctrl.disabled && !ctrl.open) {
if(!avoidReset) _resetSearchInput();
$scope.$broadcast('uis:activate');
ctrl.open = true;
ctrl.activeIndex = ctrl.activeIndex >= ctrl.items.length ? 0 : ctrl.activeIndex;
// ensure that the index is set to zero for tagging variants
// that where first option is auto-selected
if ( ctrl.activeIndex === -1 && ctrl.taggingLabel !== false ) {
ctrl.activeIndex = 0;
}
var container = $element.querySelectorAll('.ui-select-choices-content');
if (ctrl.$animate && ctrl.$animate.enabled(container[0])) {
ctrl.$animate.on('enter', container[0], function (elem, phase) {
if (phase === 'close') {
// Only focus input after the animation has finished
$timeout(function () {
ctrl.focusSearchInput(initSearchValue);
});
}
});
} else {
$timeout(function () {
ctrl.focusSearchInput(initSearchValue);
});
}
}
};
ctrl.focusSearchInput = function (initSearchValue) {
ctrl.search = initSearchValue || ctrl.search;
ctrl.searchInput[0].focus();
if(!ctrl.tagging.isActivated && ctrl.items.length > 1) {
_ensureHighlightVisible();
}
};
ctrl.findGroupByName = function(name) {
return ctrl.groups && ctrl.groups.filter(function(group) {
return group.name === name;
})[0];
};
ctrl.parseRepeatAttr = function(repeatAttr, groupByExp, groupFilterExp) {
function updateGroups(items) {
var groupFn = $scope.$eval(groupByExp);
ctrl.groups = [];
angular.forEach(items, function(item) {
var groupName = angular.isFunction(groupFn) ? groupFn(item) : item[groupFn];
var group = ctrl.findGroupByName(groupName);
if(group) {
group.items.push(item);
}
else {
ctrl.groups.push({name: groupName, items: [item]});
}
});
if(groupFilterExp){
var groupFilterFn = $scope.$eval(groupFilterExp);
if( angular.isFunction(groupFilterFn)){
ctrl.groups = groupFilterFn(ctrl.groups);
} else if(angular.isArray(groupFilterFn)){
ctrl.groups = _groupsFilter(ctrl.groups, groupFilterFn);
}
}
ctrl.items = [];
ctrl.groups.forEach(function(group) {
ctrl.items = ctrl.items.concat(group.items);
});
}
function setPlainItems(items) {
ctrl.items = items;
}
ctrl.setItemsFn = groupByExp ? updateGroups : setPlainItems;
ctrl.parserResult = RepeatParser.parse(repeatAttr);
ctrl.isGrouped = !!groupByExp;
ctrl.itemProperty = ctrl.parserResult.itemName;
//If collection is an Object, convert it to Array
var originalSource = ctrl.parserResult.source;
//When an object is used as source, we better create an array and use it as 'source'
var createArrayFromObject = function(){
var origSrc = originalSource($scope);
$scope.$uisSource = Object.keys(origSrc).map(function(v){
var result = {};
result[ctrl.parserResult.keyName] = v;
result.value = origSrc[v];
return result;
});
};
if (ctrl.parserResult.keyName){ // Check for (key,value) syntax
createArrayFromObject();
ctrl.parserResult.source = $parse('$uisSource' + ctrl.parserResult.filters);
$scope.$watch(originalSource, function(newVal, oldVal){
if (newVal !== oldVal) createArrayFromObject();
}, true);
}
ctrl.refreshItems = function (data){
data = data || ctrl.parserResult.source($scope);
var selectedItems = ctrl.selected;
//TODO should implement for single mode removeSelected
if (ctrl.isEmpty() || (angular.isArray(selectedItems) && !selectedItems.length) || !ctrl.removeSelected) {
ctrl.setItemsFn(data);
}else{
if ( data !== undefined ) {
var filteredItems = data.filter(function(i) {return selectedItems && selectedItems.indexOf(i) < 0;});
ctrl.setItemsFn(filteredItems);
}
}
if (ctrl.dropdownPosition === 'auto' || ctrl.dropdownPosition === 'up'){
$scope.calculateDropdownPos();
}
};
// See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L259
$scope.$watchCollection(ctrl.parserResult.source, function(items) {
if (items === undefined || items === null) {
// If the user specifies undefined or null => reset the collection
// Special case: items can be undefined if the user did not initialized the collection on the scope
// i.e $scope.addresses = [] is missing
ctrl.items = [];
} else {
if (!angular.isArray(items)) {
throw uiSelectMinErr('items', "Expected an array but got '{0}'.", items);
} else {
//Remove already selected items (ex: while searching)
//TODO Should add a test
ctrl.refreshItems(items);
ctrl.ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
}
}
});
};
var _refreshDelayPromise;
/**
* Typeahead mode: lets the user refresh the collection using his own function.
*
* See Expose $select.search for external / remote filtering https://github.com/angular-ui/ui-select/pull/31
*/
ctrl.refresh = function(refreshAttr) {
if (refreshAttr !== undefined) {
// Debounce
// See https://github.com/angular-ui/bootstrap/blob/0.10.0/src/typeahead/typeahead.js#L155
// FYI AngularStrap typeahead does not have debouncing: https://github.com/mgcrea/angular-strap/blob/v2.0.0-rc.4/src/typeahead/typeahead.js#L177
if (_refreshDelayPromise) {
$timeout.cancel(_refreshDelayPromise);
}
_refreshDelayPromise = $timeout(function() {
$scope.$eval(refreshAttr);
}, ctrl.refreshDelay);
}
};
ctrl.isActive = function(itemScope) {
if ( !ctrl.open ) {
return false;
}
var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
var isActive = itemIndex == ctrl.activeIndex;
if ( !isActive || ( itemIndex < 0 && ctrl.taggingLabel !== false ) ||( itemIndex < 0 && ctrl.taggingLabel === false) ) {
return false;
}
if (isActive && !angular.isUndefined(ctrl.onHighlightCallback)) {
itemScope.$eval(ctrl.onHighlightCallback);
}
return isActive;
};
ctrl.isDisabled = function(itemScope) {
if (!ctrl.open) return;
var itemIndex = ctrl.items.indexOf(itemScope[ctrl.itemProperty]);
var isDisabled = false;
var item;
if (itemIndex >= 0 && !angular.isUndefined(ctrl.disableChoiceExpression)) {
item = ctrl.items[itemIndex];
isDisabled = !!(itemScope.$eval(ctrl.disableChoiceExpression)); // force the boolean value
item._uiSelectChoiceDisabled = isDisabled; // store this for later reference
}
return isDisabled;
};
// When the user selects an item with ENTER or clicks the dropdown
ctrl.select = function(item, skipFocusser, $event) {
if (item === undefined || !item._uiSelectChoiceDisabled) {
if ( ! ctrl.items && ! ctrl.search && ! ctrl.tagging.isActivated) return;
if (!item || !item._uiSelectChoiceDisabled) {
if(ctrl.tagging.isActivated) {
// if taggingLabel is disabled, we pull from ctrl.search val
if ( ctrl.taggingLabel === false ) {
if ( ctrl.activeIndex < 0 ) {
item = ctrl.tagging.fct !== undefined ? ctrl.tagging.fct(ctrl.search) : ctrl.search;
if (!item || angular.equals( ctrl.items[0], item ) ) {
return;
}
} else {
// keyboard nav happened first, user selected from dropdown
item = ctrl.items[ctrl.activeIndex];
}
} else {
// tagging always operates at index zero, taggingLabel === false pushes
// the ctrl.search value without having it injected
if ( ctrl.activeIndex === 0 ) {
// ctrl.tagging pushes items to ctrl.items, so we only have empty val
// for `item` if it is a detected duplicate
if ( item === undefined ) return;
// create new item on the fly if we don't already have one;
// use tagging function if we have one
if ( ctrl.tagging.fct !== undefined && typeof item === 'string' ) {
item = ctrl.tagging.fct(item);
if (!item) return;
// if item type is 'string', apply the tagging label
} else if ( typeof item === 'string' ) {
// trim the trailing space
item = item.replace(ctrl.taggingLabel,'').trim();
}
}
}
// search ctrl.selected for dupes potentially caused by tagging and return early if found
if ( ctrl.selected && angular.isArray(ctrl.selected) && ctrl.selected.filter( function (selection) { return angular.equals(selection, item); }).length > 0 ) {
ctrl.close(skipFocusser);
return;
}
}
$scope.$broadcast('uis:select', item);
var locals = {};
locals[ctrl.parserResult.itemName] = item;
$timeout(function(){
ctrl.onSelectCallback($scope, {
$item: item,
$model: ctrl.parserResult.modelMapper($scope, locals)
});
});
if (ctrl.closeOnSelect) {
ctrl.close(skipFocusser);
}
if ($event && $event.type === 'click') {
ctrl.clickTriggeredSelect = true;
}
}
}
};
// Closes the dropdown
ctrl.close = function(skipFocusser) {
if (!ctrl.open) return;
if (ctrl.ngModel && ctrl.ngModel.$setTouched) ctrl.ngModel.$setTouched();
_resetSearchInput();
ctrl.open = false;
$scope.$broadcast('uis:close', skipFocusser);
};
ctrl.setFocus = function(){
if (!ctrl.focus) ctrl.focusInput[0].focus();
};
ctrl.clear = function($event) {
ctrl.select(undefined);
$event.stopPropagation();
$timeout(function() {
ctrl.focusser[0].focus();
}, 0, false);
};
// Toggle dropdown
ctrl.toggle = function(e) {
if (ctrl.open) {
ctrl.close();
e.preventDefault();
e.stopPropagation();
} else {
ctrl.activate();
}
};
ctrl.isLocked = function(itemScope, itemIndex) {
var isLocked, item = ctrl.selected[itemIndex];
if (item && !angular.isUndefined(ctrl.lockChoiceExpression)) {
isLocked = !!(itemScope.$eval(ctrl.lockChoiceExpression)); // force the boolean value
item._uiSelectChoiceLocked = isLocked; // store this for later reference
}
return isLocked;
};
var sizeWatch = null;
ctrl.sizeSearchInput = function() {
var input = ctrl.searchInput[0],
container = ctrl.searchInput.parent().parent()[0],
calculateContainerWidth = function() {
// Return the container width only if the search input is visible
return container.clientWidth * !!input.offsetParent;
},
updateIfVisible = function(containerWidth) {
if (containerWidth === 0) {
return false;
}
var inputWidth = containerWidth - input.offsetLeft - 10;
if (inputWidth < 50) inputWidth = containerWidth;
ctrl.searchInput.css('width', inputWidth+'px');
return true;
};
ctrl.searchInput.css('width', '10px');
$timeout(function() { //Give tags time to render correctly
if (sizeWatch === null && !updateIfVisible(calculateContainerWidth())) {
sizeWatch = $scope.$watch(calculateContainerWidth, function(containerWidth) {
if (updateIfVisible(containerWidth)) {
sizeWatch();
sizeWatch = null;
}
});
}
});
};
function _handleDropDownSelection(key) {
var processed = true;
switch (key) {
case KEY.DOWN:
if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
else if (ctrl.activeIndex < ctrl.items.length - 1) { ctrl.activeIndex++; }
break;
case KEY.UP:
if (!ctrl.open && ctrl.multiple) ctrl.activate(false, true); //In case its the search input in 'multiple' mode
else if (ctrl.activeIndex > 0 || (ctrl.search.length === 0 && ctrl.tagging.isActivated && ctrl.activeIndex > -1)) { ctrl.activeIndex--; }
break;
case KEY.TAB:
if (!ctrl.multiple || ctrl.open) ctrl.select(ctrl.items[ctrl.activeIndex], true);
break;
case KEY.ENTER:
if(ctrl.open && (ctrl.tagging.isActivated || ctrl.activeIndex >= 0)){
ctrl.select(ctrl.items[ctrl.activeIndex]); // Make sure at least one dropdown item is highlighted before adding if not in tagging mode
} else {
ctrl.activate(false, true); //In case its the search input in 'multiple' mode
}
break;
case KEY.ESC:
ctrl.close();
break;
default:
processed = false;
}
return processed;
}
// Bind to keyboard shortcuts
ctrl.searchInput.on('keydown', function(e) {
var key = e.which;
// if(~[KEY.ESC,KEY.TAB].indexOf(key)){
// //TODO: SEGURO?
// ctrl.close();
// }
$scope.$apply(function() {
var tagged = false;
if (ctrl.items.length > 0 || ctrl.tagging.isActivated) {
_handleDropDownSelection(key);
if ( ctrl.taggingTokens.isActivated ) {
for (var i = 0; i < ctrl.taggingTokens.tokens.length; i++) {
if ( ctrl.taggingTokens.tokens[i] === KEY.MAP[e.keyCode] ) {
// make sure there is a new value to push via tagging
if ( ctrl.search.length > 0 ) {
tagged = true;
}
}
}
if ( tagged ) {
$timeout(function() {
ctrl.searchInput.triggerHandler('tagged');
var newItem = ctrl.search.replace(KEY.MAP[e.keyCode],'').trim();
if ( ctrl.tagging.fct ) {
newItem = ctrl.tagging.fct( newItem );
}
if (newItem) ctrl.select(newItem, true);
});
}
}
}
});
if(KEY.isVerticalMovement(key) && ctrl.items.length > 0){
_ensureHighlightVisible();
}
if (key === KEY.ENTER || key === KEY.ESC) {
e.preventDefault();
e.stopPropagation();
}
});
ctrl.searchInput.on('paste', function (e) {
var data;
if (window.clipboardData && window.clipboardData.getData) { // IE
data = window.clipboardData.getData('Text');
} else {
data = (e.originalEvent || e).clipboardData.getData('text/plain');
}
// Prepend the current input field text to the paste buffer.
data = ctrl.search + data;
if (data && data.length > 0) {
// If tagging try to split by tokens and add items
if (ctrl.taggingTokens.isActivated) {
var separator = KEY.toSeparator(ctrl.taggingTokens.tokens[0]);
var items = data.split(separator || ctrl.taggingTokens.tokens[0]); // split by first token only
if (items && items.length > 0) {
var oldsearch = ctrl.search;
angular.forEach(items, function (item) {
var newItem = ctrl.tagging.fct ? ctrl.tagging.fct(item) : item;
if (newItem) {
ctrl.select(newItem, true);
}
});
ctrl.search = oldsearch || EMPTY_SEARCH;
e.preventDefault();
e.stopPropagation();
}
} else if (ctrl.paste) {
ctrl.paste(data);
ctrl.search = EMPTY_SEARCH;
e.preventDefault();
e.stopPropagation();
}
}
});
ctrl.searchInput.on('tagged', function() {
$timeout(function() {
_resetSearchInput();
});
});
// See https://github.com/ivaynberg/select2/blob/3.4.6/select2.js#L1431
function _ensureHighlightVisible() {
var container = $element.querySelectorAll('.ui-select-choices-content');
var choices = container.querySelectorAll('.ui-select-choices-row');
if (choices.length < 1) {
throw uiSelectMinErr('choices', "Expected multiple .ui-select-choices-row but got '{0}'.", choices.length);
}
if (ctrl.activeIndex < 0) {
return;
}
var highlighted = choices[ctrl.activeIndex];
var posY = highlighted.offsetTop + highlighted.clientHeight - container[0].scrollTop;
var height = container[0].offsetHeight;
if (posY > height) {
container[0].scrollTop += posY - height;
} else if (posY < highlighted.clientHeight) {
if (ctrl.isGrouped && ctrl.activeIndex === 0)
container[0].scrollTop = 0; //To make group header visible when going all the way up
else
container[0].scrollTop -= highlighted.clientHeight - posY;
}
}
$scope.$on('$destroy', function() {
ctrl.searchInput.off('keyup keydown tagged blur paste');
});
}]);
uis.directive('uiSelect',
['$document', 'uiSelectConfig', 'uiSelectMinErr', 'uisOffset', '$compile', '$parse', '$timeout',
function($document, uiSelectConfig, uiSelectMinErr, uisOffset, $compile, $parse, $timeout) {
return {
restrict: 'EA',
templateUrl: function(tElement, tAttrs) {
var theme = tAttrs.theme || uiSelectConfig.theme;
return theme + (angular.isDefined(tAttrs.multiple) ? '/select-multiple.tpl.html' : '/select.tpl.html');
},
replace: true,
transclude: true,
require: ['uiSelect', '^ngModel'],
scope: true,
controller: 'uiSelectCtrl',
controllerAs: '$select',
compile: function(tElement, tAttrs) {
// Allow setting ngClass on uiSelect
var match = /{(.*)}\s*{(.*)}/.exec(tAttrs.ngClass);
if(match) {
var combined = '{'+ match[1] +', '+ match[2] +'}';
tAttrs.ngClass = combined;
tElement.attr('ng-class', combined);
}
//Multiple or Single depending if multiple attribute presence
if (angular.isDefined(tAttrs.multiple))
tElement.append('<ui-select-multiple/>').removeAttr('multiple');
else
tElement.append('<ui-select-single/>');
if (tAttrs.inputId)
tElement.querySelectorAll('input.ui-select-search')[0].id = tAttrs.inputId;
return function(scope, element, attrs, ctrls, transcludeFn) {
var $select = ctrls[0];
var ngModel = ctrls[1];
$select.generatedId = uiSelectConfig.generateId();
$select.baseTitle = attrs.title || 'Select box';
$select.focusserTitle = $select.baseTitle + ' focus';
$select.focusserId = 'focusser-' + $select.generatedId;
$select.closeOnSelect = function() {
if (angular.isDefined(attrs.closeOnSelect)) {
return $parse(attrs.closeOnSelect)();
} else {
return uiSelectConfig.closeOnSelect;
}
}();
$select.onSelectCallback = $parse(attrs.onSelect);
$select.onRemoveCallback = $parse(attrs.onRemove);
//Limit the number of selections allowed
$select.limit = (angular.isDefined(attrs.limit)) ? parseInt(attrs.limit, 10) : undefined;
//Set reference to ngModel from uiSelectCtrl
$select.ngModel = ngModel;
$select.choiceGrouped = function(group){
return $select.isGrouped && group && group.name;
};
if(attrs.tabindex){
attrs.$observe('tabindex', function(value) {
$select.focusInput.attr('tabindex', value);
element.removeAttr('tabindex');
});
}
scope.$watch('searchEnabled', function() {
var searchEnabled = scope.$eval(attrs.searchEnabled);
$select.searchEnabled = searchEnabled !== undefined ? searchEnabled : uiSelectConfig.searchEnabled;
});
scope.$watch('sortable', function() {
var sortable = scope.$eval(attrs.sortable);
$select.sortable = sortable !== undefined ? sortable : uiSelectConfig.sortable;
});
attrs.$observe('disabled', function() {
// No need to use $eval() (thanks to ng-disabled) since we already get a boolean instead of a string
$select.disabled = attrs.disabled !== undefined ? attrs.disabled : false;
});
attrs.$observe('resetSearchInput', function() {
// $eval() is needed otherwise we get a string instead of a boolean
var resetSearchInput = scope.$eval(attrs.resetSearchInput);
$select.resetSearchInput = resetSearchInput !== undefined ? resetSearchInput : true;
});
attrs.$observe('paste', function() {
$select.paste = scope.$eval(attrs.paste);
});
attrs.$observe('tagging', function() {
if(attrs.tagging !== undefined)
{
// $eval() is needed otherwise we get a string instead of a boolean
var taggingEval = scope.$eval(attrs.tagging);
$select.tagging = {isActivated: true, fct: taggingEval !== true ? taggingEval : undefined};
}
else
{
$select.tagging = {isActivated: false, fct: undefined};
}
});
attrs.$observe('taggingLabel', function() {
if(attrs.tagging !== undefined )
{
// check eval for FALSE, in this case, we disable the labels
// associated with tagging
if ( attrs.taggingLabel === 'false' ) {
$select.taggingLabel = false;
}
else
{
$select.taggingLabel = attrs.taggingLabel !== undefined ? attrs.taggingLabel : '(new)';
}
}
});
attrs.$observe('taggingTokens', function() {
if (attrs.tagging !== undefined) {
var tokens = attrs.taggingTokens !== undefined ? attrs.taggingTokens.split('|') : [',','ENTER'];
$select.taggingTokens = {isActivated: true, tokens: tokens };
}
});
//Automatically gets focus when loaded
if (angular.isDefined(attrs.autofocus)){
$timeout(function(){
$select.setFocus();
});
}
//Gets focus based on scope event name (e.g. focus-on='SomeEventName')
if (angular.isDefined(attrs.focusOn)){
scope.$on(attrs.focusOn, function() {
$timeout(function(){
$select.setFocus();
});
});
}
function onDocumentClick(e) {
if (!$select.open) return; //Skip it if dropdown is close
var contains = false;
if (window.jQuery) {
// Firefox 3.6 does not support element.contains()
// See Node.contains https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
contains = window.jQuery.contains(element[0], e.target);
} else {
contains = element[0].contains(e.target);
}
if (!contains && !$select.clickTriggeredSelect) {
//Will lose focus only with certain targets
var focusableControls = ['input','button','textarea','select'];
var targetController = angular.element(e.target).controller('uiSelect'); //To check if target is other ui-select
var skipFocusser = targetController && targetController !== $select; //To check if target is other ui-select
if (!skipFocusser) skipFocusser = ~focusableControls.indexOf(e.target.tagName.toLowerCase()); //Check if target is input, button or textarea
$select.close(skipFocusser);
scope.$digest();
}
$select.clickTriggeredSelect = false;
}
// See Click everywhere but here event http://stackoverflow.com/questions/12931369
$document.on('click', onDocumentClick);
scope.$on('$destroy', function() {
$document.off('click', onDocumentClick);
});
// Move transcluded elements to their correct position in main template
transcludeFn(scope, function(clone) {
// See Transclude in AngularJS http://blog.omkarpatil.com/2012/11/transclude-in-angularjs.html
// One day jqLite will be replaced by jQuery and we will be able to write:
// var transcludedElement = clone.filter('.my-class')
// instead of creating a hackish DOM element:
var transcluded = angular.element('<div>').append(clone);
var transcludedMatch = transcluded.querySelectorAll('.ui-select-match');
transcludedMatch.removeAttr('ui-select-match'); //To avoid loop in case directive as attr
transcludedMatch.removeAttr('data-ui-select-match'); // Properly handle HTML5 data-attributes
if (transcludedMatch.length !== 1) {
throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-match but got '{0}'.", transcludedMatch.length);
}
element.querySelectorAll('.ui-select-match').replaceWith(transcludedMatch);
var transcludedChoices = transcluded.querySelectorAll('.ui-select-choices');
transcludedChoices.removeAttr('ui-select-choices'); //To avoid loop in case directive as attr
transcludedChoices.removeAttr('data-ui-select-choices'); // Properly handle HTML5 data-attributes
if (transcludedChoices.length !== 1) {
throw uiSelectMinErr('transcluded', "Expected 1 .ui-select-choices but got '{0}'.", transcludedChoices.length);
}
element.querySelectorAll('.ui-select-choices').replaceWith(transcludedChoices);
});
// Support for appending the select field to the body when its open
var appendToBody = scope.$eval(attrs.appendToBody);
if (appendToBody !== undefined ? appendToBody : uiSelectConfig.appendToBody) {
scope.$watch('$select.open', function(isOpen) {
if (isOpen) {
positionDropdown();
} else {
resetDropdown();
}
});
// Move the dropdown back to its original location when the scope is destroyed. Otherwise
// it might stick around when the user routes away or the select field is otherwise removed
scope.$on('$destroy', function() {
resetDropdown();
});
}
// Hold on to a reference to the .ui-select-container element for appendToBody support
var placeholder = null,
originalWidth = '';
function positionDropdown() {
// Remember the absolute position of the element
var offset = uisOffset(element);
// Clone the element into a placeholder element to take its original place in the DOM
placeholder = angular.element('<div class="ui-select-placeholder"></div>');
placeholder[0].style.width = offset.width + 'px';
placeholder[0].style.height = offset.height + 'px';
element.after(placeholder);
// Remember the original value of the element width inline style, so it can be restored
// when the dropdown is closed
originalWidth = element[0].style.width;
// Now move the actual dropdown element to the end of the body
$document.find('body').append(element);
element[0].style.position = 'absolute';
element[0].style.left = offset.left + 'px';
element[0].style.top = offset.top + 'px';
element[0].style.width = offset.width + 'px';
}
function resetDropdown() {
if (placeholder === null) {
// The dropdown has not actually been display yet, so there's nothing to reset
return;
}
// Move the dropdown element back to its original location in the DOM
placeholder.replaceWith(element);
placeholder = null;
element[0].style.position = '';
element[0].style.left = '';
element[0].style.top = '';
element[0].style.width = originalWidth;
// Set focus back on to the moved element
$select.setFocus();
}
// Hold on to a reference to the .ui-select-dropdown element for direction support.
var dropdown = null,
directionUpClassName = 'direction-up';
// Support changing the direction of the dropdown if there isn't enough space to render it.
scope.$watch('$select.open', function() {
if ($select.dropdownPosition === 'auto' || $select.dropdownPosition === 'up'){
scope.calculateDropdownPos();
}
});
var setDropdownPosUp = function(offset, offsetDropdown){
offset = offset || uisOffset(element);
offsetDropdown = offsetDropdown || uisOffset(dropdown);
dropdown[0].style.position = 'absolute';
dropdown[0].style.top = (offsetDropdown.height * -1) + 'px';
element.addClass(directionUpClassName);
};
var setDropdownPosDown = function(offset, offsetDropdown){
element.removeClass(directionUpClassName);
offset = offset || uisOffset(element);
offsetDropdown = offsetDropdown || uisOffset(dropdown);
dropdown[0].style.position = '';
dropdown[0].style.top = '';
};
scope.calculateDropdownPos = function(){
if ($select.open) {
dropdown = angular.element(element).querySelectorAll('.ui-select-dropdown');
if (dropdown.length === 0) {
return;
}
// Hide the dropdown so there is no flicker until $timeout is done executing.
dropdown[0].style.opacity = 0;
// Delay positioning the dropdown until all choices have been added so its height is correct.
$timeout(function(){
if ($select.dropdownPosition === 'up'){
//Go UP
setDropdownPosUp();
}else{ //AUTO
element.removeClass(directionUpClassName);
var offset = uisOffset(element);
var offsetDropdown = uisOffset(dropdown);
//https://code.google.com/p/chromium/issues/detail?id=342307#c4
var scrollTop = $document[0].documentElement.scrollTop || $document[0].body.scrollTop; //To make it cross browser (blink, webkit, IE, Firefox).
// Determine if the direction of the dropdown needs to be changed.
if (offset.top + offset.height + offsetDropdown.height > scrollTop + $document[0].documentElement.clientHeight) {
//Go UP
setDropdownPosUp(offset, offsetDropdown);
}else{
//Go DOWN
setDropdownPosDown(offset, offsetDropdown);
}
}
// Display the dropdown once it has been positioned.
dropdown[0].style.opacity = 1;
});
} else {
if (dropdown === null || dropdown.length === 0) {
return;
}
// Reset the position of the dropdown.
dropdown[0].style.position = '';
dropdown[0].style.top = '';
element.removeClass(directionUpClassName);
}
};
};
}
};
}]);
uis.directive('uiSelectMatch', ['uiSelectConfig', function(uiSelectConfig) {
return {
restrict: 'EA',
require: '^uiSelect',
replace: true,
transclude: true,
templateUrl: function(tElement) {
// Needed so the uiSelect can detect the transcluded content
tElement.addClass('ui-select-match');
// Gets theme attribute from parent (ui-select)
var theme = tElement.parent().attr('theme') || uiSelectConfig.theme;
var multi = tElement.parent().attr('multiple');
return theme + (multi ? '/match-multiple.tpl.html' : '/match.tpl.html');
},
link: function(scope, element, attrs, $select) {
$select.lockChoiceExpression = attrs.uiLockChoice;
attrs.$observe('placeholder', function(placeholder) {
$select.placeholder = placeholder !== undefined ? placeholder : uiSelectConfig.placeholder;
});
function setAllowClear(allow) {
$select.allowClear = (angular.isDefined(allow)) ? (allow === '') ? true : (allow.toLowerCase() === 'true') : false;
}
attrs.$observe('allowClear', setAllowClear);
setAllowClear(attrs.allowClear);
if($select.multiple){
$select.sizeSearchInput();
}
}
};
}]);
uis.directive('uiSelectMultiple', ['uiSelectMinErr','$timeout', function(uiSelectMinErr, $timeout) {
return {
restrict: 'EA',
require: ['^uiSelect', '^ngModel'],
controller: ['$scope','$timeout', function($scope, $timeout){
var ctrl = this,
$select = $scope.$select,
ngModel;
//Wait for link fn to inject it
$scope.$evalAsync(function(){ ngModel = $scope.ngModel; });
ctrl.activeMatchIndex = -1;
ctrl.updateModel = function(){
ngModel.$setViewValue(Date.now()); //Set timestamp as a unique string to force changes
ctrl.refreshComponent();
};
ctrl.refreshComponent = function(){
//Remove already selected items
//e.g. When user clicks on a selection, the selected array changes and
//the dropdown should remove that item
$select.refreshItems();
$select.sizeSearchInput();
};
// Remove item from multiple select
ctrl.removeChoice = function(index){
var removedChoice = $select.selected[index];
// if the choice is locked, can't remove it
if(removedChoice._uiSelectChoiceLocked) return;
var locals = {};
locals[$select.parserResult.itemName] = removedChoice;
$select.selected.splice(index, 1);
ctrl.activeMatchIndex = -1;
$select.sizeSearchInput();
// Give some time for scope propagation.
$timeout(function(){
$select.onRemoveCallback($scope, {
$item: removedChoice,
$model: $select.parserResult.modelMapper($scope, locals)
});
});
ctrl.updateModel();
};
ctrl.getPlaceholder = function(){
//Refactor single?
if($select.selected && $select.selected.length) return;
return $select.placeholder;
};
}],
controllerAs: '$selectMultiple',
link: function(scope, element, attrs, ctrls) {
var $select = ctrls[0];
var ngModel = scope.ngModel = ctrls[1];
var $selectMultiple = scope.$selectMultiple;
//$select.selected = raw selected objects (ignoring any property binding)
$select.multiple = true;
$select.removeSelected = true;
//Input that will handle focus
$select.focusInput = $select.searchInput;
//From view --> model
ngModel.$parsers.unshift(function () {
var locals = {},
result,
resultMultiple = [];
for (var j = $select.selected.length - 1; j >= 0; j--) {
locals = {};
locals[$select.parserResult.itemName] = $select.selected[j];
result = $select.parserResult.modelMapper(scope, locals);
resultMultiple.unshift(result);
}
return resultMultiple;
});
// From model --> view
ngModel.$formatters.unshift(function (inputValue) {
var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
locals = {},
result;
if (!data) return inputValue;
var resultMultiple = [];
var checkFnMultiple = function(list, value){
if (!list || !list.length) return;
for (var p = list.length - 1; p >= 0; p--) {
locals[$select.parserResult.itemName] = list[p];
result = $select.parserResult.modelMapper(scope, locals);
if($select.parserResult.trackByExp){
var propsItemNameMatches = /(\w*)\./.exec($select.parserResult.trackByExp);
var matches = /\.([^\s]+)/.exec($select.parserResult.trackByExp);
if(propsItemNameMatches && propsItemNameMatches.length > 0 && propsItemNameMatches[1] == $select.parserResult.itemName){
if(matches && matches.length>0 && result[matches[1]] == value[matches[1]]){
resultMultiple.unshift(list[p]);
return true;
}
}
}
if (angular.equals(result,value)){
resultMultiple.unshift(list[p]);
return true;
}
}
return false;
};
if (!inputValue) return resultMultiple; //If ngModel was undefined
for (var k = inputValue.length - 1; k >= 0; k--) {
//Check model array of currently selected items
if (!checkFnMultiple($select.selected, inputValue[k])){
//Check model array of all items available
if (!checkFnMultiple(data, inputValue[k])){
//If not found on previous lists, just add it directly to resultMultiple
resultMultiple.unshift(inputValue[k]);
}
}
}
return resultMultiple;
});
//Watch for external model changes
scope.$watchCollection(function(){ return ngModel.$modelValue; }, function(newValue, oldValue) {
if (oldValue != newValue){
ngModel.$modelValue = null; //Force scope model value and ngModel value to be out of sync to re-run formatters
$selectMultiple.refreshComponent();
}
});
ngModel.$render = function() {
// Make sure that model value is array
if(!angular.isArray(ngModel.$viewValue)){
// Have tolerance for null or undefined values
if(angular.isUndefined(ngModel.$viewValue) || ngModel.$viewValue === null){
$select.selected = [];
} else {
throw uiSelectMinErr('multiarr', "Expected model value to be array but got '{0}'", ngModel.$viewValue);
}
}
$select.selected = ngModel.$viewValue;
scope.$evalAsync(); //To force $digest
};
scope.$on('uis:select', function (event, item) {
if($select.selected.length >= $select.limit) {
return;
}
$select.selected.push(item);
$selectMultiple.updateModel();
});
scope.$on('uis:activate', function () {
$selectMultiple.activeMatchIndex = -1;
});
scope.$watch('$select.disabled', function(newValue, oldValue) {
// As the search input field may now become visible, it may be necessary to recompute its size
if (oldValue && !newValue) $select.sizeSearchInput();
});
$select.searchInput.on('keydown', function(e) {
var key = e.which;
scope.$apply(function() {
var processed = false;
// var tagged = false; //Checkme
if(KEY.isHorizontalMovement(key)){
processed = _handleMatchSelection(key);
}
if (processed && key != KEY.TAB) {
//TODO Check si el tab selecciona aun correctamente
//Crear test
e.preventDefault();
e.stopPropagation();
}
});
});
function _getCaretPosition(el) {
if(angular.isNumber(el.selectionStart)) return el.selectionStart;
// selectionStart is not supported in IE8 and we don't want hacky workarounds so we compromise
else return el.value.length;
}
// Handles selected options in "multiple" mode
function _handleMatchSelection(key){
var caretPosition = _getCaretPosition($select.searchInput[0]),
length = $select.selected.length,
// none = -1,
first = 0,
last = length-1,
curr = $selectMultiple.activeMatchIndex,
next = $selectMultiple.activeMatchIndex+1,
prev = $selectMultiple.activeMatchIndex-1,
newIndex = curr;
if(caretPosition > 0 || ($select.search.length && key == KEY.RIGHT)) return false;
$select.close();
function getNewActiveMatchIndex(){
switch(key){
case KEY.LEFT:
// Select previous/first item
if(~$selectMultiple.activeMatchIndex) return prev;
// Select last item
else return last;
break;
case KEY.RIGHT:
// Open drop-down
if(!~$selectMultiple.activeMatchIndex || curr === last){
$select.activate();
return false;
}
// Select next/last item
else return next;
break;
case KEY.BACKSPACE:
// Remove selected item and select previous/first
if(~$selectMultiple.activeMatchIndex){
$selectMultiple.removeChoice(curr);
return prev;
}
// Select last item
else return last;
break;
case KEY.DELETE:
// Remove selected item and select next item
if(~$selectMultiple.activeMatchIndex){
$selectMultiple.removeChoice($selectMultiple.activeMatchIndex);
return curr;
}
else return false;
}
}
newIndex = getNewActiveMatchIndex();
if(!$select.selected.length || newIndex === false) $selectMultiple.activeMatchIndex = -1;
else $selectMultiple.activeMatchIndex = Math.min(last,Math.max(first,newIndex));
return true;
}
$select.searchInput.on('keyup', function(e) {
if ( ! KEY.isVerticalMovement(e.which) ) {
scope.$evalAsync( function () {
$select.activeIndex = $select.taggingLabel === false ? -1 : 0;
});
}
// Push a "create new" item into array if there is a search string
if ( $select.tagging.isActivated && $select.search.length > 0 ) {
// return early with these keys
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || KEY.isVerticalMovement(e.which) ) {
return;
}
// always reset the activeIndex to the first item when tagging
$select.activeIndex = $select.taggingLabel === false ? -1 : 0;
// taggingLabel === false bypasses all of this
if ($select.taggingLabel === false) return;
var items = angular.copy( $select.items );
var stashArr = angular.copy( $select.items );
var newItem;
var item;
var hasTag = false;
var dupeIndex = -1;
var tagItems;
var tagItem;
// case for object tagging via transform `$select.tagging.fct` function
if ( $select.tagging.fct !== undefined) {
tagItems = $select.$filter('filter')(items,{'isTag': true});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
// remove the first element, if it has the `isTag` prop we generate a new one with each keyup, shaving the previous
if ( items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = $select.tagging.fct($select.search);
newItem.isTag = true;
// verify the the tag doesn't match the value of an existing item
if ( stashArr.filter( function (origItem) { return angular.equals( origItem, $select.tagging.fct($select.search) ); } ).length > 0 ) {
return;
}
newItem.isTag = true;
// handle newItem string and stripping dupes in tagging string context
} else {
// find any tagging items already in the $select.items array and store them
tagItems = $select.$filter('filter')(items,function (item) {
return item.match($select.taggingLabel);
});
if ( tagItems.length > 0 ) {
tagItem = tagItems[0];
}
item = items[0];
// remove existing tag item if found (should only ever be one tag item)
if ( item !== undefined && items.length > 0 && tagItem ) {
hasTag = true;
items = items.slice(1,items.length);
stashArr = stashArr.slice(1,stashArr.length);
}
newItem = $select.search+' '+$select.taggingLabel;
if ( _findApproxDupe($select.selected, $select.search) > -1 ) {
return;
}
// verify the the tag doesn't match the value of an existing item from
// the searched data set or the items already selected
if ( _findCaseInsensitiveDupe(stashArr.concat($select.selected)) ) {
// if there is a tag from prev iteration, strip it / queue the change
// and return early
if ( hasTag ) {
items = stashArr;
scope.$evalAsync( function () {
$select.activeIndex = 0;
$select.items = items;
});
}
return;
}
if ( _findCaseInsensitiveDupe(stashArr) ) {
// if there is a tag from prev iteration, strip it
if ( hasTag ) {
$select.items = stashArr.slice(1,stashArr.length);
}
return;
}
}
if ( hasTag ) dupeIndex = _findApproxDupe($select.selected, newItem);
// dupe found, shave the first item
if ( dupeIndex > -1 ) {
items = items.slice(dupeIndex+1,items.length-1);
} else {
items = [];
items.push(newItem);
items = items.concat(stashArr);
}
scope.$evalAsync( function () {
$select.activeIndex = 0;
$select.items = items;
});
}
});
function _findCaseInsensitiveDupe(arr) {
if ( arr === undefined || $select.search === undefined ) {
return false;
}
var hasDupe = arr.filter( function (origItem) {
if ( $select.search.toUpperCase() === undefined || origItem === undefined ) {
return false;
}
return origItem.toUpperCase() === $select.search.toUpperCase();
}).length > 0;
return hasDupe;
}
function _findApproxDupe(haystack, needle) {
var dupeIndex = -1;
if(angular.isArray(haystack)) {
var tempArr = angular.copy(haystack);
for (var i = 0; i <tempArr.length; i++) {
// handle the simple string version of tagging
if ( $select.tagging.fct === undefined ) {
// search the array for the match
if ( tempArr[i]+' '+$select.taggingLabel === needle ) {
dupeIndex = i;
}
// handle the object tagging implementation
} else {
var mockObj = tempArr[i];
if (angular.isObject(mockObj)) {
mockObj.isTag = true;
}
if ( angular.equals(mockObj, needle) ) {
dupeIndex = i;
}
}
}
}
return dupeIndex;
}
$select.searchInput.on('blur', function() {
$timeout(function() {
$selectMultiple.activeMatchIndex = -1;
});
});
}
};
}]);
uis.directive('uiSelectSingle', ['$timeout','$compile', function($timeout, $compile) {
return {
restrict: 'EA',
require: ['^uiSelect', '^ngModel'],
link: function(scope, element, attrs, ctrls) {
var $select = ctrls[0];
var ngModel = ctrls[1];
//From view --> model
ngModel.$parsers.unshift(function (inputValue) {
var locals = {},
result;
locals[$select.parserResult.itemName] = inputValue;
result = $select.parserResult.modelMapper(scope, locals);
return result;
});
//From model --> view
ngModel.$formatters.unshift(function (inputValue) {
var data = $select.parserResult.source (scope, { $select : {search:''}}), //Overwrite $search
locals = {},
result;
if (data){
var checkFnSingle = function(d){
locals[$select.parserResult.itemName] = d;
result = $select.parserResult.modelMapper(scope, locals);
return result == inputValue;
};
//If possible pass same object stored in $select.selected
if ($select.selected && checkFnSingle($select.selected)) {
return $select.selected;
}
for (var i = data.length - 1; i >= 0; i--) {
if (checkFnSingle(data[i])) return data[i];
}
}
return inputValue;
});
//Update viewValue if model change
scope.$watch('$select.selected', function(newValue) {
if (ngModel.$viewValue !== newValue) {
ngModel.$setViewValue(newValue);
}
});
ngModel.$render = function() {
$select.selected = ngModel.$viewValue;
};
scope.$on('uis:select', function (event, item) {
$select.selected = item;
});
scope.$on('uis:close', function (event, skipFocusser) {
$timeout(function(){
$select.focusser.prop('disabled', false);
if (!skipFocusser) $select.focusser[0].focus();
},0,false);
});
scope.$on('uis:activate', function () {
focusser.prop('disabled', true); //Will reactivate it on .close()
});
//Idea from: https://github.com/ivaynberg/select2/blob/79b5bf6db918d7560bdd959109b7bcfb47edaf43/select2.js#L1954
var focusser = angular.element("<input ng-disabled='$select.disabled' class='ui-select-focusser ui-select-offscreen' type='text' id='{{ $select.focusserId }}' aria-label='{{ $select.focusserTitle }}' aria-haspopup='true' role='button' />");
$compile(focusser)(scope);
$select.focusser = focusser;
//Input that will handle focus
$select.focusInput = focusser;
element.parent().append(focusser);
focusser.bind("focus", function(){
scope.$evalAsync(function(){
$select.focus = true;
});
});
focusser.bind("blur", function(){
scope.$evalAsync(function(){
$select.focus = false;
});
});
focusser.bind("keydown", function(e){
if (e.which === KEY.BACKSPACE) {
e.preventDefault();
e.stopPropagation();
$select.select(undefined);
scope.$apply();
return;
}
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC) {
return;
}
if (e.which == KEY.DOWN || e.which == KEY.UP || e.which == KEY.ENTER || e.which == KEY.SPACE){
e.preventDefault();
e.stopPropagation();
$select.activate();
}
scope.$digest();
});
focusser.bind("keyup input", function(e){
if (e.which === KEY.TAB || KEY.isControl(e) || KEY.isFunctionKey(e) || e.which === KEY.ESC || e.which == KEY.ENTER || e.which === KEY.BACKSPACE) {
return;
}
$select.activate(focusser.val()); //User pressed some regular key, so we pass it to the search input
focusser.val('');
scope.$digest();
});
}
};
}]);
// Make multiple matches sortable
uis.directive('uiSelectSort', ['$timeout', 'uiSelectConfig', 'uiSelectMinErr', function($timeout, uiSelectConfig, uiSelectMinErr) {
return {
require: '^^uiSelect',
link: function(scope, element, attrs, $select) {
if (scope[attrs.uiSelectSort] === null) {
throw uiSelectMinErr('sort', 'Expected a list to sort');
}
var options = angular.extend({
axis: 'horizontal'
},
scope.$eval(attrs.uiSelectSortOptions));
var axis = options.axis;
var draggingClassName = 'dragging';
var droppingClassName = 'dropping';
var droppingBeforeClassName = 'dropping-before';
var droppingAfterClassName = 'dropping-after';
scope.$watch(function(){
return $select.sortable;
}, function(newValue){
if (newValue) {
element.attr('draggable', true);
} else {
element.removeAttr('draggable');
}
});
element.on('dragstart', function(event) {
element.addClass(draggingClassName);
(event.dataTransfer || event.originalEvent.dataTransfer).setData('text/plain', scope.$index);
});
element.on('dragend', function() {
element.removeClass(draggingClassName);
});
var move = function(from, to) {
/*jshint validthis: true */
this.splice(to, 0, this.splice(from, 1)[0]);
};
var dragOverHandler = function(event) {
event.preventDefault();
var offset = axis === 'vertical' ? event.offsetY || event.layerY || (event.originalEvent ? event.originalEvent.offsetY : 0) : event.offsetX || event.layerX || (event.originalEvent ? event.originalEvent.offsetX : 0);
if (offset < (this[axis === 'vertical' ? 'offsetHeight' : 'offsetWidth'] / 2)) {
element.removeClass(droppingAfterClassName);
element.addClass(droppingBeforeClassName);
} else {
element.removeClass(droppingBeforeClassName);
element.addClass(droppingAfterClassName);
}
};
var dropTimeout;
var dropHandler = function(event) {
event.preventDefault();
var droppedItemIndex = parseInt((event.dataTransfer || event.originalEvent.dataTransfer).getData('text/plain'), 10);
// prevent event firing multiple times in firefox
$timeout.cancel(dropTimeout);
dropTimeout = $timeout(function() {
_dropHandler(droppedItemIndex);
}, 20);
};
var _dropHandler = function(droppedItemIndex) {
var theList = scope.$eval(attrs.uiSelectSort);
var itemToMove = theList[droppedItemIndex];
var newIndex = null;
if (element.hasClass(droppingBeforeClassName)) {
if (droppedItemIndex < scope.$index) {
newIndex = scope.$index - 1;
} else {
newIndex = scope.$index;
}
} else {
if (droppedItemIndex < scope.$index) {
newIndex = scope.$index;
} else {
newIndex = scope.$index + 1;
}
}
move.apply(theList, [droppedItemIndex, newIndex]);
scope.$apply(function() {
scope.$emit('uiSelectSort:change', {
array: theList,
item: itemToMove,
from: droppedItemIndex,
to: newIndex
});
});
element.removeClass(droppingClassName);
element.removeClass(droppingBeforeClassName);
element.removeClass(droppingAfterClassName);
element.off('drop', dropHandler);
};
element.on('dragenter', function() {
if (element.hasClass(draggingClassName)) {
return;
}
element.addClass(droppingClassName);
element.on('dragover', dragOverHandler);
element.on('drop', dropHandler);
});
element.on('dragleave', function(event) {
if (event.target != element) {
return;
}
element.removeClass(droppingClassName);
element.removeClass(droppingBeforeClassName);
element.removeClass(droppingAfterClassName);
element.off('dragover', dragOverHandler);
element.off('drop', dropHandler);
});
}
};
}]);
/**
* Parses "repeat" attribute.
*
* Taken from AngularJS ngRepeat source code
* See https://github.com/angular/angular.js/blob/v1.2.15/src/ng/directive/ngRepeat.js#L211
*
* Original discussion about parsing "repeat" attribute instead of fully relying on ng-repeat:
* https://github.com/angular-ui/ui-select/commit/5dd63ad#commitcomment-5504697
*/
uis.service('uisRepeatParser', ['uiSelectMinErr','$parse', function(uiSelectMinErr, $parse) {
var self = this;
/**
* Example:
* expression = "address in addresses | filter: {street: $select.search} track by $index"
* itemName = "address",
* source = "addresses | filter: {street: $select.search}",
* trackByExp = "$index",
*/
self.parse = function(expression) {
var match;
var isObjectCollection = /\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)/.test(expression);
// If an array is used as collection
// if (isObjectCollection){
//00000000000000000000000000000111111111000000000000000222222222222220033333333333333333333330000444444444444444444000000000000000556666660000077777777777755000000000000000000000088888880000000
match = expression.match(/^\s*(?:([\s\S]+?)\s+as\s+)?(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(([\w\.]+)?\s*(|\s*[\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
// 1 Alias
// 2 Item
// 3 Key on (key,value)
// 4 Value on (key,value)
// 5 Collection expresion (only used when using an array collection)
// 6 Object that will be converted to Array when using (key,value) syntax
// 7 Filters that will be applied to #6 when using (key,value) syntax
// 8 Track by
if (!match) {
throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
if (!match[6] && isObjectCollection) {
throw uiSelectMinErr('iexp', "Expected expression in form of '_item_ as (_key_, _item_) in _ObjCollection_ [ track by _id_]' but got '{0}'.",
expression);
}
return {
itemName: match[4] || match[2], // (lhs) Left-hand side,
keyName: match[3], //for (key, value) syntax
source: $parse(!match[3] ? match[5] : match[6]),
sourceName: match[6],
filters: match[7],
trackByExp: match[8],
modelMapper: $parse(match[1] || match[4] || match[2]),
repeatExpression: function (grouped) {
var expression = this.itemName + ' in ' + (grouped ? '$group.items' : '$select.items');
if (this.trackByExp) {
expression += ' track by ' + this.trackByExp;
}
return expression;
}
};
};
self.getGroupNgRepeatExpression = function() {
return '$group in $select.groups';
};
}]);
}());
angular.module("ui.select").run(["$templateCache", function($templateCache) {$templateCache.put("bootstrap/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content ui-select-dropdown dropdown-menu\" role=\"listbox\" ng-show=\"$select.items.length > 0\"><li class=\"ui-select-choices-group\" id=\"ui-select-choices-{{ $select.generatedId }}\"><div class=\"divider\" ng-show=\"$select.isGrouped && $index > 0\"></div><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label dropdown-header\" ng-bind=\"$group.name\"></div><div id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\" role=\"option\"><a href=\"\" class=\"ui-select-choices-row-inner\"></a></div></li></ul>");
$templateCache.put("bootstrap/match-multiple.tpl.html","<span class=\"ui-select-match\"><span ng-repeat=\"$item in $select.selected\"><span class=\"ui-select-match-item btn btn-default btn-xs\" tabindex=\"-1\" type=\"button\" ng-disabled=\"$select.disabled\" ng-click=\"$selectMultiple.activeMatchIndex = $index;\" ng-class=\"{\'btn-primary\':$selectMultiple.activeMatchIndex === $index, \'select-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span class=\"close ui-select-match-close\" ng-hide=\"$select.disabled\" ng-click=\"$selectMultiple.removeChoice($index)\"> ×</span> <span uis-transclude-append=\"\"></span></span></span></span>");
$templateCache.put("bootstrap/match.tpl.html","<div class=\"ui-select-match\" ng-hide=\"$select.open\" ng-disabled=\"$select.disabled\" ng-class=\"{\'btn-default-focus\':$select.focus}\"><span tabindex=\"-1\" class=\"btn btn-default form-control ui-select-toggle\" aria-label=\"{{ $select.baseTitle }} activate\" ng-disabled=\"$select.disabled\" ng-click=\"$select.activate()\" style=\"outline: 0;\"><span ng-show=\"$select.isEmpty()\" class=\"ui-select-placeholder text-muted\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"ui-select-match-text pull-left\" ng-class=\"{\'ui-select-allow-clear\': $select.allowClear && !$select.isEmpty()}\" ng-transclude=\"\"></span> <i class=\"caret pull-right\" ng-click=\"$select.toggle($event)\"></i> <a ng-show=\"$select.allowClear && !$select.isEmpty()\" aria-label=\"{{ $select.baseTitle }} clear\" style=\"margin-right: 10px\" ng-click=\"$select.clear($event)\" class=\"btn btn-xs btn-link pull-right\"><i class=\"glyphicon glyphicon-remove\" aria-hidden=\"true\"></i></a></span></div>");
$templateCache.put("bootstrap/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple ui-select-bootstrap dropdown form-control\" ng-class=\"{open: $select.open}\"><div><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"false\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" class=\"ui-select-search input-xs\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-click=\"$select.activate()\" ng-model=\"$select.search\" role=\"combobox\" aria-label=\"{{ $select.baseTitle }}\" ondrop=\"return false;\"></div><div class=\"ui-select-choices\"></div></div>");
$templateCache.put("bootstrap/select.tpl.html","<div class=\"ui-select-container ui-select-bootstrap dropdown\" ng-class=\"{open: $select.open}\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"false\" tabindex=\"-1\" aria-expanded=\"true\" aria-label=\"{{ $select.baseTitle }}\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"form-control ui-select-search\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-show=\"$select.searchEnabled && $select.open\"><div class=\"ui-select-choices\"></div></div>");
$templateCache.put("select2/choices.tpl.html","<ul class=\"ui-select-choices ui-select-choices-content select2-results\"><li class=\"ui-select-choices-group\" ng-class=\"{\'select2-result-with-children\': $select.choiceGrouped($group) }\"><div ng-show=\"$select.choiceGrouped($group)\" class=\"ui-select-choices-group-label select2-result-label\" ng-bind=\"$group.name\"></div><ul role=\"listbox\" id=\"ui-select-choices-{{ $select.generatedId }}\" ng-class=\"{\'select2-result-sub\': $select.choiceGrouped($group), \'select2-result-single\': !$select.choiceGrouped($group) }\"><li role=\"option\" id=\"ui-select-choices-row-{{ $select.generatedId }}-{{$index}}\" class=\"ui-select-choices-row\" ng-class=\"{\'select2-highlighted\': $select.isActive(this), \'select2-disabled\': $select.isDisabled(this)}\"><div class=\"select2-result-label ui-select-choices-row-inner\"></div></li></ul></li></ul>");
$templateCache.put("select2/match-multiple.tpl.html","<span class=\"ui-select-match\"><li class=\"ui-select-match-item select2-search-choice\" ng-repeat=\"$item in $select.selected\" ng-class=\"{\'select2-search-choice-focus\':$selectMultiple.activeMatchIndex === $index, \'select2-locked\':$select.isLocked(this, $index)}\" ui-select-sort=\"$select.selected\"><span uis-transclude-append=\"\"></span> <a href=\"javascript:;\" class=\"ui-select-match-close select2-search-choice-close\" ng-click=\"$selectMultiple.removeChoice($index)\" tabindex=\"-1\"></a></li></span>");
$templateCache.put("select2/match.tpl.html","<a class=\"select2-choice ui-select-match\" ng-class=\"{\'select2-default\': $select.isEmpty()}\" ng-click=\"$select.toggle($event)\" aria-label=\"{{ $select.baseTitle }} select\"><span ng-show=\"$select.isEmpty()\" class=\"select2-chosen\">{{$select.placeholder}}</span> <span ng-hide=\"$select.isEmpty()\" class=\"select2-chosen\" ng-transclude=\"\"></span> <abbr ng-if=\"$select.allowClear && !$select.isEmpty()\" class=\"select2-search-choice-close\" ng-click=\"$select.clear($event)\"></abbr> <span class=\"select2-arrow ui-select-toggle\"><b></b></span></a>");
$templateCache.put("select2/select-multiple.tpl.html","<div class=\"ui-select-container ui-select-multiple select2 select2-container select2-container-multi\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled}\"><ul class=\"select2-choices\"><span class=\"ui-select-match\"></span><li class=\"select2-search-field\"><input type=\"text\" autocomplete=\"false\" autocorrect=\"off\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"select2-input ui-select-search\" placeholder=\"{{$selectMultiple.getPlaceholder()}}\" ng-disabled=\"$select.disabled\" ng-hide=\"$select.disabled\" ng-model=\"$select.search\" ng-click=\"$select.activate()\" style=\"width: 34px;\" ondrop=\"return false;\"></li></ul><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"ui-select-choices\"></div></div></div>");
$templateCache.put("select2/select.tpl.html","<div class=\"ui-select-container select2 select2-container\" ng-class=\"{\'select2-container-active select2-dropdown-open open\': $select.open, \'select2-container-disabled\': $select.disabled, \'select2-container-active\': $select.focus, \'select2-allowclear\': $select.allowClear && !$select.isEmpty()}\"><div class=\"ui-select-match\"></div><div class=\"ui-select-dropdown select2-drop select2-with-searchbox select2-drop-active\" ng-class=\"{\'select2-display-none\': !$select.open}\"><div class=\"select2-search\" ng-show=\"$select.searchEnabled\"><input type=\"text\" autocomplete=\"false\" autocorrect=\"false\" autocapitalize=\"off\" spellcheck=\"false\" role=\"combobox\" aria-expanded=\"true\" aria-owns=\"ui-select-choices-{{ $select.generatedId }}\" aria-label=\"{{ $select.baseTitle }}\" aria-activedescendant=\"ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}\" class=\"ui-select-search select2-input\" ng-model=\"$select.search\"></div><div class=\"ui-select-choices\"></div></div></div>");
$templateCache.put("selectize/choices.tpl.html","<div ng-show=\"$select.open\" class=\"ui-select-choices ui-select-dropdown selectize-dropdown single\"><div class=\"ui-select-choices-content selectize-dropdown-content\"><div class=\"ui-select-choices-group optgroup\" role=\"listbox\"><div ng-show=\"$select.isGrouped\" class=\"ui-select-choices-group-label optgroup-header\" ng-bind=\"$group.name\"></div><div role=\"option\" class=\"ui-select-choices-row\" ng-class=\"{active: $select.isActive(this), disabled: $select.isDisabled(this)}\"><div class=\"option ui-select-choices-row-inner\" data-selectable=\"\"></div></div></div></div></div>");
$templateCache.put("selectize/match.tpl.html","<div ng-hide=\"($select.open || $select.isEmpty())\" class=\"ui-select-match\" ng-transclude=\"\"></div>");
$templateCache.put("selectize/select.tpl.html","<div class=\"ui-select-container selectize-control single\" ng-class=\"{\'open\': $select.open}\"><div class=\"selectize-input\" ng-class=\"{\'focus\': $select.open, \'disabled\': $select.disabled, \'selectize-focus\' : $select.focus}\" ng-click=\"$select.open && !$select.searchEnabled ? $select.toggle($event) : $select.activate()\"><div class=\"ui-select-match\"></div><input type=\"text\" autocomplete=\"false\" tabindex=\"-1\" class=\"ui-select-search ui-select-toggle\" ng-click=\"$select.toggle($event)\" placeholder=\"{{$select.placeholder}}\" ng-model=\"$select.search\" ng-hide=\"!$select.searchEnabled || ($select.selected && !$select.open)\" ng-disabled=\"$select.disabled\" aria-label=\"{{ $select.baseTitle }}\"></div><div class=\"ui-select-choices\"></div></div>");}]); |
src/static/containers/Login/index.js | AdrienAgnel/testDjangoApp | import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import classNames from 'classnames';
import { push } from 'react-router-redux';
import t from 'tcomb-form';
import PropTypes from 'prop-types';
import * as actionCreators from '../../actions/auth';
const Form = t.form.Form;
const Login = t.struct({
email: t.String,
password: t.String
});
const LoginFormOptions = {
auto: 'placeholders',
help: <i>Hint: [email protected] / qw</i>,
fields: {
password: {
type: 'password'
}
}
};
class LoginView extends React.Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
isAuthenticating: PropTypes.bool.isRequired,
statusText: PropTypes.string,
actions: PropTypes.shape({
authLoginUser: PropTypes.func.isRequired
}).isRequired,
location: PropTypes.shape({
search: PropTypes.string.isRequired
})
};
static defaultProps = {
statusText: '',
location: null
};
constructor(props) {
super(props);
const redirectRoute = this.props.location ? this.extractRedirect(this.props.location.search) || '/' : '/';
this.state = {
formValues: {
email: '',
password: ''
},
redirectTo: redirectRoute
};
}
componentWillMount() {
if (this.props.isAuthenticated) {
this.props.dispatch(push('/'));
}
}
onFormChange = (value) => {
this.setState({ formValues: value });
};
extractRedirect = (string) => {
const match = string.match(/next=(.*)/);
return match ? match[1] : '/';
};
login = (e) => {
e.preventDefault();
const value = this.loginForm.getValue();
if (value) {
this.props.actions.authLoginUser(value.email, value.password, this.state.redirectTo);
}
};
render() {
let statusText = null;
if (this.props.statusText) {
const statusTextClassNames = classNames({
'alert': true,
'alert-danger': this.props.statusText.indexOf('Authentication Error') === 0,
'alert-success': this.props.statusText.indexOf('Authentication Error') !== 0
});
statusText = (
<div className="row">
<div className="col-sm-12">
<div className={statusTextClassNames}>
{this.props.statusText}
</div>
</div>
</div>
);
}
return (
<div className="container login">
<h1 className="text-center">Login</h1>
<div className="login-container margin-top-medium">
{statusText}
<form onSubmit={this.login}>
<Form ref={(ref) => { this.loginForm = ref; }}
type={Login}
options={LoginFormOptions}
value={this.state.formValues}
onChange={this.onFormChange}
/>
<button disabled={this.props.isAuthenticating}
type="submit"
className="btn btn-default btn-block"
>
Submit
</button>
</form>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.isAuthenticated,
isAuthenticating: state.auth.isAuthenticating,
statusText: state.auth.statusText
};
};
const mapDispatchToProps = (dispatch) => {
return {
dispatch,
actions: bindActionCreators(actionCreators, dispatch)
};
};
export default connect(mapStateToProps, mapDispatchToProps)(LoginView);
export { LoginView as LoginViewNotConnected };
|
src/frontend/components/Unauthorized.js | al3x/ground-control | import React from 'react';
import {BernieTheme} from './styles/bernie-theme';
import {BernieColors, BernieText} from './styles/bernie-css';
export default class Unauthorized extends React.Component {
render() {
return (
<div>
You don't have access to that.
</div>
)
}
} |
js/views/RegistrationPagePart1.js | ecohealthalliance/GoodQuestion | import React from 'react';
import {
Text,
TextInput,
View,
ScrollView,
} from 'react-native';
import Variables from '../styles/Variables';
import Styles from '../styles/Styles';
import Button from '../components/Button';
import Checkbox from '../components/Checkbox';
import Footer from '../components/Footer';
import Icon from 'react-native-vector-icons/FontAwesome';
const uncheckedComponent = <Icon name='square-o' size={30} />;
const checkedComponent = <Icon name='check-square-o' size={30} />;
import Joi from '../lib/joi-browser.min';
import JoiMixins from '../mixins/joi-mixins';
import EventMixins from '../mixins/event-mixins';
const RegistrationPagePart1 = React.createClass({
propTypes: {
navigator: React.PropTypes.object.isRequired,
},
styles: {
checkboxWrapper: {
alignItems: 'center',
justifyContent: 'center',
marginLeft: 50,
height: 35,
},
},
formInputs: [
'email',
'password',
'confirmPassword',
'acceptedTerms',
],
mixins: [
JoiMixins,
EventMixins,
],
schema: {
email: Joi.string().email({minDomainAtoms: 2}).required().options(
{language: {any: {allowOnly: 'must be a valid email'}}}).label('Email'),
password: Joi.string().regex(/^([a-zA-Z0-9@*#]{8,15})$/).required().options(
{language: {string: {regex: {base: 'must be between 8 and 15 alphanumeric characters'}}}}).label('Password'),
confirmPassword: Joi.string().regex(/^([a-zA-Z0-9@*#]{8,15})$/).required().options(
{language: {string: {regex: {base: 'must be between 8 and 15 alphanumeric characters'}}}}).label('Confirm Password'),
acceptedTerms: Joi.boolean().required().invalid(false).options(
{language: {any: {invalid: 'must be accepted'}}}).label('Terms of Service'),
},
getInitialState() {
return {
title: 'Registration',
buttonText: 'Next',
email: '',
password: '',
confirmPassword: '',
acceptedTerms: false,
errors: {},
};
},
/* Methods */
goToTermsPage() {
this.props.navigator.push({path: 'terms', unsecured: true, title: 'Terms of Service'});
},
goToNextPage() {
const errors = this.props.validatePage(0);
if (Object.keys(errors).length <= 0) {
this.props.setIndex(1);
return;
}
},
confirmPasswordChangeHandler(name, value) {
const password = this.state.password;
const errors = Object.assign({}, this.state.errors);
const state = {
errors: errors,
};
if (password !== value) {
state.errors[name] = '"Confirm Password" does not match password';
state[name] = value;
this.setState(state);
return;
}
// continue with mixin handler
this.textFieldChangeHandler(name, value);
},
renderTerms() {
return (
<Text style={[Styles.type.h3, {textAlign: 'center', paddingBottom: 2, position: 'relative'}]}>
<Text>I accept the </Text>
<Text style={Styles.type.link} onPress={this.goToTermsPage}>Terms of Service.</Text>
</Text>
);
},
/* Render */
render() {
this.props.buttonStyles(this, this.formInputs);
return (
<View style={[Styles.container.defaultWhite]}>
<ScrollView
ref='scrollView'
horizontal={false}
keyboardShouldPersistTaps={true}
keyboardDismissMode='on-drag'
style={Styles.form.registrationView}>
<View style={{paddingBottom: 50}}>
<Text style={[Styles.type.h1, {textAlign: 'center'}]} >
Create an Account
</Text>
<View style={Styles.form.inputGroup}>
<Text style={Styles.form.errorText}>
{this.decodeText(this.state.errors.email)}
</Text>
<View ref='emailView'>
<TextInput
ref='email'
style={Styles.form.input}
onChangeText={this.textFieldChangeHandler.bind(null, 'email')}
onFocus={this.scrollToViewWrapper.bind(null, 'scrollView', 'emailView', Variables.REGISTRATION_HEIGHT)}
onBlur={this.trimText.bind(null, 'email')}
value={this.state.email}
autoCapitalize='none'
autoCorrect={false}
returnKeyType='done'
placeholder='Email'
/>
</View>
<Text style={Styles.form.errorText}>
{this.decodeText(this.state.errors.password)}
</Text>
<View ref='passwordView'>
<TextInput
ref='password'
secureTextEntry={true}
style={Styles.form.input}
onChangeText={this.textFieldChangeHandler.bind(null, 'password')}
onFocus={this.scrollToViewWrapper.bind(null, 'scrollView', 'passwordView', Variables.REGISTRATION_HEIGHT)}
onBlur={this.trimText.bind(null, 'password')}
value={this.state.password}
autoCapitalize='none'
autoCorrect={false}
returnKeyType='done'
placeholder='Password'
/>
</View>
<Text style={Styles.form.errorText}>
{this.decodeText(this.state.errors.confirmPassword)}
</Text>
<View ref='confirmPasswordView'>
<TextInput
ref='confirmPassword'
secureTextEntry={true}
style={Styles.form.input}
onChangeText={this.confirmPasswordChangeHandler.bind(null, 'confirmPassword')}
onFocus={this.scrollToViewWrapper.bind(null, 'scrollView', 'confirmPasswordView', Variables.REGISTRATION_HEIGHT)}
onBlur={this.trimText.bind(null, 'confirmPassword')}
value={this.state.confirmPassword}
autoCapitalize='none'
autoCorrect={false}
returnKeyType='done'
placeholder='Confirm Password'
/>
</View>
<Text style={Styles.form.errorText}>
{this.decodeText(this.state.errors.acceptedTerms)}
</Text>
<View style={this.styles.checkboxWrapper}>
<Checkbox
children={this.renderTerms()}
checked={this.state.acceptedTerms}
uncheckedComponent={uncheckedComponent}
checkedComponent={checkedComponent}
onChange={this.checkboxChangeHandler.bind(null, 'acceptedTerms')}
/>
</View>
</View>
</View>
</ScrollView>
<Footer>
<Button action={this.goToNextPage} style={this.buttonStyles} textStyle={this.buttonTextStyles}>
{this.state.buttonText}
</Button>
</Footer>
</View>
);
},
});
module.exports = RegistrationPagePart1;
|
app/actions/user.js | typesettin/manuscript | import constants from '../constants';
import LoginSettings from '../../content/config/login.json';
import AppConfigSettings from '../../content/config/settings.json';
import { AsyncStorage, } from 'react-native';
import pageActions from './pages';
import { Platform, } from 'react-native';
// import Immutable from 'immutable';
const checkStatus = function (response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
let error = new Error(response.statusText);
error.response = response;
throw error;
}
};
const user = {
/**
* @param {string} url restful resource
*/
loginRequest(url) {
return {
type: constants.user.LOGIN_DATA_REQUEST,
payload: {
url,
},
};
},
/**
* @param {string} location name of extension to load
* @param {object} options what-wg fetch options
*/
recievedLoginUser(url, response, json) {
return {
type: constants.user.LOGIN_DATA_SUCCESS,
payload: {
url,
response,
json,
updatedAt: new Date(),
timestamp: Date.now(),
},
};
},
/**
* @param {string} location name of extension to load
* @param {object} options what-wg fetch options
*/
saveUserProfile(url, response, json) {
return {
type: constants.user.SAVE_DATA_SUCCESS,
payload: {
url,
response,
json,
updatedAt: new Date(),
timestamp: Date.now(),
},
};
},
/**
* @param {string} location name of extension to load
*/
failedUserRequest(url, error) {
return {
type: constants.user.USER_DATA_FAILURE,
payload: {
url,
error,
updatedAt: new Date(),
timestamp: Date.now(),
},
};
},
logoutUserSuccess() {
return {
type: constants.user.LOGOUT_SUCCESS,
payload: {
updatedAt: new Date(),
timestamp: Date.now(),
},
};
},
failedLogoutRequest(error) {
return {
type: constants.user.LOGOUT_FAILURE,
payload: {
error,
updatedAt: new Date(),
timestamp: Date.now(),
},
};
},
logoutUser() {
return (dispatch) => {
dispatch(pageActions.resetAppLoadedState());
Promise.all([
AsyncStorage.removeItem(constants.jwt_token.TOKEN_NAME),
AsyncStorage.removeItem(constants.jwt_token.TOKEN_DATA),
AsyncStorage.removeItem(constants.jwt_token.PROFILE_JSON),
AsyncStorage.removeItem(constants.pages.ASYNCSTORAGE_KEY),
])
.then(results => {
// console.log('logout user results', results);
dispatch(this.logoutUserSuccess());
dispatch(pageActions.initialAppLoaded());
})
.catch(error => {
dispatch(this.failedLogoutRequest(error));
dispatch(pageActions.initialAppLoaded());
});
};
},
getUserProfile(jwt_token, responseFormatter) {
return (dispatch, getState) => {
let fetchResponse;
let url = LoginSettings[ getState().page.runtime.environment ].userprofile.url;
dispatch(this.loginRequest(url));
fetch(url, {
method: LoginSettings[getState().page.runtime.environment].userprofile.method || 'POST',
headers: Object.assign({
'Accept': 'application/json',
'Content-Type': 'application/json',
}, LoginSettings[getState().page.runtime.environment].userprofile.options.headers, {
'x-access-token': jwt_token,
}),
// body: JSON.stringify({
// username: loginData.username,
// password: loginData.password,
// })
})
.then(checkStatus)
.then((response) => {
fetchResponse = response;
if (responseFormatter) {
let formatterPromise = responseFormatter(response);
if (formatterPromise instanceof Promise) {
return formatterPromise;
} else {
throw new Error('responseFormatter must return a Promise');
}
} else {
return response.json();
}
})
.then((responseData) => {
AsyncStorage.setItem(constants.jwt_token.PROFILE_JSON, JSON.stringify(responseData.user));
dispatch(this.saveUserProfile(url, fetchResponse, responseData));
})
.catch((error) => {
dispatch(this.failedUserRequest(url, error));
});
}
},
/**
* @param {string} url url for fetch request
* @param {object} options what-wg fetch options
* @param {function} responseFormatter custom reponse formatter, must be a function that returns a promise that resolves to json/javascript object
*/
loginUser(loginData, responseFormatter) {
return (dispatch, getState) => {
let fetchResponse;
let cachedResponseData;
let url = LoginSettings[getState().page.runtime.environment].login.url;
dispatch(this.loginRequest(url));
fetch(url, {
method: LoginSettings[getState().page.runtime.environment].login.method || 'POST',
headers: Object.assign({
'Accept': 'application/json',
'Content-Type': 'application/json',
}, LoginSettings[getState().page.runtime.environment].login.options.headers, {
username: loginData.username,
password: loginData.password,
}),
// body: JSON.stringify({
// username: loginData.username,
// password: loginData.password,
// })
})
.then(checkStatus)
.then((response) => {
fetchResponse = response;
if (responseFormatter) {
let formatterPromise = responseFormatter(response);
if (formatterPromise instanceof Promise) {
return formatterPromise;
} else {
throw new Error('responseFormatter must return a Promise');
}
} else {
return response.json();
}
})
.then((responseData) => {
cachedResponseData = responseData;
return Promise.all([
AsyncStorage.setItem(constants.jwt_token.TOKEN_NAME, responseData.token),
AsyncStorage.setItem(constants.jwt_token.TOKEN_DATA, JSON.stringify({
expires: responseData.expires,
timeout: responseData.timeout,
token: responseData.token,
})),
AsyncStorage.setItem(constants.jwt_token.PROFILE_JSON, JSON.stringify(responseData.user)),
]);
// console.log('login USER responseData', responseData);
})
.then(() => {
dispatch(this.recievedLoginUser(url, fetchResponse, cachedResponseData));
})
.catch((error) => {
dispatch(this.failedUserRequest(url, error));
});
};
},
};
export default user; |
internals/templates/appContainer.js | kenaku/react-boilerplate | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import styles from './styles.css';
export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div className={styles.container}>
{this.props.children}
</div>
);
}
}
|
ajax/libs/inferno/1.0.0-beta33/inferno-compat.min.js | hare1039/cdnjs | !function(n,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("./inferno-component"),require("./inferno")):"function"==typeof define&&define.amd?define(["exports","inferno-component","inferno"],e):e(n.Inferno=n.Inferno||{},n.Inferno.Component,n.Inferno)}(this,function(n,e,r){"use strict";function t(n,e){return e={exports:{}},n(e,e.exports),e.exports}function o(n){return!d(n.prototype)&&!d(n.prototype.render)}function i(n){return d(n)||l(n)}function u(n){return l(n)||n===!1||p(n)||d(n)}function a(n){return"function"==typeof n}function f(n){return"o"===n[0]&&"n"===n[1]&&n.length>3}function c(n){return"string"==typeof n}function l(n){return null===n}function p(n){return n===!0}function d(n){return void 0===n}function s(n){return"object"==typeof n}function y(n){var e=s(n)&&l(n)===!1;if(e===!1)return!1;var r=n.flags;return!!(3998&r)}function v(n,e,r){for(var t in e)r!==!0&&i(e[t])||(n[t]=e[t]);return n}function m(n){for(var e in n){var r=n[e];"function"!=typeof r||r.__bound||P[e]||((n[e]=r.bind(n)).__bound=!0)}}function h(n,e){void 0===e&&(e={});for(var r=0;r<n.length;r++){var t=n[r];t.mixins&&h(t.mixins,e);for(var o in t)t.hasOwnProperty(o)&&"function"==typeof t[o]&&(e[o]||(e[o]=[])).push(t[o])}return e}function b(n,e,r){var t=e[n];e[n]=function(){for(var n,o=arguments,i=0;i<r.length;i++){var u=r[i],a=u.apply(e,o);d(a)||(n=a)}if(t){var f=t.call(e);d(f)||(n=f)}return n}}function x(n,e){for(var r in e)if(e.hasOwnProperty(r)){var t=e[r];a(t[0])?b(r,n,t):n[r]=t}}function g(n){var r=function(e){function r(t){e.call(this,t),this.isMounted=function(){return!this._unmounted},v(this,n),r.mixins&&x(this,r.mixins),m(this),n.getInitialState&&(this.state=n.getInitialState.call(this))}return e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r,r}(e);return r.displayName=n.displayName||"Component",r.propTypes=n.propTypes,r.defaultProps=n.getDefaultProps?n.getDefaultProps():void 0,r.mixins=n.mixins&&h(n.mixins),n.statics&&v(r,n.statics),r}function E(n,e){for(var t=[],i=arguments.length-2;i-- >0;)t[i]=arguments[i+2];if(u(n)||s(n))throw new Error("Inferno Error: createElement() name paramater cannot be undefined, null, false or true, It must be a string, class or function.");var a=t,l=null,p=null,y=null,v=0;if(t&&(1===t.length?a=t[0]:0===t.length&&(a=void 0)),c(n)){switch(v=2,n){case"svg":v=128;break;case"input":v=512;break;case"textarea":v=1024;break;case"select":v=2048}for(var m in e)"key"===m?(p=e.key,delete e.key):"children"===m&&d(a)?a=e.children:"ref"===m?l=e.ref:f(m)&&(y||(y={}),y[m]=e[m],delete e[m])}else{v=o(n)?4:8,d(a)||(e||(e={}),e.children=a,a=null);for(var h in e)j[h]?(l||(l={}),l[h]=e[h]):"key"===h&&(p=e.key,delete e.key)}return r.createVNode(v,n,e,a,y,p,l)}function C(n){return r.render(null,n),!0}function w(n,e){if(("input"===n||"textarea"===n)&&e.onChange){var r="checkbox"===e.type?"onclick":"oninput";e[r]||(e[r]=e.onChange,delete e.onChange)}}function O(n,e){for(var r in n)if(!(r in e))return!0;for(var t in e)if(n[t]!==e[t])return!0;return!1}function N(n,r){e.call(this,n,r)}function _(n,e,t,o){var i=r.createVNode(4,T,{context:n.context,children:e}),u=r.render(i,t);return o&&o(u),u}e="default"in e?e.default:e;var A="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},I=t(function(n,e){!function(r,t){if("function"==typeof define&&define.amd)define("PropTypes",["exports","module"],t);else if("undefined"!=typeof e&&"undefined"!=typeof n)t(e,n);else{var o={exports:{}};t(o.exports,o),r.PropTypes=o.exports}}(A,function(n,e){function r(n){var e=n&&(C&&n[C]||n[w]);if("function"==typeof e)return e}function t(n){function e(e,r,t,o,i,u){if(o=o||O,u=u||t,null==r[t]){var a=g[i];return e?new Error("Required "+a+" `"+u+"` was not specified in "+("`"+o+"`.")):null}return n(r,t,o,i,u)}var r=e.bind(null,!1);return r.isRequired=e.bind(null,!0),r}function o(n){function e(e,r,t,o,i){var u=e[r],a=v(u);if(a!==n){var f=g[o],c=m(u);return new Error("Invalid "+f+" `"+i+"` of type "+("`"+c+"` supplied to `"+t+"`, expected ")+("`"+n+"`."))}return null}return t(e)}function i(){return t(E.thatReturns(null))}function u(n){function e(e,r,t,o,i){var u=e[r];if(!Array.isArray(u)){var a=g[o],f=v(u);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+f+"` supplied to `"+t+"`, expected an array."))}for(var c=0;c<u.length;c++){var l=n(u,c,t,o,i+"["+c+"]");if(l instanceof Error)return l}return null}return t(e)}function a(){function n(n,e,r,t,o){if(!x.isValidElement(n[e])){var i=g[t];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+r+"`, expected a single ReactElement."))}return null}return t(n)}function f(n){function e(e,r,t,o,i){if(!(e[r]instanceof n)){var u=g[o],a=n.name||O,f=h(e[r]);return new Error("Invalid "+u+" `"+i+"` of type "+("`"+f+"` supplied to `"+t+"`, expected ")+("instance of `"+a+"`."))}return null}return t(e)}function c(n){function e(e,r,t,o,i){for(var u=e[r],a=0;a<n.length;a++)if(u===n[a])return null;var f=g[o],c=JSON.stringify(n);return new Error("Invalid "+f+" `"+i+"` of value `"+u+"` "+("supplied to `"+t+"`, expected one of "+c+"."))}return t(Array.isArray(n)?e:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function l(n){function e(e,r,t,o,i){var u=e[r],a=v(u);if("object"!==a){var f=g[o];return new Error("Invalid "+f+" `"+i+"` of type "+("`"+a+"` supplied to `"+t+"`, expected an object."))}for(var c in u)if(u.hasOwnProperty(c)){var l=n(u,c,t,o,i+"."+c);if(l instanceof Error)return l}return null}return t(e)}function p(n){function e(e,r,t,o,i){for(var u=0;u<n.length;u++){var a=n[u];if(null==a(e,r,t,o,i))return null}var f=g[o];return new Error("Invalid "+f+" `"+i+"` supplied to "+("`"+t+"`."))}return t(Array.isArray(n)?e:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function d(){function n(n,e,r,t,o){if(!y(n[e])){var i=g[t];return new Error("Invalid "+i+" `"+o+"` supplied to "+("`"+r+"`, expected a ReactNode."))}return null}return t(n)}function s(n){function e(e,r,t,o,i){var u=e[r],a=v(u);if("object"!==a){var f=g[o];return new Error("Invalid "+f+" `"+i+"` of type `"+a+"` "+("supplied to `"+t+"`, expected `object`."))}for(var c in n){var l=n[c];if(l){var p=l(u,c,t,o,i+"."+c);if(p)return p}}return null}return t(e)}function y(n){switch(typeof n){case"number":case"string":case"undefined":return!0;case"boolean":return!n;case"object":if(Array.isArray(n))return n.every(y);if(null===n||x.isValidElement(n))return!0;var e=r(n);if(!e)return!1;var t,o=e.call(n);if(e!==n.entries){for(;!(t=o.next()).done;)if(!y(t.value))return!1}else for(;!(t=o.next()).done;){var i=t.value;if(i&&!y(i[1]))return!1}return!0;default:return!1}}function v(n){var e=typeof n;return Array.isArray(n)?"array":n instanceof RegExp?"object":e}function m(n){var e=v(n);if("object"===e){if(n instanceof Date)return"date";if(n instanceof RegExp)return"regexp"}return e}function h(n){return n.constructor&&n.constructor.name?n.constructor.name:O}var b="function"==typeof Symbol&&Symbol.for&&Symbol.for("react.element")||60103,x={};x.isValidElement=function(n){return"object"==typeof n&&null!==n&&n.$$typeof===b};var g={prop:"prop",context:"context",childContext:"child context"},E={thatReturns:function(n){return function(){return n}}},C="function"==typeof Symbol&&Symbol.iterator,w="@@iterator",O="<<anonymous>>",N={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:u,element:a(),instanceOf:f,node:d(),objectOf:l,oneOf:c,oneOfType:p,shape:s};e.exports=N})}),P={constructor:1,render:1,shouldComponentUpdate:1,componentWillReceiveProps:1,componentWillUpdate:1,componentDidUpdate:1,componentWillMount:1,componentDidMount:1,componentWillUnmount:1,componentDidUnmount:1},j={onComponentWillMount:!0,onComponentDidMount:!0,onComponentWillUnmount:!0,onComponentShouldUpdate:!0,onComponentWillUpdate:!0,onComponentDidUpdate:!0};r.enableFindDOMNode();var V=[],D={map:function(n,e,r){return n=D.toArray(n),r&&r!==n&&(e=e.bind(r)),n.map(e)},forEach:function(n,e,r){n=D.toArray(n),r&&r!==n&&(e=e.bind(r)),n.forEach(e)},count:function(n){return n=D.toArray(n),n.length},only:function(n){if(n=D.toArray(n),1!==n.length)throw new Error("Children.only() expects only one child.");return n[0]},toArray:function(n){return Array.isArray&&Array.isArray(n)?n:V.concat(n)}},R=null;e.prototype.isReactComponent={},e.prototype._beforeRender=function(){R=this},e.prototype._afterRender=function(){R=null};var k="15.4.1";"undefined"==typeof Event||Event.prototype.persist||(Event.prototype.persist=function(){});var M=function(n){return function(e,r){for(var t=[],o=arguments.length-2;o-- >0;)t[o]=arguments[o+2];var i=r||{},u=i.ref;return"string"==typeof u&&(i.ref=function(n){this&&this.refs&&(this.refs[u]=n)}.bind(R||null)),"string"==typeof e&&w(e,i),n.apply(void 0,[e,i].concat(t))}},S=M(E),U=M(r.cloneVNode);N.prototype=new e({},{}),N.prototype.shouldComponentUpdate=function(n,e){return O(this.props,n)||O(this.state,e)};var T=function(n){function e(){n.apply(this,arguments)}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.getChildContext=function(){return this.props.context},e.prototype.render=function(n){return n.children},e}(e),W={createVNode:r.createVNode,render:r.render,isValidElement:y,createElement:S,Component:e,PureComponent:N,unmountComponentAtNode:C,cloneElement:U,PropTypes:I,createClass:g,findDOMNode:r.findDOMNode,Children:D,cloneVNode:r.cloneVNode,NO_OP:r.NO_OP,version:k,unstable_renderSubtreeIntoContainer:_};n.createVNode=r.createVNode,n.render=r.render,n.isValidElement=y,n.createElement=S,n.Component=e,n.PureComponent=N,n.unmountComponentAtNode=C,n.cloneElement=U,n.PropTypes=I,n.createClass=g,n.findDOMNode=r.findDOMNode,n.Children=D,n.cloneVNode=r.cloneVNode,n.NO_OP=r.NO_OP,n.version=k,n.unstable_renderSubtreeIntoContainer=_,n.default=W,Object.defineProperty(n,"__esModule",{value:!0})});
|
node_modules/react-router/es/Redirect.js | Snatch-M/fesCalendar | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { formatPattern } from './PatternUtils';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
object = _React$PropTypes.object;
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
/* eslint-disable react/require-render-return */
var Redirect = React.createClass({
displayName: 'Redirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element) {
var route = _createRouteFromReactElement(element);
if (route.from) route.path = route.from;
route.onEnter = function (nextState, replace) {
var location = nextState.location,
params = nextState.params;
var pathname = void 0;
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params);
} else if (!route.to) {
pathname = location.pathname;
} else {
var routeIndex = nextState.routes.indexOf(route);
var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1);
var pattern = parentPattern.replace(/\/*$/, '/') + route.to;
pathname = formatPattern(pattern, params);
}
replace({
pathname: pathname,
query: route.query || location.query,
state: route.state || location.state
});
};
return route;
},
getRoutePattern: function getRoutePattern(routes, routeIndex) {
var parentPattern = '';
for (var i = routeIndex; i >= 0; i--) {
var route = routes[i];
var pattern = route.path || '';
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern;
if (pattern.indexOf('/') === 0) break;
}
return '/' + parentPattern;
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Redirect; |
ajax/libs/forerunnerdb/1.2.13/fdb-all.js | jonathantneal/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;"undefined"!=typeof window?n=window:"undefined"!=typeof global?n=global:"undefined"!=typeof self&&(n=self),n.ForerunnerDB=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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview');
module.exports = Core;
},{"../lib/CollectionGroup":4,"../lib/Core":5,"../lib/Document":7,"../lib/Highchart":8,"../lib/Overview":18,"../lib/Persist":20,"../lib/View":23}],2:[function(_dereq_,module,exports){
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The active bucket class.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey,
bucketData;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
ActiveBucket.prototype.sortAsc = function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
};
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
ActiveBucket.prototype.sortDesc = function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Path":19,"./Shared":22}],3:[function(_dereq_,module,exports){
/**
* The main collection class. Collections store multiple documents and
* can operate on them using the query language to insert, read, update
* and delete.
*/
var Shared,
Core,
Metrics,
KeyValueStore,
Path,
Index,
Crc;
Shared = _dereq_('./Shared');
/**
* Collection object used to store data.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._groups = [];
this._metrics = new Metrics();
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this._subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
Index = _dereq_('./Index');
Crc = _dereq_('./Crc');
Core = Shared.modules.Core;
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Get the internal data
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function () {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log('Dropping collection ' + this._name);
}
this.emit('drop');
delete this._db._collection[this._name];
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < this._groups.length; i++) {
groupArr.push(this._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
this._groups[i].removeCollection(this);
}
return true;
}
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db');
/**
* Sets the collection's data to the array of documents passed.
* @param data
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw('Call to setData failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = JSON.stringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
this.emit('truncate', this._data);
this._data.length = 0;
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
// Decouple the update data
update = this.decouple(update);
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log('Updating some collection data for collection "' + this.name() + '"');
}
var self = this,
op = this._metrics.create('update'),
pKey = this._primaryKey,
dataSet,
updated,
updateCall = function (doc) {
if (update && update[pKey] !== undefined && update[pKey] != doc[pKey]) {
// Remove item from indexes
self._removeIndex(doc);
var result = self.updateObject(doc, update, query, options, '');
// Update the item in the primary index
if (self._insertIndex(doc)) {
return result;
} else {
throw('Primary key violation in update! Key violated: ' + doc[pKey]);
}
} else {
return self.updateObject(doc, update, query, options, '');
}
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
pathInstance,
sourceIsArray,
updateIsArray,
i, k;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$index':
// Ignore $index operators
operation = true;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0])) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
this._updateIncrement(doc, i, update[i]);
updated = true;
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
doc[i] = [];
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw("Cannot push to a key that is not an array! (" + i + ")");
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i])) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw("Cannot pullAll without being given an array of values to pull! (" + i + ")");
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
doc[i] = [];
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = JSON.stringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (JSON.stringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw("Cannot addToSet on a key that is not an array! (" + k + ")!");
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
doc[i] = [];
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
var tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw("Cannot splicePush without a $index integer value!");
}
} else {
throw("Cannot splicePush with a key that is not an array! (" + i + ")");
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i])) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw("Cannot move without a $index integer value!");
}
break;
}
}
} else {
throw("Cannot move on a key that is not an array! (" + i + ")");
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw("Cannot pop from a key that is not an array! (" + i + ")");
}
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
Collection.prototype._updateProperty = function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Collection: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"');
}
};
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
Collection.prototype._updateIncrement = function (doc, prop, val) {
doc[prop] += val;
};
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
Collection.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"');
}
};
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
};
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._updatePush = function (arr, doc) {
arr.push(doc);
};
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
Collection.prototype._updatePull = function (arr, index) {
arr.splice(index, 1);
};
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
Collection.prototype._updateMultiply = function (doc, prop, val) {
doc[prop] *= val;
};
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
Collection.prototype._updateRename = function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
};
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
Collection.prototype._updateUnset = function (doc, prop) {
delete doc[prop];
};
/**
* Pops an item from the array stack.
* @param {Object} doc The document to modify.
* @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift.
* @return {Boolean}
* @private
*/
Collection.prototype._updatePop = function (doc, val) {
var updated = false;
if (doc.length > 0) {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
return updated;
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
var self = this,
dataSet,
index,
dataItem,
arrIndex,
returnArr;
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
dataItem = dataSet[i];
// Remove the item from the collection's indexes
this._removeIndex(dataItem);
// Remove data from internal stores
index = this._data.indexOf(dataItem);
this._dataRemoveIndex(index);
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this.deferEmit('change', {type: 'remove', data: dataSet});
}
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc.
* @private
*/
Collection.prototype.deferEmit = function () {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
if (this._changeTimeout) {
clearTimeout(this._changeTimeout);
}
// Set a timeout
this._changeTimeout = setTimeout(function () {
if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); }
self.emit.apply(self, args);
}, 100);
} else {
this.emit.apply(this, arguments);
}
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
*/
Collection.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this[type](dataArr);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
}
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
this._onInsert(inserted, failed);
if (callback) { callback(); }
this.deferEmit('change', {type: 'insert', data: inserted});
return {
inserted: inserted,
failed: failed
};
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var indexViolation;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
if (!indexViolation) {
// Add the item to the collection's indexes
this._insertIndex(doc);
// Check index overflow
if (index > this._data.length) {
index = this._data.length;
}
// Insert the document
this._dataInsertIndex(index, doc);
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIndex = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = JSON.stringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeIndex = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = JSON.stringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets the collection that this collection is a subset of.
* @returns {Collection}
*/
Collection.prototype.subsetOf = function () {
return this.__subsetOf;
};
/**
* Sets the collection that this collection is a subset of.
* @param {Collection} collection The collection to set as the parent of this subset.
* @returns {*} This object for chaining.
* @private
*/
Collection.prototype._subsetOf = function (collection) {
this.__subsetOf = collection;
return this;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = JSON.stringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options) {
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
self = this,
analysis,
finalQuery,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearch,
joinMulti,
joinRequire,
joinFindResults,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i,
matcher = function (doc) {
return self._match(doc, query, 'and');
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(query, options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup;
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.matchedKeyCount) {
// Require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
op.time('tableScan: ' + scanLength);
}
if (options.limit && resultArr && resultArr.length > options.limit) {
resultArr.length = options.limit;
op.data('limit', options.limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.join.length; joinCollectionIndex++) {
for (joinCollectionName in options.join[joinCollectionIndex]) {
if (options.join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
joinCollectionInstance = this._db.collection(joinCollectionName);
// Get the match data for the join
joinMatch = options.join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearch = {};
joinMulti = false;
joinRequire = false;
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
default:
// Check for a double-dollar which is a back-reference to the root collection item
if (joinMatchIndex.substr(0, 3) === '$$.') {
// Back reference
// TODO: Support complex joins
}
break;
}
} else {
// TODO: Could optimise this by caching path objects
// Get the data to match against and store in the search object
joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0];
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearch);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
op.stop();
resultArr.__fdbOp = op;
return resultArr;
} else {
op.stop();
resultArr = [];
resultArr.__fdbOp = op;
return resultArr;
}
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query) {
var item = this.find(query, {$decouple: false})[0];
if (item) {
return this._data.indexOf(item);
}
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
if (obj === false) {
// Turn off transforms
this._transformEnabled = false;
} else {
// Turn on transforms
this._transformEnabled = true;
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
}
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = sortKey;
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
buckets = this.bucket(keyObj.___fdbKey, arr);
// Loop buckets and sort contents
for (i in buckets) {
if (buckets.hasOwnProperty(i)) {
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i]));
}
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
if (typeof valA === 'string' && typeof valB === 'string') {
return valA.localeCompare(valB);
} else {
if (valA > valB) {
return 1;
} else if (valA < valB) {
return -1;
}
}
return 0;
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
if (typeof valA === 'string' && typeof valB === 'string') {
return valB.localeCompare(valA);
} else {
if (valA > valB) {
return -1;
} else if (valA < valB) {
return 1;
}
}
return 0;
};
} else {
throw(this._name + ': $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
buckets = {};
for (i = 0; i < arr.length; i++) {
buckets[arr[i][key]] = buckets[arr[i][key]] || [];
buckets[arr[i][key]].push(arr[i]);
}
return buckets;
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
pathSolver = new Path();
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
matchedKeyCount: 1,
totalKeyCount: pathSolver.countKeys(query)
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
indexLookup = indexRef.lookup(query, options);
if (indexMatchData.matchedKeyCount > 0) {
// This index can be used, store it
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.totalKeyCount === indexMatchData.matchedKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.totalKeyCount === a.keyData.matchedKeyCount) {
// This index matches all query keys so will return the correct result instantly
return -1;
}
if (b.keyData.totalKeyCount === b.keyData.matchedKeyCount) {
// This index matches all query keys so will return the correct result instantly
return 1;
}
// The indexes don't match all the query keys, check if both these indexes match
// the same number of keys and if so they are technically equal from a key point
// of view, but can still be compared by the number of records they return from
// the query. The fewer records they return the better so order by record count
if (a.keyData.matchedKeyCount === b.keyData.matchedKeyCount) {
return a.lookup.length - b.lookup.length;
}
// The indexes don't match all the query keys and they don't have matching key
// counts, so order them by key count. The index with the most matching keys
// should return the query results the fastest
return b.keyData.matchedKeyCount - a.keyData.matchedKeyCount; // index._keyCount
});
op.time('findOptimalIndex');
}
// Check for join data
if (options.join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.join[joinCollectionIndex]) {
if (options.join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.join[joinCollectionIndex][joinCollectionName]['$as']);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
Collection.prototype._match = function (source, test, opToApply) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
i;
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (source !== test) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$gt':
// Greater than
if (source > test[i]) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
operation = true;
break;
case '$gte':
// Greater than or equal
if (source >= test[i]) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
operation = true;
break;
case '$lt':
// Less than
if (source < test[i]) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
operation = true;
break;
case '$lte':
// Less than or equal
if (source <= test[i]) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
operation = true;
break;
case '$exists':
// Property exists
if ((source === undefined) !== test[i]) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
operation = true;
break;
case '$or':
// Match true on ANY check to pass
operation = true;
for (var orIndex = 0; orIndex < test[i].length; orIndex++) {
if (this._match(source, test[i][orIndex], 'and')) {
return true;
} else {
matchedAll = false;
}
}
break;
case '$and':
// Match true on ALL checks to pass
operation = true;
for (var andIndex = 0; andIndex < test[i].length; andIndex++) {
if (!this._match(source, test[i][andIndex], 'and')) {
return false;
}
}
break;
case '$in':
// In
// Check that the in test is an array
if (test[i] instanceof Array) {
var inArr = test[i],
inArrCount = inArr.length,
inArrIndex,
isIn = false;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] === source) {
isIn = true;
break;
}
}
if (isIn) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
throw('Cannot use a $nin operator on a non-array key: ' + i);
}
operation = true;
break;
case '$nin':
// Not in
// Check that the not-in test is an array
if (test[i] instanceof Array) {
var notInArr = test[i],
notInArrCount = notInArr.length,
notInArrIndex,
notIn = true;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
notIn = false;
break;
}
}
if (notIn) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
throw('Cannot use a $nin operator on a non-array key: ' + i);
}
operation = true;
break;
case '$ne':
// Not equals
if (source != test[i]) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
operation = true;
break;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], applyOp);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], applyOp);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], applyOp);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i]['$exists'] !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], applyOp);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param match
* @param path
* @param subDocQuery
* @param subDocOptions
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
resultObj.subDocs.push(subDocResults);
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.noStats) {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index = new Index(keys, options, this),
time = {
start: new Date().getTime()
};
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm === collection.primaryKey()) {
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) === collection._primaryCrc.get(arrItem[pm])) {
// Matching objects, no update required
} else {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert requried
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
} else {
throw('Collection diffing requires that both collections have the same primary key!');
}
return diff;
};
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String=} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
Core.prototype.collection = function (collectionName, primaryKey) {
if (collectionName) {
if (!this._collection[collectionName]) {
if (this.debug()) {
console.log('Creating collection ' + collectionName);
}
}
this._collection[collectionName] = this._collection[collectionName] || new Collection(collectionName).db(this);
if (primaryKey !== undefined) {
this._collection[collectionName].primaryKey(primaryKey);
}
return this._collection[collectionName];
} else {
throw('Cannot get collection with undefined name!');
}
};
/**
* Determine if a collection with the passed name already exists.
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Core.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Core.prototype.collections = function (search) {
var arr = [],
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: this._collection[i].count()
});
}
} else {
arr.push({
name: i,
count: this._collection[i].count()
});
}
}
}
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":6,"./Index":9,"./KeyValueStore":10,"./Metrics":11,"./Path":19,"./Shared":22}],4:[function(_dereq_,module,exports){
// Import external names locally
var Shared,
Core,
CoreInit,
Collection;
Shared = _dereq_('./Shared');
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new Collection('__FDB__cg_data_' + this._name);
this._collections = [];
this._views = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Collection = _dereq_('./Collection');
Core = Shared.modules.Core;
CoreInit = Shared.modules.Core.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw("All collections in a collection group must have the same primary key!");
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups.push(this);
collection.chain(this);
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function () {
var i,
collArr = [].concat(this._collections),
viewArr = [].concat(this._views);
if (this._debug) {
console.log('Dropping collection group ' + this._name);
}
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
this.emit('drop');
return true;
};
// Extend DB to include collection groups
Core.prototype.init = function () {
this._collectionGroup = {};
CoreInit.apply(this, arguments);
};
Core.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
module.exports = CollectionGroup;
},{"./Collection":3,"./Shared":22}],5:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2014 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Forerunner is free for use if you are using it for non-commercial, non-governmental or
non-profit use. If you are doing something commercial please visit the license page to
see which license best suits your requirements:
http://www.forerunnerdb.com/licensing.html
Commercial licenses help to continue development of ForerunnerDB and pay for developers,
equipment, offices and electricity and without them ForerunnerDB would not exist!
*/
var Shared,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The main ForerunnerDB core object.
* @constructor
*/
var Core = function () {
this.init.apply(this, arguments);
};
Core.prototype.init = function () {
this._collection = {};
this._debug = {};
this._version = '1.2.13';
};
Core.prototype.moduleLoaded = Overload({
/**
* Checks if a module has been loaded into the database.
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.ChainReactor');
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Core.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Core.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Core.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Core.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Core.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Core.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Core.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
module.exports = Core;
},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":11,"./Overload":17,"./Shared":22}],6:[function(_dereq_,module,exports){
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1),
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ (-1)) >>> 0;
};
},{}],7:[function(_dereq_,module,exports){
var Shared,
Collection,
Core,
CoreInit;
Shared = _dereq_('./Shared');
var Document = function () {
this.init.apply(this, arguments);
};
Document.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', Document);
Shared.mixin(Document.prototype, 'Mixin.Common');
Shared.mixin(Document.prototype, 'Mixin.Events');
Shared.mixin(Document.prototype, 'Mixin.ChainReactor');
Collection = _dereq_('./Collection');
Core = Shared.modules.Core;
CoreInit = Shared.modules.Core.prototype.init;
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Document.prototype, 'db');
/**
* Gets / sets the document name.
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(Document.prototype, 'name');
Document.prototype.setData = function (data) {
var i,
$unset;
if (data) {
data = this.decouple(data);
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
}
return this;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Document.prototype.update = function (query, update, options) {
this.updateObject(this._data, update, query, options);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Document.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Document.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
Document.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log('ForerunnerDB.Document: Setting data-bound document property "' + prop + '" for collection "' + this.name() + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Document: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
Document.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
Document.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log('ForerunnerDB.Document: Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
Document.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
Document.prototype._updatePush = function (arr, doc) {
if (this._linked) {
jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
Document.prototype._updatePull = function (arr, index) {
if (this._linked) {
jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
Document.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
Document.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
jQuery.observable(doc).setProperty(val, existingVal);
jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
Document.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @return {Boolean}
* @private
*/
Document.prototype._updatePop = function (doc, val) {
var index,
updated = false;
if (doc.length > 0) {
if (this._linked) {
if (val === 1) {
index = doc.length - 1;
} else if (val === -1) {
index = 0;
}
if (index > -1) {
jQuery.observable(arr).remove(index);
updated = true;
}
} else {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
}
return updated;
};
Document.prototype.drop = function () {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
delete this._db._document[this._name];
this._data = {};
}
}
};
// Extend DB to include documents
Core.prototype.init = function () {
CoreInit.apply(this, arguments);
};
Core.prototype.document = function (documentName) {
if (documentName) {
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new Document(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
Shared.finishModule('Document');
module.exports = Document;
},{"./Collection":3,"./Shared":22}],8:[function(_dereq_,module,exports){
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = $(this._options.selector);
if (!this._selector[0]) {
throw('Chart target element does not exist via selector: ' + this._options.selector);
return;
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData,
i;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
$.extend(seriesObj, this._options.seriesOptions);
$.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw('Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
break;
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
}
seriesData.push({
name: seriesName,
data: seriesValues
});
}
return {
xAxis: xAxis,
series: seriesData
};
};
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () { self._changeListener.apply(self, arguments); });
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () { self._dropListener.apply(self, arguments); });
};
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if(typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy
);
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
Highchart.prototype._dropListener = function () {
var self = this;
self._collection.off('change', self._changeListener);
self._collection.off('drop', self._dropListener);
};
Highchart.prototype.drop = function () {
this._chart.destroy();
this._collection.off('change', this._changeListener);
this._collection.off('drop', this._dropListener);
delete this._collection._highcharts[this._options.selector];
delete this._chart;
delete this._options;
delete this._collection;
return this;
};
// Extend collection with view init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
Collection.prototype.lineChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
Collection.prototype.dropChart = function (selector) {
if (this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":17,"./Shared":22}],9:[function(_dereq_,module,exports){
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var Index = function () {
this.init.apply(this, arguments);
};
Index.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('Index', Index);
Shared.mixin(Index.prototype, 'Mixin.ChainReactor');
Index.prototype.id = function () {
return this._id;
};
Index.prototype.state = function () {
return this._state;
};
Index.prototype.size = function () {
return this._size;
};
Index.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
return this;
}
return this._data;
};
Shared.synthesize(Index.prototype, 'name');
Index.prototype.collection = function (val) {
if (val !== undefined) {
this._collection = val;
return this;
}
return this._collection;
};
Index.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
Index.prototype.type = function (val) {
if (val !== undefined) {
this._type = val;
return this;
}
return this._type;
};
Index.prototype.unique = function (val) {
if (val !== undefined) {
this._unique = val;
return this;
}
return this._unique;
};
Index.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
Index.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
Index.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
Index.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
Index.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
Index.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
Index.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
Index.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
delete this._crossRef[id];
};
Index.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
Index.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
return pathSolver.countObjectPaths(this._keys, query);
};
Index.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('Index');
module.exports = Index;
},{"./Path":19,"./Shared":22}],10:[function(_dereq_,module,exports){
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":22}],11:[function(_dereq_,module,exports){
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":16,"./Shared":22}],12:[function(_dereq_,module,exports){
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],13:[function(_dereq_,module,exports){
var ChainReactor = {
chain: function (obj) {
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arr[index].chainReceive(this, type, data, options);
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],14:[function(_dereq_,module,exports){
var idCounter = 0,
Overload = _dereq_('./Overload'),
Common;
Common = {
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @returns {*}
*/
decouple: function (data) {
if (data !== undefined) {
return JSON.parse(JSON.stringify(data));
}
return undefined;
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
])
};
module.exports = Common;
},{"./Overload":17}],15:[function(_dereq_,module,exports){
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
// Handle global emit
if (this._listeners[event]['*']) {
var arr = this._listeners[event]['*'],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
var listenerIdArr = this._listeners[event],
listenerIdCount,
listenerIdIndex;
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
return this;
}
};
module.exports = Events;
},{}],16:[function(_dereq_,module,exports){
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":19,"./Shared":22}],17:[function(_dereq_,module,exports){
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
Overload = function (def) {
if (def) {
var index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return def[index].apply(this, arguments);
}
}
} else {
// Generate lookup key from arguments
var arr = [],
lookup,
type;
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return def[lookup].apply(this, arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return def[lookup + ',...'].apply(this, arguments);
}
}
}
}
throw('Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
module.exports = Overload;
},{}],18:[function(_dereq_,module,exports){
// Import external names locally
var Shared,
Core,
CoreInit,
Collection,
Document;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new Document('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._collections = [];
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Collection = _dereq_('./Collection');
Document = _dereq_('./Document');
Core = Shared.modules.Core;
CoreInit = Shared.modules.Core.prototype.init;
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (collection) {
if (collection !== undefined) {
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._addCollection(collection);
}
return this;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._addCollection = function (collection) {
if (this._collections.indexOf(collection) === -1) {
this._collections.push(collection);
collection.chain(this);
this._refresh();
}
return this;
};
Overview.prototype._removeCollection = function (collection) {
var collectionIndex = this._collections.indexOf(collection);
if (collectionIndex > -1) {
this._collections.splice(collection, 1);
collection.unChain(this);
this._refresh();
}
return this;
};
Overview.prototype._refresh = function () {
if (this._collections && this._collections[0]) {
this._collData.primaryKey(this._collections[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._collections.length; i++) {
tempArr = tempArr.concat(this._collections[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce();
// Update the document with the newly returned data
this._data.setData(reducedData);
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
// Extend DB to include collection groups
Core.prototype.init = function () {
this._overview = {};
CoreInit.apply(this, arguments);
};
Core.prototype.overview = function (overviewName) {
if (overviewName) {
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview;
}
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":3,"./Document":7,"./Shared":22}],19:[function(_dereq_,module,exports){
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":22}],20:[function(_dereq_,module,exports){
// TODO: Add doc comments to this class
// Import external names locally
var Shared = _dereq_('./Shared'),
localforage = _dereq_('localforage'),
Core,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
CoreInit,
Persist;
Persist = function () {
this.init.apply(this, arguments);
};
Persist.prototype.init = function (db) {
// Check environment
if (db.isClient()) {
if (Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: 'ForerunnerDB',
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
CoreInit = Core.prototype.init;
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
break;
}
return this;
}
return localforage.driver();
};
Persist.prototype.save = function (key, data, callback) {
var encode;
encode = function (val, finished) {
if (typeof val === 'object') {
val = 'json::fdb::' + JSON.stringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (finished) {
finished(false, val);
}
};
switch (this.mode()) {
case 'localforage':
encode(data, function (err, data) {
localforage.setItem(key, data).then(function (data) {
callback(false, data);
}, function (err) {
callback(err);
});
});
break;
default:
if (callback) {
callback('No data handler.');
}
break;
}
};
Persist.prototype.load = function (key, callback) {
var parts,
data,
decode;
decode = function (val, finished) {
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = JSON.parse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (finished) {
finished(false, data);
}
} else {
finished(false, val);
}
};
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
decode(val, callback);
}, function (err) {
callback(err);
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
callback(false);
}, function (err) {
callback(err);
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = function (removePersistent) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Save the collection data
this._db.persist.drop(this._name);
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
}
// Call the original method
CollectionDrop.apply(this, arguments);
};
Collection.prototype.save = function (callback) {
if (this._name) {
if (this._db) {
// Save the collection data
this._db.persist.save(this._name, this._data, callback);
} else {
if (callback) {
callback('Cannot save a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot save a collection with no assigned name!');
}
}
};
Collection.prototype.load = function (callback) {
var self = this;
if (this._name) {
if (this._db) {
// Load the collection data
this._db.persist.load(this._name, function (err, data) {
if (!err) {
if (data) {
self.setData(data);
}
if (callback) {
callback(false);
}
} else {
if (callback) {
callback(err);
}
}
});
} else {
if (callback) {
callback('Cannot load a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot load a collection with no assigned name!');
}
}
};
// Override the DB init to instantiate the plugin
Core.prototype.init = function () {
this.persist = new Persist(this);
CoreInit.apply(this, arguments);
};
Core.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
index;
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
callback(false);
}
} else {
callback(err);
}
});
}
}
};
Core.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
index;
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
callback(false);
}
} else {
callback(err);
}
});
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":3,"./CollectionGroup":4,"./Shared":22,"localforage":30}],21:[function(_dereq_,module,exports){
var Shared = _dereq_('./Shared');
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ReactorIO requires an in, out and process argument to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
ReactorIO.prototype.drop = function () {
// Remove links
this._reactorIn.unChain(this);
this.unChain(this._reactorOut);
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
};
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":22}],22:[function(_dereq_,module,exports){
var Shared = {
modules: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
this.modules[name] = module;
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
this.modules[name]._fdbFinished = true;
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
callback(name, this.modules[name]);
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: function (obj, mixinName) {
var system = this.mixins[mixinName];
if (system) {
for (var i in system) {
if (system.hasOwnProperty(i)) {
obj[i] = system[i];
}
}
} else {
throw('Cannot find mixin named: ' + mixinName);
}
},
/**
* Generates a generic getter/setter method for the passed method name.
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
}
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @param arr
* @returns {Function}
* @constructor
*/
overload: _dereq_('./Overload'),
/**
* Define the mixins that other modules can use as required.
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":12,"./Mixin.ChainReactor":13,"./Mixin.Common":14,"./Mixin.Events":15,"./Overload":17}],23:[function(_dereq_,module,exports){
// Import external names locally
var Shared,
Core,
Collection,
CollectionInit,
CoreInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param name
* @param query
* @param options
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
this._name = name;
this._groups = [];
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._privateData = new Collection('__FDB__view_privateData_' + this._name);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Core = Shared.modules.Core;
CoreInit = Core.prototype.init;
Shared.synthesize(View.prototype, 'name');
/**
* Executes an insert against the view's underlying data-source.
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the collection from which the view will assemble its data.
* @param {Collection} collection The collection to use to assemble view data.
* @returns {View}
*/
View.prototype.from = function (collection) {
var self = this;
if (collection !== undefined) {
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" collection and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(collection, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, 'and')) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, 'and')) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
return false;
}
}
}
return false;
});
var collData = collection.find(this._querySettings.query, this._querySettings.options);
this._transformPrimaryKey(collection.primaryKey());
this._transformSetData(collData);
this._privateData.primaryKey(collection.primaryKey());
this._privateData.setData(collData);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
}
return this;
};
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
View.prototype._chainHandler = function (chainPacket) {
var self = this,
arr,
count,
index,
insertIndex,
tempData,
dataIsArray,
updates,
finalUpdates,
primaryKey,
tQuery,
item,
currentIndex,
i;
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
// Modify transform data
this._transformSetData(collData);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
if (this._transformEnabled && this._transformIn) {
primaryKey = this._publicData.primaryKey();
for (i = 0; i < updates.length; i++) {
tQuery = {};
item = updates[i];
tQuery[primaryKey] = item[primaryKey];
this._transformUpdate(tQuery, item);
}
}
break;
case 'remove':
if (this.debug()) {
console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Modify transform data
this._transformRemove(chainPacket.data.query, chainPacket.options);
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
View.prototype.on = function () {
this._privateData.on.apply(this._privateData, arguments);
};
View.prototype.off = function () {
this._privateData.off.apply(this._privateData, arguments);
};
View.prototype.emit = function () {
this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function () {
if (this._from) {
if (this.debug() || (this._db && this._db.debug())) {
console.log('ForerunnerDB.View: Dropping view ' + this._name);
}
// Clear io and chains
this._io.drop();
// Drop the view's internal collection
this._privateData.drop();
return true;
}
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
View.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
this.privateData().db(db);
this.publicData().db(db);
return this;
}
return this._db;
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._privateData.primaryKey();
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var sortedData,
pubData = this.publicData();
// Re-grab all the data for the view from the collection
this._privateData.remove();
pubData.remove();
this._privateData.insert(this._from.find(this._querySettings.query, this._querySettings.options));
if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
//jQuery.observable(pubData._data).refresh(transformedData);
}
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._privateData && this._privateData._data ? this._privateData._data.length : 0;
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
if (obj === false) {
// Turn off transforms
this._transformEnabled = false;
} else {
// Turn on transforms
this._transformEnabled = true;
}
}
// Update the transformed data object
this._transformPrimaryKey(this.privateData().primaryKey());
this._transformSetData(this.privateData().find());
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* Updates the public data object to match data from the private data object
* by running private data through the dataIn method provided in
* the transform() call.
* @private
*/
View.prototype._transformSetData = function (data) {
if (this._transformEnabled) {
// Clear existing data
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
this._publicData.setData(data);
}
};
View.prototype._transformInsert = function (data, index) {
if (this._transformEnabled && this._publicData) {
this._publicData.insert(data, index);
}
};
View.prototype._transformUpdate = function (query, update, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.update(query, update, options);
}
};
View.prototype._transformRemove = function (query, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.remove(query, options);
}
};
View.prototype._transformPrimaryKey = function (key) {
if (this._transformEnabled && this._publicData) {
this._publicData.primaryKey(key);
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._views = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._views ) {
if (!this._db._views[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._views = this._views || [];
this._views.push(view);
return view;
} else {
throw('Cannot create a view using this collection because one with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._views.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._views.indexOf(view);
if (index > -1) {
this._views.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Core.prototype.init = function () {
this._views = {};
CoreInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Core.prototype.view = function (viewName) {
if (!this._views[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log('Core.View: Creating view ' + viewName);
}
}
this._views[viewName] = this._views[viewName] || new View(viewName).db(this);
return this._views[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Core.prototype.viewExists = function (viewName) {
return Boolean(this._views[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Core.prototype.views = function () {
var arr = [],
i;
for (i in this._views) {
if (this._views.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._views[i].count()
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":21,"./Shared":22}],24:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":26}],25:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex)
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":24,"asap":26}],26:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":31}],27:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function() {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
}).catch(reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readwrite')
.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
req.onsuccess = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
}).catch(reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readwrite')
.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `.delete()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store.delete(key);
req.onsuccess = function() {
resolve();
};
req.onerror = function() {
reject(req.error);
};
// The request will be aborted if we've exceeded our storage
// space. In this case, we will reject with a specific
// "QuotaExceededError".
req.onabort = function(event) {
var error = event.target.error;
if (error === 'QuotaExceededError') {
reject(error);
}
};
}).catch(reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readwrite')
.objectStore(dbInfo.storeName);
var req = store.clear();
req.onsuccess = function() {
resolve();
};
req.onerror = function() {
reject(req.error);
};
}).catch(reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor.continue();
};
req.onerror = function() {
reject(req.error);
};
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
function executeDeferedCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
deferCallback(callback, result);
}, function(error) {
callback(error);
});
}
}
// Under Chrome the callback is called before the changes (save, clear)
// are actually made. So we use a defer function which wait that the
// call stack to be empty.
// For more info : https://github.com/mozilla/localForage/issues/175
// Pull request : https://github.com/mozilla/localForage/pull/178
function deferCallback(callback, result) {
if (callback) {
return setTimeout(function() {
return callback(null, result);
}, 0);
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = asyncStorage;
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":25}],28:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
return Promise.resolve();
}
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
resolve();
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
try {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = _deserialize(result);
}
resolve(result);
} catch (e) {
reject(e);
}
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
resolve(result);
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
resolve(keys);
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.keys().then(function(keys) {
resolve(keys.length);
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
resolve();
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function _deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
// Fill the string into a ArrayBuffer.
// 2 bytes for each char.
var buffer = new ArrayBuffer(serializedString.length * 2);
var bufferView = new Uint16Array(buffer);
for (var i = serializedString.length - 1; i >= 0; i--) {
bufferView[i] = serializedString.charCodeAt(i);
}
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return new Blob([buffer]);
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function _bufferToString(buffer) {
var str = '';
var uint16Array = new Uint16Array(buffer);
try {
str = String.fromCharCode.apply(null, uint16Array);
} catch (e) {
// This is a fallback implementation in case the first one does
// not work. This is required to get the phantomjs passing...
for (var i = 0; i < uint16Array.length; i++) {
str += String.fromCharCode(uint16Array[i]);
}
}
return str;
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function _serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + _bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
var str = _bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
window.console.error("Couldn't convert value into a JSON " +
'string: ', value);
callback(e);
}
}
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
_serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
}
resolve(originalValue);
}
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof define === 'function' && define.amd) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = localStorageWrapper;
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"promise":25}],29:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL is Base64 serializing
// it, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
var openDatabase = this.openDatabase;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
return new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver('localStorageWrapper')
.then(function() {
return self._initStorage(options);
})
.then(resolve)
.catch(reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = _deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
_serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) { // The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key], function() {
resolve();
}, function(t, error) {
reject(error);
});
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
}).catch(reject);
});
executeCallback(promise, callback);
return promise;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function _bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var i;
var base64String = '';
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function _deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return new Blob([buffer]);
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function _serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + _bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
var str = _bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
window.console.error("Couldn't convert value into a JSON " +
'string: ', value);
callback(null, e);
}
}
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof define === 'function' && define.amd) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"promise":25}],30:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
} else if (typeof module !== 'undefined' && module.exports) {
moduleType = ModuleType.EXPORT;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
}).catch(reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], function(lib) {
self._extend(lib);
resolve();
});
return;
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
var driver;
switch (driverName) {
case self.INDEXEDDB:
driver = _dereq_('./drivers/indexeddb');
break;
case self.LOCALSTORAGE:
driver = _dereq_('./drivers/localstorage');
break;
case self.WEBSQL:
driver = _dereq_('./drivers/websql');
}
self._extend(driver);
} else {
self._extend(globalObject[driverName]);
}
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
} else {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
resolve();
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":27,"./drivers/localstorage":28,"./drivers/websql":29,"promise":25}],31:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
}
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}]},{},[1])(1)
});
|
src/containers/DevToolsWindow.js | haozeng/react-redux-filter | import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
export default createDevTools(
<LogMonitor />
)
|
site/pages/guides/getting-started.js | chrisdarroch/skatejs | // @flow
import '../../components/layout';
import '../../components/marked';
import { define } from 'skatejs';
import { Component } from '../../utils';
@define
export default class extends Component {
static is = 'x-pages-guides-getting-started';
render() {
return this.$`
<x-layout title="Getting started">
<x-marked
src="${`
At its core, Skate is about creating
[Custom Elements](https://w3c.github.io/webcomponents/spec/custom/). Skate
provides a series of
[mixin functions](/mixins)
that enable you to control what your component can do.
For instance, Skate's main mixin, \`withComponent\`, is just a composition of all
of Skate's other mixin behaviours:
* \`withChildren\` -- the generated element will react to changes to its child
elements.
* \`withContext\` -- the element will inherit context from components up the tree,
like in React.
* \`withLifecycle\` -- the element can use added sugar on top of the built-in
lifecycle callbacks.
* \`withRenderer\` -- the element can generate its own DOM and output it to a
\`renderRoot\` (a \`ShadowRoot\` node by default).
* \`withUpdate\` -- the generated element will react to changes on their props or
HTML attributes.
Calling \`withComponent()\` gives you a Custom Element class constructor, which
you can then extend to define your own elements.
Every mixin accepts an optional \`Element\` constructor as its only parameter,
which allows you to extend virtually any element type in HTML!
### Rendering an element
As an example, let's create a simple greeting component...
\`\`\`html
<x-hello>Bob</x-hello>
\`\`\`
...such that when this element is rendered, the end-user will see \`Hello, Bob!\`.
We can define a Skate component that renders the contents of our Custom Element:
\`\`\`js
import { withComponent } from 'skatejs';
const Component = withComponent();
class GreetingComponent extends Component {
render() {
return 'Hello, <slot></slot>!';
}
}
customElements.define('x-hello', GreetingComponent);
\`\`\`
> It's worth noting that while \`withRenderer()\` provides a very basic renderer that
sets \`innerHTML\` using the return value of \`render()\`, it's not intended for complex
usage. If you need events / props / efficient updates, you should use something
like \`@skatejs/renderer-preact\`.
When this element is rendered, the DOM will look something like the following:
\`\`\`html
<x-hello>
#shadow-root
Hello, <slot></slot>!
Bob
</x-hello>
\`\`\`
This is the utility that web components provide when using Custom Elements and
the Shadow DOM.
Skate also allows **turning off Shadow DOM** if you don't wanna use it for
various particular reasons. You can turn it off via \`get renderRoot()\` override:
> NOTE: by turning off Shadow DOM you cannot use <slot/> content projection
> anymore by default, further tweaks needs to be applied
\`\`\`js
import { withComponent, props } from 'skatejs';
// define base class without Shadow DOM
const NoShadowComponent = class extends withComponent() {
// you need to return where you want to render your content, in our case we wanna render directly to our custom element children
get renderRoot() {
return this;
}
};
// use custom NoShadowComponent as a base class
class GreetingComponent extends NoShadowComponent {
static get props() {
return {
name: props.string
};
}
render({ name }) {
return \`Hello, ${name}!\`;
}
}
customElements.define('x-hello', GreetingComponent);
\`\`\`
Now when you write:
\`\`\`html
<x-hello name="Bob"></x-hello>
\`\`\`
When this element is rendered, the DOM will look something like the following:
\`\`\`html
<x-hello>
Hello, Bob!
</x-hello>
\`\`\`
### Watching element properties and attributes
We can create a Skate component that watches for HTML attribute changes on
itself:
\`\`\`js
import { props, withComponent } from 'skatejs';
const Component = withComponent();
class GreetingComponent extends Component {
static get props() {
return {
name: props.string
};
}
render({ name }) {
return \`Hello, ${name}!\`;
}
}
customElements.define('x-hello', GreetingComponent);
\`\`\`
The resulting HTML when the element is rendered would look like this:
\`\`\`html
<x-hello name="Bob">
#shadow-root
Hello, Bob!
</x-hello>
\`\`\`
Now, whenever the \`name\` property or attribute on the greeting component
changes, the component will re-render.
### Making your own mixins
In the previous examples, each component implements \`render\` method which
returns a string. This is default "renderer" behaviour provided by Skate. You
can define custom renderer as well by re-defining \`renderer\` all the time for
every component or rather we can write a mixin and take advantage of prototype
inheritance:
> NOTE: the \`with\` prefix is not mandatory, just a common practice for naming
> HOCs and Mixins
\`\`\`js
import { props, withComponent } from 'skatejs';
const withDangerouslyNaiveRenderer = (Base = HTMLElement) => {
return class extends Base {
renderer(renderRoot, render) {
renderRoot.innerHtml = '';
renderRoot.appendChild(render());
}
};
};
const Component = withComponent(withDangerouslyNaiveRenderer());
class GreetingComponent extends Component {
static get props() {
return {
name: props.string
};
}
render({ name }) {
const el = document.createElement('span');
el.innerHTML = \`Hello, ${name}!\`;
return el;
}
}
customElements.define('x-hello', GreetingComponent);
\`\`\`
### Rendering using other front-end libraries
Skate provides default renderer by setting return string of \`render\` method to
your component root ( ShadowRoot by default ) via \`innerHTML\`. Besides that it
allows you to hook to the renderer ( by defining custom renderer ), which gives
you options to support just about every modern component-based front-end library
— React, Preact, Vue... just provide a \`render\` to stamp out your
component's HTML, a \`renderer\` to update the DOM with your HTML, and then it's
all the same to Skate!
The Skate team have provided a few renderers for popular front-end libraries.
See the section on [renderers](/renderers) for more info.
#### Using Skate with Preact
Instead of writing our own \`renderer\`, we could use a library like
[Preact](https://preactjs.com/) to do the work for us. Skate provides a
ready-made renderer for Preact; here's how we would update our previous greeting
component to use it:
\`\`\`js
/** @jsx h */
import { props, withComponent } from 'skatejs';
import withRenderer from '@skatejs/renderer-preact';
import { h } from 'preact';
const Component = withComponent(withRenderer());
customElements.define(
'x-hello',
class extends Component {
static get props() {
return {
name: props.string
};
}
render({ name }) {
return <span>Hello, {name}!</span>;
}
}
);
\`\`\`
Now that the greeting component is rendered via Preact, when it renders, it only
changes the part of the DOM that requires updating.
`}"
></x-marked>
</x-layout>
`;
}
}
|
src/components/Header/Header.js | okmttdhr/aupa | import React from 'react'
import { IndexLink, Link } from 'react-router'
import classes from './Header.scss'
export const Header = () => (
<div>
<h1>React Redux Starter Kit</h1>
<IndexLink to='/' activeClassName={classes.activeRoute}>
Home
</IndexLink>
{' · '}
<Link to='/counter' activeClassName={classes.activeRoute}>
Counter
</Link>
</div>
)
export default Header
|
node_modules/react-icons/ti/battery-low.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const TiBatteryLow = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m10 26.7c-0.9 0-1.7-0.8-1.7-1.7v-6.7c0-0.9 0.8-1.6 1.7-1.6s1.7 0.7 1.7 1.6v6.7c0 0.9-0.8 1.7-1.7 1.7z m21.7-10c0-2.8-2.3-5-5-5h-18.4c-2.7 0-5 2.2-5 5v10c0 2.7 2.3 5 5 5h18.4c2.7 0 5-2.3 5-5 1.8 0 3.3-1.5 3.3-3.4v-3.3c0-1.8-1.5-3.3-3.3-3.3z m-3.4 10c0 0.9-0.7 1.6-1.6 1.6h-18.4c-0.9 0-1.6-0.7-1.6-1.6v-10c0-1 0.7-1.7 1.6-1.7h18.4c0.9 0 1.6 0.7 1.6 1.7v10z"/></g>
</Icon>
)
export default TiBatteryLow
|
fixtures/ssr/src/index.js | jorrit/react | import React from 'react';
import {hydrate} from 'react-dom';
import App from './components/App';
hydrate(<App assets={window.assetManifest} />, document);
|
app/components/styled/Grid/index.js | aaronlangford31/ruah-web | import React, { PropTypes } from 'react';
const Grid = ({ children, size, childStyle }) => (
<div style={{ display: 'flex', flexDirection: 'row', flexWrap: 'wrap' }}>
{React.Children.map(children, (child) => (React.cloneElement(child, {
style: Object.assign({
flexBasis: `calc(100% / ${size} - 24px)`,
margin: '0 12px',
}, childStyle),
})))}
</div>
);
Grid.propTypes = {
children: PropTypes.node,
size: PropTypes.number,
childStyle: PropTypes.object,
};
Grid.defaultProps = {
childStyle: {},
};
export default Grid;
|
src/containers/App/index.js | mmazzarolo/tap-the-number | /* @flow */
/**
* Main application component, handles the routing.
*/
import React, { Component } from 'react';
import { StatusBar } from 'react-native';
import { Image, View } from 'react-native-animatable';
import { inject, observer } from 'mobx-react/native';
import backgroundImg from 'src/images/bg.jpg';
import Playground from 'src/containers/Playground';
import Home from 'src/containers/Home';
import Endgame from 'src/containers/Endgame';
import styles from './index.style';
type Props = {
currentScreen: string,
};
@inject(allStores => ({
currentScreen: allStores.router.currentScreen,
}))
@observer
export default class App extends Component<Props, Props, void> {
static defaultProps = {
currentScreen: 'HOME',
};
render() {
let content;
switch (this.props.currentScreen) {
case 'HOME':
content = <Home />;
break;
case 'PLAYGROUND':
content = <Playground />;
break;
case 'ENDGAME':
content = <Endgame />;
break;
default:
content = <View />;
break;
}
return (
<Image source={backgroundImg} style={styles.container}>
<StatusBar hidden={true} />
{content}
</Image>
);
}
}
|
src/shared/components/section/section.js | OperationCode/operationcode_frontend | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import styles from './section.css';
import Heading from '../heading/heading';
const Section = (props) => {
const {
id,
title,
children,
className,
theme,
headingLines,
headingTheme,
} = props;
const classes = classNames({
[`${styles.section}`]: true,
[`${className}`]: className,
[`${styles[theme]}`]: true
});
return (
<div name={id} className={classes}>
{title && <Heading text={title} id={id} headingLines={headingLines} theme={headingTheme} />}
<div className={styles.content}>
{children}
</div>
</div>
);
};
Section.propTypes = {
id: PropTypes.string,
title: PropTypes.string,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.element),
PropTypes.arrayOf(PropTypes.node),
PropTypes.element,
PropTypes.node
]).isRequired,
className: PropTypes.string,
theme: PropTypes.string,
headingLines: PropTypes.bool,
headingTheme: PropTypes.string
};
Section.defaultProps = {
id: null,
title: null,
className: null,
theme: 'gray',
headingLines: true,
headingTheme: 'dark'
};
export default Section;
|
renderer/components/Channels/ChannelsInfo.js | LN-Zap/zap-desktop | import React from 'react'
import PropTypes from 'prop-types'
import { FormattedMessage } from 'react-intl'
import { Flex } from 'rebass/styled-components'
import { Card } from 'components/UI'
import ChannelsCapacity from './ChannelsCapacity'
import ChannelsSummaryDonut from './ChannelsSummaryDonut'
import messages from './messages'
const ChannelsInfo = ({ channels, receiveCapacity, sendCapacity, ...rest }) => {
const hasCapacity = Boolean(receiveCapacity || sendCapacity)
return (
<Card pb={2} pt={2} px={3} width={1} {...rest}>
<Flex alignItems="center" as="section" justifyContent="space-between" mt={2}>
<Flex alignItems="center" as="section">
{hasCapacity && (
<ChannelsSummaryDonut
mr={3}
receiveCapacity={receiveCapacity}
sendCapacity={sendCapacity}
width={40}
/>
)}
<ChannelsCapacity
capacity={sendCapacity}
message={<FormattedMessage {...messages.total_capacity_send} />}
mr={3}
my={2}
/>
<ChannelsCapacity
capacity={receiveCapacity}
color="superBlue"
message={<FormattedMessage {...messages.total_capacity_receive} />}
my={2}
/>
</Flex>
</Flex>
</Card>
)
}
ChannelsInfo.propTypes = {
channels: PropTypes.array,
receiveCapacity: PropTypes.string.isRequired,
sendCapacity: PropTypes.string.isRequired,
}
ChannelsInfo.defaultProps = {
channels: [],
}
export default ChannelsInfo
|
awesomeProject/timeBattery/src/index.js | yuanzhaokang/myAwesomeSimpleDemo | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
client/components/categories/item.js | jankeromnes/kresus | import React from 'react';
import PropTypes from 'prop-types';
import { translate as $t, NONE_CATEGORY_ID, assert } from '../../helpers';
import ConfirmDeleteModal from '../ui/confirm-delete-modal';
import ColorPicker from '../ui/color-picker';
class CategoryListItem extends React.Component {
constructor(props) {
super(props);
if (this.isCreating()) {
assert(this.props.createCategory instanceof Function);
assert(this.props.onCancelCreation instanceof Function);
} else {
assert(this.props.updateCategory instanceof Function);
assert(this.props.deleteCategory instanceof Function);
}
this.handleKeyUp = this.handleKeyUp.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleSave = this.handleSave.bind(this);
this.handleColorSave = this.handleColorSave.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.colorInput = null;
this.titleInput = null;
this.replacementSelector = null;
}
isEditing() {
return (typeof this.props.cat.id !== 'undefined');
}
isCreating() {
return !this.isEditing();
}
handleKeyUp(e) {
if (e.key === 'Enter') {
return this.handleSave(e);
} else if (e.key === 'Escape') {
if (this.isEditing()) {
e.target.value = this.props.cat.title;
} else {
this.props.onCancelCreation(e);
}
}
return true;
}
handleColorSave(e) {
if (this.isEditing() || this.titleInput.value.trim().length) {
this.handleSave(e);
}
}
handleSave(e) {
let cat = this.props.cat;
let title = this.titleInput.value.trim();
let color = this.colorInput.getValue();
if (!title || !color || ((color === cat.color) && (title === cat.title))) {
if (this.isCreating()) {
this.props.onCancelCreation(e);
} else if (!this.title) {
this.titleInput.value = this.props.cat.title;
}
return false;
}
let category = {
title,
color
};
if (this.isEditing()) {
this.props.updateCategory(cat, category);
} else {
this.props.createCategory(category);
this.titleInput.value = '';
this.props.onCancelCreation(e);
}
if (e && e instanceof Event) {
e.preventDefault();
}
}
handleBlur(e) {
if (this.isEditing()) {
this.handleSave(e);
}
}
handleDelete(e) {
if (this.isEditing()) {
let replaceCategory = this.replacementSelector.value;
this.props.deleteCategory(this.props.cat, replaceCategory);
} else {
this.props.onCancelCreation(e);
}
}
selectTitle() {
this.titleInput.select();
}
render() {
let c = this.props.cat;
let replacementOptions = this.props.categories
.filter(cat => cat.id !== c.id)
.map(cat => (
<option
key={ cat.id }
value={ cat.id }>
{ cat.title }
</option>
));
replacementOptions = [
<option
key="none"
value={ NONE_CATEGORY_ID }>
{ $t('client.category.dont_replace') }
</option>
].concat(replacementOptions);
let deleteButton;
let maybeModal;
if (this.isCreating()) {
deleteButton = (<span
className="fa fa-times-circle"
aria-label="remove"
onClick={ this.handleDelete }
title={ $t('client.general.delete') }
/>);
} else {
deleteButton = (<span
className="fa fa-times-circle"
aria-label="remove"
data-toggle="modal"
data-target={ `#confirmDeleteCategory${c.id}` }
title={ $t('client.general.delete') }
/>);
let refReplacementSelector = selector => {
this.replacementSelector = selector;
};
let modalBody = (<div>
<div className="alert alert-info">
{ $t('client.category.erase', { title: c.title }) }
</div>
<div>
<select
className="form-control"
ref={ refReplacementSelector }>
{ replacementOptions }
</select>
</div>
</div>);
maybeModal = (<ConfirmDeleteModal
modalId={ `confirmDeleteCategory${c.id}` }
modalBody={ modalBody }
onDelete={ this.handleDelete }
/>);
}
let refColorInput = input => {
this.colorInput = input;
};
let refTitleInput = input => {
this.titleInput = input;
};
return (
<tr key={ c.id }>
<td>
<ColorPicker
defaultValue={ c.color }
onChange={ this.handleColorSave }
ref={ refColorInput }
/>
</td>
<td>
<input
type="text"
className="form-control"
placeholder={ $t('client.category.label') }
defaultValue={ c.title }
onKeyUp={ this.handleKeyUp }
onBlur={ this.handleBlur }
ref={ refTitleInput }
/>
</td>
<td>
{ deleteButton }
{ maybeModal }
</td>
</tr>
);
}
}
CategoryListItem.propTypes = {
// The category related to this item.
cat: PropTypes.object.isRequired,
// The list of categories.
categories: PropTypes.array.isRequired,
// The method to create a category.
createCategory: PropTypes.func,
// The method to update a category.
updateCategory: PropTypes.func,
// The method to delete a category.
deleteCategory: PropTypes.func,
// A method to call when the creation of a category is cancelled.
onCancelCreation: PropTypes.func
};
export default CategoryListItem;
|
ajax/libs/ngOfficeUiFabric/0.4.0/ngOfficeUiFabric.js | sufuf3/cdnjs | /*!
* ngOfficeUIFabric
* http://ngofficeuifabric.com
* Angular 1.x directives for Microsoft's Office UI Fabric
* https://angularjs.org & https://dev.office.com/fabric
* v0.4.0
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("angular"));
else if(typeof define === 'function' && define.amd)
define(["angular"], factory);
else {
var a = typeof exports === 'object' ? factory(require("angular")) : factory(root["angular"]);
for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
}
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
module.exports = __webpack_require__(3);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
exports.module = ng.module('officeuifabric.core', []);
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var calloutModule = __webpack_require__(4);
var buttonModule = __webpack_require__(7);
var choicefieldModule = __webpack_require__(10);
var contextualMenuModule = __webpack_require__(12);
var dropdownModule = __webpack_require__(13);
var iconModule = __webpack_require__(14);
var labelModule = __webpack_require__(16);
var linkModule = __webpack_require__(17);
var overlayModule = __webpack_require__(18);
var progressIndicatorModule = __webpack_require__(20);
var searchboxModule = __webpack_require__(21);
var spinnerModule = __webpack_require__(22);
var tableModule = __webpack_require__(24);
var textFieldModule = __webpack_require__(26);
var toggleModule = __webpack_require__(27);
exports.module = ng.module('officeuifabric.components', [
calloutModule.module.name,
buttonModule.module.name,
choicefieldModule.module.name,
contextualMenuModule.module.name,
dropdownModule.module.name,
iconModule.module.name,
labelModule.module.name,
linkModule.module.name,
overlayModule.module.name,
progressIndicatorModule.module.name,
searchboxModule.module.name,
spinnerModule.module.name,
tableModule.module.name,
textFieldModule.module.name,
toggleModule.module.name
]);
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var calloutTypeEnum_1 = __webpack_require__(5);
var calloutArrowEnum_1 = __webpack_require__(6);
var CalloutController = (function () {
function CalloutController($scope, $log) {
this.$scope = $scope;
this.$log = $log;
}
CalloutController.$inject = ['$scope', '$log'];
return CalloutController;
})();
exports.CalloutController = CalloutController;
var CalloutHeaderDirective = (function () {
function CalloutHeaderDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = false;
this.scope = false;
this.template = '<div class="ms-Callout-header"><p class="ms-Callout-title" ng-transclude></p></div>';
}
CalloutHeaderDirective.factory = function () {
var directive = function () { return new CalloutHeaderDirective(); };
return directive;
};
CalloutHeaderDirective.prototype.link = function (scope, instanceElement, attrs, ctrls) {
var mainWrapper = instanceElement.parent().parent();
if (!ng.isUndefined(mainWrapper) && mainWrapper.hasClass('ms-Callout-main')) {
var detachedHeader = instanceElement.detach();
mainWrapper.prepend(detachedHeader);
}
};
return CalloutHeaderDirective;
})();
exports.CalloutHeaderDirective = CalloutHeaderDirective;
var CalloutContentDirective = (function () {
function CalloutContentDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = false;
this.scope = false;
this.template = '<div class="ms-Callout-content"><p class="ms-Callout-subText" ng-transclude></p></div>';
}
CalloutContentDirective.factory = function () {
var directive = function () { return new CalloutContentDirective(); };
return directive;
};
return CalloutContentDirective;
})();
exports.CalloutContentDirective = CalloutContentDirective;
var CalloutActionsDirective = (function () {
function CalloutActionsDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = false;
this.scope = false;
this.template = '<div class="ms-Callout-actions" ng-transclude></div>';
this.require = '^?uifCallout';
}
CalloutActionsDirective.factory = function () {
var directive = function () { return new CalloutActionsDirective(); };
return directive;
};
CalloutActionsDirective.prototype.link = function (scope, instanceElement, attrs, calloutController) {
if (ng.isObject(calloutController)) {
calloutController.$scope.$watch('hasSeparator', function (hasSeparator) {
var actionChildren = instanceElement.children().eq(0).children();
for (var buttonIndex = 0; buttonIndex < actionChildren.length; buttonIndex++) {
var action = actionChildren.eq(buttonIndex);
if (hasSeparator) {
action.addClass('ms-Callout-action');
}
else {
action.removeClass('ms-Callout-action');
}
var actionSpans = action.find('span');
for (var spanIndex = 0; spanIndex < actionSpans.length; spanIndex++) {
var actionSpan = actionSpans.eq(spanIndex);
if (hasSeparator) {
actionSpan.addClass('ms-Callout-actionText');
}
else {
actionSpan.removeClass('ms-Callout-actionText');
}
}
}
});
}
};
return CalloutActionsDirective;
})();
exports.CalloutActionsDirective = CalloutActionsDirective;
var CalloutDirective = (function () {
function CalloutDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = false;
this.template = '<div class="ms-Callout ms-Callout--arrow{{arrowDirection}}" ' +
'ng-class="{\'ms-Callout--actionText\': hasSeparator, \'ms-Callout--OOBE\': uifType==\'oobe\',' +
' \'ms-Callout--Peek\': uifType==\'peek\', \'ms-Callout--close\': closeButton}">' +
'<div class="ms-Callout-main"><div class="ms-Callout-inner" ng-transclude></div></div></div>';
this.require = ['uifCallout'];
this.scope = {
ngShow: '=?',
uifType: '@'
};
this.controller = CalloutController;
}
CalloutDirective.factory = function () {
var directive = function () { return new CalloutDirective(); };
return directive;
};
CalloutDirective.prototype.link = function (scope, instanceElement, attrs, ctrls) {
var calloutController = ctrls[0];
attrs.$observe('uifType', function (calloutType) {
if (ng.isUndefined(calloutTypeEnum_1.CalloutType[calloutType])) {
calloutController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.callout - "' +
calloutType + '" is not a valid value for uifType. It should be oobe or peek');
}
});
if (!attrs.uifArrow) {
scope.arrowDirection = 'Left';
}
attrs.$observe('uifArrow', function (attrArrowDirection) {
if (ng.isUndefined(calloutArrowEnum_1.CalloutArrow[attrArrowDirection])) {
calloutController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.callout - "' +
attrArrowDirection + '" is not a valid value for uifArrow. It should be left, right, top, bottom.');
return;
}
var capitalizedDirection = (attrArrowDirection.charAt(0)).toUpperCase();
capitalizedDirection += (attrArrowDirection.slice(1)).toLowerCase();
scope.arrowDirection = capitalizedDirection;
});
scope.hasSeparator = (!ng.isUndefined(attrs.uifActionText) || !ng.isUndefined(attrs.uifSeparator));
if (!ng.isUndefined(attrs.uifClose)) {
scope.closeButton = true;
var closeButtonElement = ng.element('<button class="ms-Callout-close">' +
'<i class="ms-Icon ms-Icon--x"></i>' +
'</button>');
var calloutDiv = instanceElement.find('div').eq(0);
calloutDiv.append(closeButtonElement);
closeButtonElement.bind('click', function (eventObject) {
scope.ngShow = false;
scope.closeButtonClicked = true;
scope.$apply();
});
}
instanceElement.bind('mouseenter', function (eventObject) {
scope.isMouseOver = true;
scope.$apply();
});
instanceElement.bind('mouseleave', function (eventObject) {
scope.isMouseOver = false;
scope.$apply();
});
scope.$watch('ngShow', function (newValue, oldValue) {
var isClosingByButtonClick = !newValue && scope.closeButtonClicked;
if (isClosingByButtonClick) {
scope.ngShow = scope.closeButtonClicked = false;
return;
}
if (!newValue) {
scope.ngShow = scope.isMouseOver;
}
});
scope.$watch('isMouseOver', function (newVal, oldVal) {
if (!newVal && oldVal) {
if (!scope.closeButton) {
scope.ngShow = false;
}
}
});
};
return CalloutDirective;
})();
exports.CalloutDirective = CalloutDirective;
exports.module = ng.module('officeuifabric.components.callout', ['officeuifabric.components'])
.directive('uifCallout', CalloutDirective.factory())
.directive('uifCalloutHeader', CalloutHeaderDirective.factory())
.directive('uifCalloutContent', CalloutContentDirective.factory())
.directive('uifCalloutActions', CalloutActionsDirective.factory());
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
(function (CalloutType) {
CalloutType[CalloutType["oobe"] = 0] = "oobe";
CalloutType[CalloutType["peek"] = 1] = "peek";
})(exports.CalloutType || (exports.CalloutType = {}));
var CalloutType = exports.CalloutType;
/***/ },
/* 6 */
/***/ function(module, exports) {
'use strict';
(function (CalloutArrow) {
CalloutArrow[CalloutArrow["left"] = 0] = "left";
CalloutArrow[CalloutArrow["right"] = 1] = "right";
CalloutArrow[CalloutArrow["top"] = 2] = "top";
CalloutArrow[CalloutArrow["bottom"] = 3] = "bottom";
})(exports.CalloutArrow || (exports.CalloutArrow = {}));
var CalloutArrow = exports.CalloutArrow;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var buttonTypeEnum_ts_1 = __webpack_require__(8);
var buttonTemplateType_ts_1 = __webpack_require__(9);
var ButtonController = (function () {
function ButtonController($log) {
this.$log = $log;
}
ButtonController.$inject = ['$log'];
return ButtonController;
})();
var ButtonDirective = (function () {
function ButtonDirective($log) {
var _this = this;
this.$log = $log;
this.restrict = 'E';
this.transclude = true;
this.replace = true;
this.scope = {};
this.controller = ButtonController;
this.controllerAs = 'button';
this.template = function ($element, $attrs) {
if (!ng.isUndefined($attrs.uifType) && ng.isUndefined(buttonTypeEnum_ts_1.ButtonTypeEnum[$attrs.uifType])) {
_this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.button - Unsupported button: ' +
'The button (\'' + $attrs.uifType + '\') is not supported by the Office UI Fabric. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/button/buttonTypeEnum.ts');
}
switch ($attrs.uifType) {
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.primary]:
return ng.isUndefined($attrs.ngHref)
? _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.primaryButton]
: _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.primaryLink];
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.command]:
return ng.isUndefined($attrs.ngHref)
? _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.commandButton]
: _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.commandLink];
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.compound]:
return ng.isUndefined($attrs.ngHref)
? _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.compoundButton]
: _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.compoundLink];
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.hero]:
return ng.isUndefined($attrs.ngHref)
? _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.heroButton]
: _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.heroLink];
default:
return ng.isUndefined($attrs.ngHref)
? _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.actionButton]
: _this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.actionLink];
}
};
this.templateOptions = {};
this._populateHtmlTemplates();
}
ButtonDirective.factory = function () {
var directive = function ($log) { return new ButtonDirective($log); };
directive.$inject = ['$log'];
return directive;
};
ButtonDirective.prototype.compile = function (element, attrs, transclude) {
return {
post: this.postLink,
pre: this.preLink
};
};
ButtonDirective.prototype.preLink = function (scope, element, attrs, controllers, transclude) {
var disabled = 'disabled' in attrs;
scope.disabled = disabled;
};
ButtonDirective.prototype.postLink = function (scope, element, attrs, controllers, transclude) {
if (ng.isUndefined(attrs.uifType) ||
attrs.uifType === buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.primary] ||
attrs.uifType === buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.compound]) {
var iconElement = element.find('uif-icon');
if (iconElement.length !== 0) {
iconElement.remove();
controllers.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.button - ' +
'Icon not allowed in primary or compound buttons: ' +
'The primary & compound button does not support including icons in the body. ' +
'The icon has been removed but may cause rendering errors. Consider buttons that support icons such as command or hero.');
}
}
transclude(function (clone) {
var wrapper;
switch (attrs.uifType) {
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.command]:
for (var i = 0; i < clone.length; i++) {
if (clone[i].tagName === 'SPAN') {
wrapper = ng.element('<span></span>');
wrapper.addClass('ms-Button-label').append(clone[i]);
element.append(wrapper);
}
if (clone[i].tagName === 'UIF-ICON') {
wrapper = ng.element('<span></span>');
wrapper.addClass('ms-Button-icon').append(clone[i]);
element.append(wrapper);
}
}
break;
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.compound]:
for (var i = 0; i < clone.length; i++) {
if (clone[i].tagName !== 'SPAN') {
continue;
}
if (clone[i].classList[0] === 'ng-scope' &&
clone[i].classList.length === 1) {
wrapper = ng.element('<span></span>');
wrapper.addClass('ms-Button-label').append(clone[i]);
element.append(wrapper);
}
else {
element.append(clone[i]);
}
}
break;
case buttonTypeEnum_ts_1.ButtonTypeEnum[buttonTypeEnum_ts_1.ButtonTypeEnum.hero]:
for (var i = 0; i < clone.length; i++) {
if (clone[i].tagName === 'SPAN') {
wrapper = ng.element('<span></span>');
wrapper.addClass('ms-Button-label').append(clone[i]);
element.append(wrapper);
}
if (clone[i].tagName === 'UIF-ICON') {
wrapper = ng.element('<span></span>');
wrapper.addClass('ms-Button-icon').append(clone[i]);
element.append(wrapper);
}
}
break;
default:
break;
}
});
};
ButtonDirective.prototype._populateHtmlTemplates = function () {
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.actionButton] =
"<button class=\"ms-Button\" ng-class=\"{'is-disabled': disabled}\">\n <span class=\"ms-Button-label\" ng-transclude></span>\n </button>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.actionLink] =
"<a class=\"ms-Button\" ng-class=\"{'is-disabled': disabled}\">\n <span class=\"ms-Button-label\" ng-transclude></span>\n </a>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.primaryButton] =
"<button class=\"ms-Button ms-Button--primary\" ng-class=\"{'is-disabled': disabled}\">\n <span class=\"ms-Button-label\" ng-transclude></span>\n </button>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.primaryLink] =
"<a class=\"ms-Button ms-Button--primary\" ng-class=\"{'is-disabled': disabled}\">\n <span class=\"ms-Button-label\" ng-transclude></span>\n </a>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.commandButton] =
"<button class=\"ms-Button ms-Button--command\" ng-class=\"{'is-disabled': disabled}\"></button>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.commandLink] =
"<a class=\"ms-Button ms-Button--command\" ng-class=\"{'is-disabled': disabled}\"></a>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.compoundButton] =
"<button class=\"ms-Button ms-Button--compound\" ng-class=\"{'is-disabled': disabled}\"></button>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.compoundLink] =
"<a class=\"ms-Button ms-Button--compound\" ng-class=\"{'is-disabled': disabled}\"></a>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.heroButton] =
"<button class=\"ms-Button ms-Button--hero\" ng-class=\"{'is-disabled': disabled}\"></button>";
this.templateOptions[buttonTemplateType_ts_1.ButtonTemplateType.heroLink] =
"<a class=\"ms-Button ms-Button--hero\" ng-class=\"{'is-disabled': disabled}\"></a>";
};
return ButtonDirective;
})();
exports.ButtonDirective = ButtonDirective;
var ButtonDescriptionDirective = (function () {
function ButtonDescriptionDirective() {
this.restrict = 'E';
this.require = '^uifButton';
this.transclude = true;
this.replace = true;
this.scope = false;
this.template = '<span class="ms-Button-description" ng-transclude></span>';
}
ButtonDescriptionDirective.factory = function () {
var directive = function () { return new ButtonDescriptionDirective(); };
return directive;
};
return ButtonDescriptionDirective;
})();
exports.ButtonDescriptionDirective = ButtonDescriptionDirective;
exports.module = ng.module('officeuifabric.components.button', [
'officeuifabric.components'
])
.directive('uifButton', ButtonDirective.factory())
.directive('uifButtonDescription', ButtonDescriptionDirective.factory());
/***/ },
/* 8 */
/***/ function(module, exports) {
'use strict';
(function (ButtonTypeEnum) {
ButtonTypeEnum[ButtonTypeEnum["primary"] = 0] = "primary";
ButtonTypeEnum[ButtonTypeEnum["command"] = 1] = "command";
ButtonTypeEnum[ButtonTypeEnum["compound"] = 2] = "compound";
ButtonTypeEnum[ButtonTypeEnum["hero"] = 3] = "hero";
})(exports.ButtonTypeEnum || (exports.ButtonTypeEnum = {}));
var ButtonTypeEnum = exports.ButtonTypeEnum;
;
/***/ },
/* 9 */
/***/ function(module, exports) {
'use strict';
(function (ButtonTemplateType) {
ButtonTemplateType[ButtonTemplateType["actionButton"] = 0] = "actionButton";
ButtonTemplateType[ButtonTemplateType["actionLink"] = 1] = "actionLink";
ButtonTemplateType[ButtonTemplateType["primaryButton"] = 2] = "primaryButton";
ButtonTemplateType[ButtonTemplateType["primaryLink"] = 3] = "primaryLink";
ButtonTemplateType[ButtonTemplateType["commandButton"] = 4] = "commandButton";
ButtonTemplateType[ButtonTemplateType["commandLink"] = 5] = "commandLink";
ButtonTemplateType[ButtonTemplateType["compoundButton"] = 6] = "compoundButton";
ButtonTemplateType[ButtonTemplateType["compoundLink"] = 7] = "compoundLink";
ButtonTemplateType[ButtonTemplateType["heroButton"] = 8] = "heroButton";
ButtonTemplateType[ButtonTemplateType["heroLink"] = 9] = "heroLink";
})(exports.ButtonTemplateType || (exports.ButtonTemplateType = {}));
var ButtonTemplateType = exports.ButtonTemplateType;
;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var choicefieldTypeEnum_1 = __webpack_require__(11);
var ChoicefieldOptionController = (function () {
function ChoicefieldOptionController($log) {
this.$log = $log;
}
ChoicefieldOptionController.$inject = ['$log'];
return ChoicefieldOptionController;
})();
exports.ChoicefieldOptionController = ChoicefieldOptionController;
var ChoicefieldOptionDirective = (function () {
function ChoicefieldOptionDirective() {
this.template = '<div class="ms-ChoiceField">' +
'<input id="{{::$id}}" class="ms-ChoiceField-input" type="{{uifType}}" value="{{value}}" ' +
'ng-model="ngModel" ng-true-value="{{ngTrueValue}}" ng-false-value="{{ngFalseValue}}" />' +
'<label for="{{::$id}}" class="ms-ChoiceField-field"><span class="ms-Label" ng-transclude></span></label>' +
'</div>';
this.restrict = 'E';
this.require = ['uifChoicefieldOption', '^?uifChoicefieldGroup'];
this.replace = true;
this.transclude = true;
this.scope = {
ngFalseValue: '@',
ngModel: '=',
ngTrueValue: '@',
uifType: '@',
value: '@'
};
this.controller = ChoicefieldOptionController;
}
ChoicefieldOptionDirective.factory = function () {
var directive = function () {
return new ChoicefieldOptionDirective();
};
return directive;
};
ChoicefieldOptionDirective.prototype.compile = function (templateElement, templateAttributes, transclude) {
var input = templateElement.find('input');
if (!('ngModel' in templateAttributes)) {
input.removeAttr('ng-model');
}
return {
pre: this.preLink
};
};
ChoicefieldOptionDirective.prototype.preLink = function (scope, instanceElement, attrs, ctrls, transclude) {
var choicefieldOptionController = ctrls[0];
var choicefieldGroupController = ctrls[1];
scope.$watch('uifType', function (newValue, oldValue) {
if (choicefieldTypeEnum_1.ChoicefieldType[newValue] === undefined) {
choicefieldOptionController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.choicefield - "' +
newValue + '" is not a valid value for uifType. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/choicefield/choicefieldTypeEnum.ts');
}
});
if (choicefieldGroupController != null) {
var render = function () {
var checked = (choicefieldGroupController.getViewValue() === attrs.value);
instanceElement.find('input').prop('checked', checked);
};
choicefieldGroupController.addRender(render);
attrs.$observe('value', render);
instanceElement
.on('$destroy', function () {
choicefieldGroupController.removeRender(render);
});
}
var disabled = 'disabled' in attrs;
var parentScope = scope.$parent.$parent;
disabled = disabled || (parentScope != null && parentScope.disabled);
if (disabled) {
instanceElement.find('input').attr('disabled', 'disabled');
}
instanceElement
.on('click', function (ev) {
if (disabled) {
return;
}
scope.$apply(function () {
if (choicefieldGroupController != null) {
choicefieldGroupController.setViewValue(attrs.value, ev);
}
});
});
};
return ChoicefieldOptionDirective;
})();
exports.ChoicefieldOptionDirective = ChoicefieldOptionDirective;
var ChoicefieldGroupController = (function () {
function ChoicefieldGroupController($element, $scope) {
this.$element = $element;
this.$scope = $scope;
this.renderFns = [];
}
ChoicefieldGroupController.prototype.init = function () {
var _this = this;
if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) {
this.$scope.ngModel.$render = function () {
_this.render();
};
this.render();
}
};
ChoicefieldGroupController.prototype.addRender = function (fn) {
this.renderFns.push(fn);
};
ChoicefieldGroupController.prototype.removeRender = function (fn) {
this.renderFns.splice(this.renderFns.indexOf(fn));
};
ChoicefieldGroupController.prototype.setViewValue = function (value, eventType) {
this.$scope.ngModel.$setViewValue(value, eventType);
this.render();
};
ChoicefieldGroupController.prototype.getViewValue = function () {
if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) {
return this.$scope.ngModel.$viewValue;
}
};
ChoicefieldGroupController.prototype.render = function () {
for (var i = 0; i < this.renderFns.length; i++) {
this.renderFns[i]();
}
};
ChoicefieldGroupController.$inject = ['$element', '$scope'];
return ChoicefieldGroupController;
})();
exports.ChoicefieldGroupController = ChoicefieldGroupController;
var ChoicefieldGroupDirective = (function () {
function ChoicefieldGroupDirective() {
this.template = '<div class="ms-ChoiceFieldGroup">' +
'<div class="ms-ChoiceFieldGroup-title">' +
'<label class="ms-Label is-required">Pick one</label>' +
'</div>' +
'<ng-transclude />' +
'</div>';
this.restrict = 'E';
this.transclude = true;
this.require = ['uifChoicefieldGroup', '?ngModel'];
this.controller = ChoicefieldGroupController;
}
ChoicefieldGroupDirective.factory = function () {
var directive = function () { return new ChoicefieldGroupDirective(); };
return directive;
};
ChoicefieldGroupDirective.prototype.compile = function (templateElement, templateAttributes, transclude) {
return {
pre: this.preLink
};
};
ChoicefieldGroupDirective.prototype.preLink = function (scope, instanceElement, instanceAttributes, ctrls) {
var choicefieldGroupController = ctrls[0];
var modelController = ctrls[1];
scope.ngModel = modelController;
choicefieldGroupController.init();
scope.disabled = 'disabled' in instanceAttributes;
};
return ChoicefieldGroupDirective;
})();
exports.ChoicefieldGroupDirective = ChoicefieldGroupDirective;
exports.module = ng.module('officeuifabric.components.choicefield', [
'officeuifabric.components'
])
.directive('uifChoicefieldOption', ChoicefieldOptionDirective.factory())
.directive('uifChoicefieldGroup', ChoicefieldGroupDirective.factory());
/***/ },
/* 11 */
/***/ function(module, exports) {
'use strict';
(function (ChoicefieldType) {
ChoicefieldType[ChoicefieldType["radio"] = 0] = "radio";
ChoicefieldType[ChoicefieldType["checkbox"] = 1] = "checkbox";
})(exports.ChoicefieldType || (exports.ChoicefieldType = {}));
var ChoicefieldType = exports.ChoicefieldType;
;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var MenuItemTypes;
(function (MenuItemTypes) {
MenuItemTypes[MenuItemTypes["link"] = 0] = "link";
MenuItemTypes[MenuItemTypes["divider"] = 1] = "divider";
MenuItemTypes[MenuItemTypes["header"] = 2] = "header";
MenuItemTypes[MenuItemTypes["subMenu"] = 3] = "subMenu";
})(MenuItemTypes || (MenuItemTypes = {}));
exports.contextualMenuItemDirectiveName = 'uifContextualMenuItem';
exports.contextualMenuDirectiveName = 'uifContextualMenu';
var ContextualMenuItemDirective = (function () {
function ContextualMenuItemDirective($log) {
var _this = this;
this.$log = $log;
this.restrict = 'E';
this.require = '^uifContextualMenu';
this.transclude = true;
this.controller = ContextualMenuItemController;
this.template = function ($element, $attrs) {
var type = $attrs.uifType;
if (ng.isUndefined(type)) {
return _this.templateTypes[MenuItemTypes.link];
}
if (MenuItemTypes[type] === undefined) {
_this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - unsupported menu type:\n' +
'the type \'' + type + '\' is not supported by ng-Office UI Fabric as valid type for context menu.' +
'Supported types can be found under MenuItemTypes enum here:\n' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/contextualmenu/contextualMenu.ts');
}
return _this.templateTypes[MenuItemTypes[type]];
};
this.replace = true;
this.scope = {
isDisabled: '=?uifIsDisabled',
isSelected: '=?uifIsSelected',
onClick: '&uifClick',
text: '=uifText',
type: '@uifType'
};
this.templateTypes = {};
this.templateTypes[MenuItemTypes.subMenu] =
"<li class=\"ms-ContextualMenu-item\">\n <a class=\"ms-ContextualMenu-link ms-ContextualMenu-link--hasMenu\"\n ng-class=\"{'is-selected': isSelected, 'is-disabled': isDisabled}\" ng-click=\"selectItem()\" href>{{text}}</a>\n <i class=\"ms-ContextualMenu-subMenuIcon ms-Icon ms-Icon--chevronRight\"></i>\n <div class=\"content\"></div>\n </li>";
this.templateTypes[MenuItemTypes.link] =
"<li class=\"ms-ContextualMenu-item\">\n <a class=\"ms-ContextualMenu-link\" ng-class=\"{'is-selected': isSelected, 'is-disabled': isDisabled}\"\n ng-click=\"selectItem()\" href>{{text}}</a>\n </li>";
this.templateTypes[MenuItemTypes.header] = "<li class=\"ms-ContextualMenu-item ms-ContextualMenu-item--header\">{{text}}</li>";
this.templateTypes[MenuItemTypes.divider] = "<li class=\"ms-ContextualMenu-item ms-ContextualMenu-item--divider\"></li>";
}
ContextualMenuItemDirective.factory = function () {
var directive = function ($log) { return new ContextualMenuItemDirective($log); };
directive.$inject = ['$log'];
return directive;
};
ContextualMenuItemDirective.prototype.link = function ($scope, $element, $attrs, contextualMenuController, $transclude) {
if (typeof $scope.isDisabled !== 'boolean' && $scope.isDisabled !== undefined) {
contextualMenuController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - ' +
'invalid attribute type: \'uif-is-disabled\'.\n' +
'The type \'' + typeof $scope.isDisabled + '\' is not supported as valid type for \'uif-is-disabled\' attribute for ' +
'<uif-contextual-menu-item />. The valid type is boolean.');
}
if (typeof $scope.isSelected !== 'boolean' && $scope.isSelected !== undefined) {
contextualMenuController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - ' +
'invalid attribute type: \'uif-is-selected\'.\n' +
'The type \'' + typeof $scope.isSelected + '\' is not supported as valid type for \'uif-is-selected\' attribute for ' +
'<uif-contextual-menu-item />. The valid type is boolean.');
}
$transclude(function (clone) {
$element.find('div').replaceWith(clone);
});
$scope.selectItem = function () {
if (!contextualMenuController.isMultiSelectionMenu()) {
contextualMenuController.onDeselectItems();
}
if (ng.isUndefined($scope.isSelected) && !$scope.isDisabled) {
$scope.isSelected = true;
}
else {
$scope.isSelected = !$scope.isSelected;
}
if (contextualMenuController.isRootMenu()) {
contextualMenuController.onCloseMenus($scope.$id);
}
else {
if (!$scope.hasChildMenu) {
contextualMenuController.onCloseMenus(null, true);
contextualMenuController.onDeselectItems(true);
}
else {
contextualMenuController.onCloseMenus($scope.$id);
}
}
if ($scope.hasChildMenu) {
$scope.childMenuCtrl.openMenu();
}
if (!ng.isUndefined($scope.onClick)) {
$scope.onClick();
}
};
$scope.$on('uif-menu-deselect', function () {
$scope.isSelected = false;
});
$scope.$on('uif-menu-close', function (event, menuItemId) {
if ($scope.hasChildMenu && $scope.$id !== menuItemId) {
$scope.childMenuCtrl.closeMenu();
}
});
};
return ContextualMenuItemDirective;
})();
exports.ContextualMenuItemDirective = ContextualMenuItemDirective;
var ContextualMenuItemController = (function () {
function ContextualMenuItemController($scope, $element) {
this.$scope = $scope;
this.$element = $element;
}
ContextualMenuItemController.prototype.setChildMenu = function (childMenuCtrl) {
this.$scope.hasChildMenu = true;
this.$scope.childMenuCtrl = childMenuCtrl;
};
ContextualMenuItemController.$inject = ['$scope', '$element'];
return ContextualMenuItemController;
})();
exports.ContextualMenuItemController = ContextualMenuItemController;
var ContextualMenuDirective = (function () {
function ContextualMenuDirective() {
this.restrict = 'E';
this.require = exports.contextualMenuDirectiveName;
this.transclude = true;
this.template = "<ul class=\"ms-ContextualMenu\" ng-transclude></ul>";
this.replace = true;
this.controller = ContextualMenuController;
this.scope = {
isOpen: '=?uifIsOpen',
multiselect: '@uifMultiselect'
};
}
ContextualMenuDirective.factory = function () {
var directive = function () { return new ContextualMenuDirective(); };
return directive;
};
ContextualMenuDirective.prototype.link = function ($scope, $element, $attrs, contextualMenuController) {
var parentMenuItemCtrl = $element.controller(exports.contextualMenuItemDirectiveName);
if (!ng.isUndefined(parentMenuItemCtrl)) {
parentMenuItemCtrl.setChildMenu(contextualMenuController);
}
if (!ng.isUndefined($scope.multiselect) && $scope.multiselect.toLowerCase() === 'true') {
$element.addClass('ms-ContextualMenu--multiselect');
}
};
return ContextualMenuDirective;
})();
exports.ContextualMenuDirective = ContextualMenuDirective;
var ContextualMenuController = (function () {
function ContextualMenuController($scope, $animate, $element, $log) {
var _this = this;
this.$scope = $scope;
this.$animate = $animate;
this.$element = $element;
this.$log = $log;
this.isOpenClassName = 'is-open';
if (ng.isUndefined($element.controller(exports.contextualMenuItemDirectiveName))) {
$scope.isRootMenu = true;
}
$scope.$watch('isOpen', function (newValue) {
if (typeof newValue !== 'boolean' && newValue !== undefined) {
_this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - invalid attribute type: \'uif-is-open\'.\n' +
'The type \'' + typeof newValue + '\' is not supported as valid type for \'uif-is-open\' attribute for ' +
'<uif-contextual-menu />. The valid type is boolean.');
}
$animate[newValue ? 'addClass' : 'removeClass']($element, _this.isOpenClassName);
});
}
ContextualMenuController.prototype.onDeselectItems = function (deselectParentMenus) {
this.$scope.$broadcast('uif-menu-deselect');
if (deselectParentMenus) {
this.$scope.$emit('uif-menu-deselect');
}
};
ContextualMenuController.prototype.onCloseMenus = function (menuItemToSkip, closeRootMenu) {
if (closeRootMenu) {
this.$scope.$emit('uif-menu-close');
}
else {
this.$scope.$broadcast('uif-menu-close', menuItemToSkip);
}
};
ContextualMenuController.prototype.openMenu = function () {
this.$scope.isOpen = true;
};
ContextualMenuController.prototype.closeMenu = function () {
this.$scope.isOpen = false;
};
ContextualMenuController.prototype.isRootMenu = function () {
return this.$scope.isRootMenu;
};
ContextualMenuController.prototype.isMultiSelectionMenu = function () {
if (ng.isUndefined(this.$scope.multiselect)) {
return false;
}
return this.$scope.multiselect.toLowerCase() === 'true';
};
ContextualMenuController.$inject = ['$scope', '$animate', '$element', '$log'];
return ContextualMenuController;
})();
exports.ContextualMenuController = ContextualMenuController;
exports.module = ng.module('officeuifabric.components.contextualmenu', [
'officeuifabric.components'])
.directive(exports.contextualMenuDirectiveName, ContextualMenuDirective.factory())
.directive(exports.contextualMenuItemDirectiveName, ContextualMenuItemDirective.factory());
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var DropdownOptionDirective = (function () {
function DropdownOptionDirective() {
this.template = '<li class="ms-Dropdown-item" ng-transclude></li>';
this.restrict = 'E';
this.require = '^uifDropdown';
this.replace = true;
this.transclude = true;
}
DropdownOptionDirective.factory = function () {
var directive = function () { return new DropdownOptionDirective(); };
return directive;
};
DropdownOptionDirective.prototype.compile = function (templateElement, templateAttributes, transclude) {
return {
post: this.postLink
};
};
DropdownOptionDirective.prototype.postLink = function (scope, instanceElement, attrs, dropdownController, transclude) {
if (!dropdownController) {
throw 'Dropdown controller not found!';
}
instanceElement
.on('click', function (ev) {
scope.$apply(function () {
dropdownController.setViewValue(instanceElement.find('span').html(), attrs.value, ev);
});
});
};
return DropdownOptionDirective;
})();
exports.DropdownOptionDirective = DropdownOptionDirective;
var DropdownController = (function () {
function DropdownController($element, $scope) {
this.$element = $element;
this.$scope = $scope;
}
DropdownController.prototype.init = function () {
var self = this;
this.$element.bind('click', function () {
if (!self.$scope.disabled) {
self.$scope.isOpen = !self.$scope.isOpen;
self.$scope.$apply();
var dropdownWidth = angular.element(this.querySelector('.ms-Dropdown'))[0].clientWidth;
angular.element(this.querySelector('.ms-Dropdown-items'))[0].style.width = dropdownWidth + 'px';
}
});
if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) {
this.$scope.ngModel.$render = function () {
var options = self.$element.find('li');
for (var i = 0; i < options.length; i++) {
var option = options[i];
var value = option.getAttribute('value');
if (value === self.$scope.ngModel.$viewValue) {
self.$scope.selectedTitle = angular.element(option).find('span').html();
break;
}
}
};
}
};
DropdownController.prototype.setViewValue = function (title, value, eventType) {
this.$scope.selectedTitle = title;
this.$scope.ngModel.$setViewValue(value, eventType);
};
DropdownController.prototype.getViewValue = function () {
if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) {
return this.$scope.ngModel.$viewValue;
}
};
DropdownController.$inject = ['$element', '$scope'];
return DropdownController;
})();
exports.DropdownController = DropdownController;
var DropdownDirective = (function () {
function DropdownDirective() {
this.template = '<div ng-click="dropdownClick" ' +
'ng-class="{\'ms-Dropdown\' : true, \'is-open\': isOpen, \'is-disabled\': disabled}" tabindex="0">' +
'<i class="ms-Dropdown-caretDown ms-Icon ms-Icon--caretDown"></i>' +
'<span class="ms-Dropdown-title">{{selectedTitle}}</span><ul class="ms-Dropdown-items"><ng-transclude></ng-transclude></ul></div>';
this.restrict = 'E';
this.transclude = true;
this.require = ['uifDropdown', '?ngModel'];
this.scope = {};
this.controller = DropdownController;
}
DropdownDirective.factory = function () {
var directive = function () { return new DropdownDirective(); };
return directive;
};
DropdownDirective.prototype.compile = function (templateElement, templateAttributes, transclude) {
return {
pre: this.preLink
};
};
DropdownDirective.prototype.preLink = function (scope, instanceElement, instanceAttributes, ctrls) {
var dropdownController = ctrls[0];
var modelController = ctrls[1];
scope.ngModel = modelController;
dropdownController.init();
scope.disabled = 'disabled' in instanceAttributes;
};
return DropdownDirective;
})();
exports.DropdownDirective = DropdownDirective;
exports.module = ng.module('officeuifabric.components.dropdown', [
'officeuifabric.components'
])
.directive('uifDropdownOption', DropdownOptionDirective.factory())
.directive('uifDropdown', DropdownDirective.factory());
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var iconEnum_1 = __webpack_require__(15);
var IconController = (function () {
function IconController($log) {
this.$log = $log;
}
IconController.$inject = ['$log'];
return IconController;
})();
var IconDirective = (function () {
function IconDirective() {
this.restrict = 'E';
this.template = '<i class="ms-Icon ms-Icon--{{uifType}}" aria-hidden="true"></i>';
this.scope = {
uifType: '@'
};
this.transclude = true;
this.controller = IconController;
this.controllerAs = 'icon';
}
IconDirective.factory = function () {
var directive = function () { return new IconDirective(); };
return directive;
};
IconDirective.prototype.link = function (scope, instanceElement, attrs, controller) {
scope.$watch('uifType', function (newValule, oldValue) {
if (iconEnum_1.IconEnum[newValule] === undefined) {
controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.icon - Unsupported icon: ' +
'The icon (\'' + scope.uifType + '\') is not supported by the Office UI Fabric. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/icon/iconEnum.ts');
}
});
};
;
return IconDirective;
})();
exports.IconDirective = IconDirective;
exports.module = ng.module('officeuifabric.components.icon', [
'officeuifabric.components'
])
.directive('uifIcon', IconDirective.factory());
/***/ },
/* 15 */
/***/ function(module, exports) {
'use strict';
(function (IconEnum) {
IconEnum[IconEnum["alert"] = 0] = "alert";
IconEnum[IconEnum["alert2"] = 1] = "alert2";
IconEnum[IconEnum["alertOutline"] = 2] = "alertOutline";
IconEnum[IconEnum["arrowDown"] = 3] = "arrowDown";
IconEnum[IconEnum["arrowDown2"] = 4] = "arrowDown2";
IconEnum[IconEnum["arrowDownLeft"] = 5] = "arrowDownLeft";
IconEnum[IconEnum["arrowDownRight"] = 6] = "arrowDownRight";
IconEnum[IconEnum["arrowLeft"] = 7] = "arrowLeft";
IconEnum[IconEnum["arrowRight"] = 8] = "arrowRight";
IconEnum[IconEnum["arrowUp"] = 9] = "arrowUp";
IconEnum[IconEnum["arrowUp2"] = 10] = "arrowUp2";
IconEnum[IconEnum["arrowUpLeft"] = 11] = "arrowUpLeft";
IconEnum[IconEnum["arrowUpRight"] = 12] = "arrowUpRight";
IconEnum[IconEnum["ascending"] = 13] = "ascending";
IconEnum[IconEnum["at"] = 14] = "at";
IconEnum[IconEnum["attachment"] = 15] = "attachment";
IconEnum[IconEnum["bag"] = 16] = "bag";
IconEnum[IconEnum["balloon"] = 17] = "balloon";
IconEnum[IconEnum["bell"] = 18] = "bell";
IconEnum[IconEnum["boards"] = 19] = "boards";
IconEnum[IconEnum["bold"] = 20] = "bold";
IconEnum[IconEnum["bookmark"] = 21] = "bookmark";
IconEnum[IconEnum["books"] = 22] = "books";
IconEnum[IconEnum["briefcase"] = 23] = "briefcase";
IconEnum[IconEnum["bundle"] = 24] = "bundle";
IconEnum[IconEnum["cake"] = 25] = "cake";
IconEnum[IconEnum["calendar"] = 26] = "calendar";
IconEnum[IconEnum["calendarDay"] = 27] = "calendarDay";
IconEnum[IconEnum["calendarPublic"] = 28] = "calendarPublic";
IconEnum[IconEnum["calendarWeek"] = 29] = "calendarWeek";
IconEnum[IconEnum["calendarWorkWeek"] = 30] = "calendarWorkWeek";
IconEnum[IconEnum["camera"] = 31] = "camera";
IconEnum[IconEnum["car"] = 32] = "car";
IconEnum[IconEnum["caretDown"] = 33] = "caretDown";
IconEnum[IconEnum["caretDownLeft"] = 34] = "caretDownLeft";
IconEnum[IconEnum["caretDownOutline"] = 35] = "caretDownOutline";
IconEnum[IconEnum["caretDownRight"] = 36] = "caretDownRight";
IconEnum[IconEnum["caretLeft"] = 37] = "caretLeft";
IconEnum[IconEnum["caretLeftOutline"] = 38] = "caretLeftOutline";
IconEnum[IconEnum["caretRight"] = 39] = "caretRight";
IconEnum[IconEnum["caretRightOutline"] = 40] = "caretRightOutline";
IconEnum[IconEnum["caretUp"] = 41] = "caretUp";
IconEnum[IconEnum["caretUpLeft"] = 42] = "caretUpLeft";
IconEnum[IconEnum["caretUpOutline"] = 43] = "caretUpOutline";
IconEnum[IconEnum["caretUpRight"] = 44] = "caretUpRight";
IconEnum[IconEnum["cart"] = 45] = "cart";
IconEnum[IconEnum["cat"] = 46] = "cat";
IconEnum[IconEnum["chart"] = 47] = "chart";
IconEnum[IconEnum["chat"] = 48] = "chat";
IconEnum[IconEnum["chatAdd"] = 49] = "chatAdd";
IconEnum[IconEnum["check"] = 50] = "check";
IconEnum[IconEnum["checkbox"] = 51] = "checkbox";
IconEnum[IconEnum["checkboxCheck"] = 52] = "checkboxCheck";
IconEnum[IconEnum["checkboxEmpty"] = 53] = "checkboxEmpty";
IconEnum[IconEnum["checkboxMixed"] = 54] = "checkboxMixed";
IconEnum[IconEnum["checkPeople"] = 55] = "checkPeople";
IconEnum[IconEnum["chevronDown"] = 56] = "chevronDown";
IconEnum[IconEnum["chevronLeft"] = 57] = "chevronLeft";
IconEnum[IconEnum["chevronRight"] = 58] = "chevronRight";
IconEnum[IconEnum["chevronsDown"] = 59] = "chevronsDown";
IconEnum[IconEnum["chevronsLeft"] = 60] = "chevronsLeft";
IconEnum[IconEnum["chevronsRight"] = 61] = "chevronsRight";
IconEnum[IconEnum["chevronsUp"] = 62] = "chevronsUp";
IconEnum[IconEnum["chevronThickDown"] = 63] = "chevronThickDown";
IconEnum[IconEnum["chevronThickLeft"] = 64] = "chevronThickLeft";
IconEnum[IconEnum["chevronThickRight"] = 65] = "chevronThickRight";
IconEnum[IconEnum["chevronThickUp"] = 66] = "chevronThickUp";
IconEnum[IconEnum["chevronThinDown"] = 67] = "chevronThinDown";
IconEnum[IconEnum["chevronThinLeft"] = 68] = "chevronThinLeft";
IconEnum[IconEnum["chevronThinRight"] = 69] = "chevronThinRight";
IconEnum[IconEnum["chevronThinUp"] = 70] = "chevronThinUp";
IconEnum[IconEnum["chevronUp"] = 71] = "chevronUp";
IconEnum[IconEnum["circle"] = 72] = "circle";
IconEnum[IconEnum["circleBall"] = 73] = "circleBall";
IconEnum[IconEnum["circleBalloons"] = 74] = "circleBalloons";
IconEnum[IconEnum["circleCar"] = 75] = "circleCar";
IconEnum[IconEnum["circleCat"] = 76] = "circleCat";
IconEnum[IconEnum["circleCoffee"] = 77] = "circleCoffee";
IconEnum[IconEnum["circleDog"] = 78] = "circleDog";
IconEnum[IconEnum["circleEmpty"] = 79] = "circleEmpty";
IconEnum[IconEnum["circleFill"] = 80] = "circleFill";
IconEnum[IconEnum["circleFilled"] = 81] = "circleFilled";
IconEnum[IconEnum["circleHalfFilled"] = 82] = "circleHalfFilled";
IconEnum[IconEnum["circleInfo"] = 83] = "circleInfo";
IconEnum[IconEnum["circleLightning"] = 84] = "circleLightning";
IconEnum[IconEnum["circlePill"] = 85] = "circlePill";
IconEnum[IconEnum["circlePlane"] = 86] = "circlePlane";
IconEnum[IconEnum["circlePlus"] = 87] = "circlePlus";
IconEnum[IconEnum["circlePoodle"] = 88] = "circlePoodle";
IconEnum[IconEnum["circleUnfilled"] = 89] = "circleUnfilled";
IconEnum[IconEnum["classNotebook"] = 90] = "classNotebook";
IconEnum[IconEnum["classroom"] = 91] = "classroom";
IconEnum[IconEnum["clock"] = 92] = "clock";
IconEnum[IconEnum["clutter"] = 93] = "clutter";
IconEnum[IconEnum["coffee"] = 94] = "coffee";
IconEnum[IconEnum["collapse"] = 95] = "collapse";
IconEnum[IconEnum["conflict"] = 96] = "conflict";
IconEnum[IconEnum["contact"] = 97] = "contact";
IconEnum[IconEnum["contactForm"] = 98] = "contactForm";
IconEnum[IconEnum["contactPublic"] = 99] = "contactPublic";
IconEnum[IconEnum["copy"] = 100] = "copy";
IconEnum[IconEnum["creditCard"] = 101] = "creditCard";
IconEnum[IconEnum["creditCardOutline"] = 102] = "creditCardOutline";
IconEnum[IconEnum["dashboard"] = 103] = "dashboard";
IconEnum[IconEnum["descending"] = 104] = "descending";
IconEnum[IconEnum["desktop"] = 105] = "desktop";
IconEnum[IconEnum["deviceWipe"] = 106] = "deviceWipe";
IconEnum[IconEnum["dialpad"] = 107] = "dialpad";
IconEnum[IconEnum["directions"] = 108] = "directions";
IconEnum[IconEnum["document"] = 109] = "document";
IconEnum[IconEnum["documentAdd"] = 110] = "documentAdd";
IconEnum[IconEnum["documentForward"] = 111] = "documentForward";
IconEnum[IconEnum["documentLandscape"] = 112] = "documentLandscape";
IconEnum[IconEnum["documentPDF"] = 113] = "documentPDF";
IconEnum[IconEnum["documentReply"] = 114] = "documentReply";
IconEnum[IconEnum["documents"] = 115] = "documents";
IconEnum[IconEnum["documentSearch"] = 116] = "documentSearch";
IconEnum[IconEnum["dog"] = 117] = "dog";
IconEnum[IconEnum["dogAlt"] = 118] = "dogAlt";
IconEnum[IconEnum["dot"] = 119] = "dot";
IconEnum[IconEnum["download"] = 120] = "download";
IconEnum[IconEnum["drm"] = 121] = "drm";
IconEnum[IconEnum["drop"] = 122] = "drop";
IconEnum[IconEnum["dropdown"] = 123] = "dropdown";
IconEnum[IconEnum["editBox"] = 124] = "editBox";
IconEnum[IconEnum["ellipsis"] = 125] = "ellipsis";
IconEnum[IconEnum["embed"] = 126] = "embed";
IconEnum[IconEnum["event"] = 127] = "event";
IconEnum[IconEnum["eventCancel"] = 128] = "eventCancel";
IconEnum[IconEnum["eventInfo"] = 129] = "eventInfo";
IconEnum[IconEnum["eventRecurring"] = 130] = "eventRecurring";
IconEnum[IconEnum["eventShare"] = 131] = "eventShare";
IconEnum[IconEnum["exclamation"] = 132] = "exclamation";
IconEnum[IconEnum["expand"] = 133] = "expand";
IconEnum[IconEnum["eye"] = 134] = "eye";
IconEnum[IconEnum["favorites"] = 135] = "favorites";
IconEnum[IconEnum["fax"] = 136] = "fax";
IconEnum[IconEnum["fieldMail"] = 137] = "fieldMail";
IconEnum[IconEnum["fieldNumber"] = 138] = "fieldNumber";
IconEnum[IconEnum["fieldText"] = 139] = "fieldText";
IconEnum[IconEnum["fieldTextBox"] = 140] = "fieldTextBox";
IconEnum[IconEnum["fileDocument"] = 141] = "fileDocument";
IconEnum[IconEnum["fileImage"] = 142] = "fileImage";
IconEnum[IconEnum["filePDF"] = 143] = "filePDF";
IconEnum[IconEnum["filter"] = 144] = "filter";
IconEnum[IconEnum["filterClear"] = 145] = "filterClear";
IconEnum[IconEnum["firstAid"] = 146] = "firstAid";
IconEnum[IconEnum["flag"] = 147] = "flag";
IconEnum[IconEnum["folder"] = 148] = "folder";
IconEnum[IconEnum["folderMove"] = 149] = "folderMove";
IconEnum[IconEnum["folderPublic"] = 150] = "folderPublic";
IconEnum[IconEnum["folderSearch"] = 151] = "folderSearch";
IconEnum[IconEnum["fontColor"] = 152] = "fontColor";
IconEnum[IconEnum["fontDecrease"] = 153] = "fontDecrease";
IconEnum[IconEnum["fontIncrease"] = 154] = "fontIncrease";
IconEnum[IconEnum["frowny"] = 155] = "frowny";
IconEnum[IconEnum["fullscreen"] = 156] = "fullscreen";
IconEnum[IconEnum["gear"] = 157] = "gear";
IconEnum[IconEnum["glasses"] = 158] = "glasses";
IconEnum[IconEnum["globe"] = 159] = "globe";
IconEnum[IconEnum["graph"] = 160] = "graph";
IconEnum[IconEnum["group"] = 161] = "group";
IconEnum[IconEnum["header"] = 162] = "header";
IconEnum[IconEnum["heart"] = 163] = "heart";
IconEnum[IconEnum["heartEmpty"] = 164] = "heartEmpty";
IconEnum[IconEnum["hide"] = 165] = "hide";
IconEnum[IconEnum["home"] = 166] = "home";
IconEnum[IconEnum["inboxCheck"] = 167] = "inboxCheck";
IconEnum[IconEnum["info"] = 168] = "info";
IconEnum[IconEnum["infoCircle"] = 169] = "infoCircle";
IconEnum[IconEnum["italic"] = 170] = "italic";
IconEnum[IconEnum["key"] = 171] = "key";
IconEnum[IconEnum["late"] = 172] = "late";
IconEnum[IconEnum["lifesaver"] = 173] = "lifesaver";
IconEnum[IconEnum["lifesaverLock"] = 174] = "lifesaverLock";
IconEnum[IconEnum["lightBulb"] = 175] = "lightBulb";
IconEnum[IconEnum["lightning"] = 176] = "lightning";
IconEnum[IconEnum["link"] = 177] = "link";
IconEnum[IconEnum["linkRemove"] = 178] = "linkRemove";
IconEnum[IconEnum["listBullets"] = 179] = "listBullets";
IconEnum[IconEnum["listCheck"] = 180] = "listCheck";
IconEnum[IconEnum["listCheckbox"] = 181] = "listCheckbox";
IconEnum[IconEnum["listGroup"] = 182] = "listGroup";
IconEnum[IconEnum["listGroup2"] = 183] = "listGroup2";
IconEnum[IconEnum["listNumbered"] = 184] = "listNumbered";
IconEnum[IconEnum["lock"] = 185] = "lock";
IconEnum[IconEnum["mail"] = 186] = "mail";
IconEnum[IconEnum["mailCheck"] = 187] = "mailCheck";
IconEnum[IconEnum["mailDown"] = 188] = "mailDown";
IconEnum[IconEnum["mailEdit"] = 189] = "mailEdit";
IconEnum[IconEnum["mailEmpty"] = 190] = "mailEmpty";
IconEnum[IconEnum["mailError"] = 191] = "mailError";
IconEnum[IconEnum["mailOpen"] = 192] = "mailOpen";
IconEnum[IconEnum["mailPause"] = 193] = "mailPause";
IconEnum[IconEnum["mailPublic"] = 194] = "mailPublic";
IconEnum[IconEnum["mailRead"] = 195] = "mailRead";
IconEnum[IconEnum["mailSend"] = 196] = "mailSend";
IconEnum[IconEnum["mailSync"] = 197] = "mailSync";
IconEnum[IconEnum["mailUnread"] = 198] = "mailUnread";
IconEnum[IconEnum["mapMarker"] = 199] = "mapMarker";
IconEnum[IconEnum["meal"] = 200] = "meal";
IconEnum[IconEnum["menu"] = 201] = "menu";
IconEnum[IconEnum["menu2"] = 202] = "menu2";
IconEnum[IconEnum["merge"] = 203] = "merge";
IconEnum[IconEnum["metadata"] = 204] = "metadata";
IconEnum[IconEnum["microphone"] = 205] = "microphone";
IconEnum[IconEnum["miniatures"] = 206] = "miniatures";
IconEnum[IconEnum["minus"] = 207] = "minus";
IconEnum[IconEnum["mobile"] = 208] = "mobile";
IconEnum[IconEnum["money"] = 209] = "money";
IconEnum[IconEnum["move"] = 210] = "move";
IconEnum[IconEnum["multiChoice"] = 211] = "multiChoice";
IconEnum[IconEnum["music"] = 212] = "music";
IconEnum[IconEnum["navigate"] = 213] = "navigate";
IconEnum[IconEnum["new"] = 214] = "new";
IconEnum[IconEnum["newsfeed"] = 215] = "newsfeed";
IconEnum[IconEnum["note"] = 216] = "note";
IconEnum[IconEnum["notebook"] = 217] = "notebook";
IconEnum[IconEnum["noteEdit"] = 218] = "noteEdit";
IconEnum[IconEnum["noteForward"] = 219] = "noteForward";
IconEnum[IconEnum["noteReply"] = 220] = "noteReply";
IconEnum[IconEnum["notRecurring"] = 221] = "notRecurring";
IconEnum[IconEnum["onlineAdd"] = 222] = "onlineAdd";
IconEnum[IconEnum["onlineJoin"] = 223] = "onlineJoin";
IconEnum[IconEnum["oofReply"] = 224] = "oofReply";
IconEnum[IconEnum["org"] = 225] = "org";
IconEnum[IconEnum["page"] = 226] = "page";
IconEnum[IconEnum["paint"] = 227] = "paint";
IconEnum[IconEnum["panel"] = 228] = "panel";
IconEnum[IconEnum["partner"] = 229] = "partner";
IconEnum[IconEnum["pause"] = 230] = "pause";
IconEnum[IconEnum["pencil"] = 231] = "pencil";
IconEnum[IconEnum["people"] = 232] = "people";
IconEnum[IconEnum["peopleAdd"] = 233] = "peopleAdd";
IconEnum[IconEnum["peopleCheck"] = 234] = "peopleCheck";
IconEnum[IconEnum["peopleError"] = 235] = "peopleError";
IconEnum[IconEnum["peoplePause"] = 236] = "peoplePause";
IconEnum[IconEnum["peopleRemove"] = 237] = "peopleRemove";
IconEnum[IconEnum["peopleSecurity"] = 238] = "peopleSecurity";
IconEnum[IconEnum["peopleSync"] = 239] = "peopleSync";
IconEnum[IconEnum["person"] = 240] = "person";
IconEnum[IconEnum["personAdd"] = 241] = "personAdd";
IconEnum[IconEnum["personRemove"] = 242] = "personRemove";
IconEnum[IconEnum["phone"] = 243] = "phone";
IconEnum[IconEnum["phoneAdd"] = 244] = "phoneAdd";
IconEnum[IconEnum["phoneTransfer"] = 245] = "phoneTransfer";
IconEnum[IconEnum["picture"] = 246] = "picture";
IconEnum[IconEnum["pictureAdd"] = 247] = "pictureAdd";
IconEnum[IconEnum["pictureEdit"] = 248] = "pictureEdit";
IconEnum[IconEnum["pictureRemove"] = 249] = "pictureRemove";
IconEnum[IconEnum["pill"] = 250] = "pill";
IconEnum[IconEnum["pinDown"] = 251] = "pinDown";
IconEnum[IconEnum["pinLeft"] = 252] = "pinLeft";
IconEnum[IconEnum["placeholder"] = 253] = "placeholder";
IconEnum[IconEnum["plane"] = 254] = "plane";
IconEnum[IconEnum["play"] = 255] = "play";
IconEnum[IconEnum["plus"] = 256] = "plus";
IconEnum[IconEnum["plus2"] = 257] = "plus2";
IconEnum[IconEnum["pointItem"] = 258] = "pointItem";
IconEnum[IconEnum["popout"] = 259] = "popout";
IconEnum[IconEnum["post"] = 260] = "post";
IconEnum[IconEnum["print"] = 261] = "print";
IconEnum[IconEnum["protectionCenter"] = 262] = "protectionCenter";
IconEnum[IconEnum["question"] = 263] = "question";
IconEnum[IconEnum["questionReverse"] = 264] = "questionReverse";
IconEnum[IconEnum["quote"] = 265] = "quote";
IconEnum[IconEnum["radioButton"] = 266] = "radioButton";
IconEnum[IconEnum["reactivate"] = 267] = "reactivate";
IconEnum[IconEnum["receiptCheck"] = 268] = "receiptCheck";
IconEnum[IconEnum["receiptForward"] = 269] = "receiptForward";
IconEnum[IconEnum["receiptReply"] = 270] = "receiptReply";
IconEnum[IconEnum["refresh"] = 271] = "refresh";
IconEnum[IconEnum["reload"] = 272] = "reload";
IconEnum[IconEnum["reply"] = 273] = "reply";
IconEnum[IconEnum["replyAll"] = 274] = "replyAll";
IconEnum[IconEnum["replyAllAlt"] = 275] = "replyAllAlt";
IconEnum[IconEnum["replyAlt"] = 276] = "replyAlt";
IconEnum[IconEnum["ribbon"] = 277] = "ribbon";
IconEnum[IconEnum["room"] = 278] = "room";
IconEnum[IconEnum["save"] = 279] = "save";
IconEnum[IconEnum["scheduling"] = 280] = "scheduling";
IconEnum[IconEnum["search"] = 281] = "search";
IconEnum[IconEnum["section"] = 282] = "section";
IconEnum[IconEnum["sections"] = 283] = "sections";
IconEnum[IconEnum["settings"] = 284] = "settings";
IconEnum[IconEnum["share"] = 285] = "share";
IconEnum[IconEnum["shield"] = 286] = "shield";
IconEnum[IconEnum["sites"] = 287] = "sites";
IconEnum[IconEnum["smiley"] = 288] = "smiley";
IconEnum[IconEnum["soccer"] = 289] = "soccer";
IconEnum[IconEnum["socialListening"] = 290] = "socialListening";
IconEnum[IconEnum["sort"] = 291] = "sort";
IconEnum[IconEnum["sortLines"] = 292] = "sortLines";
IconEnum[IconEnum["split"] = 293] = "split";
IconEnum[IconEnum["star"] = 294] = "star";
IconEnum[IconEnum["starEmpty"] = 295] = "starEmpty";
IconEnum[IconEnum["stopwatch"] = 296] = "stopwatch";
IconEnum[IconEnum["story"] = 297] = "story";
IconEnum[IconEnum["styleRemove"] = 298] = "styleRemove";
IconEnum[IconEnum["subscribe"] = 299] = "subscribe";
IconEnum[IconEnum["sun"] = 300] = "sun";
IconEnum[IconEnum["sunAdd"] = 301] = "sunAdd";
IconEnum[IconEnum["sunQuestion"] = 302] = "sunQuestion";
IconEnum[IconEnum["support"] = 303] = "support";
IconEnum[IconEnum["table"] = 304] = "table";
IconEnum[IconEnum["tablet"] = 305] = "tablet";
IconEnum[IconEnum["tag"] = 306] = "tag";
IconEnum[IconEnum["taskRecurring"] = 307] = "taskRecurring";
IconEnum[IconEnum["tasks"] = 308] = "tasks";
IconEnum[IconEnum["teamwork"] = 309] = "teamwork";
IconEnum[IconEnum["text"] = 310] = "text";
IconEnum[IconEnum["textBox"] = 311] = "textBox";
IconEnum[IconEnum["tile"] = 312] = "tile";
IconEnum[IconEnum["timeline"] = 313] = "timeline";
IconEnum[IconEnum["today"] = 314] = "today";
IconEnum[IconEnum["toggle"] = 315] = "toggle";
IconEnum[IconEnum["toggleMiddle"] = 316] = "toggleMiddle";
IconEnum[IconEnum["touch"] = 317] = "touch";
IconEnum[IconEnum["trash"] = 318] = "trash";
IconEnum[IconEnum["triangleDown"] = 319] = "triangleDown";
IconEnum[IconEnum["triangleEmptyDown"] = 320] = "triangleEmptyDown";
IconEnum[IconEnum["triangleEmptyLeft"] = 321] = "triangleEmptyLeft";
IconEnum[IconEnum["triangleEmptyRight"] = 322] = "triangleEmptyRight";
IconEnum[IconEnum["triangleEmptyUp"] = 323] = "triangleEmptyUp";
IconEnum[IconEnum["triangleLeft"] = 324] = "triangleLeft";
IconEnum[IconEnum["triangleRight"] = 325] = "triangleRight";
IconEnum[IconEnum["triangleUp"] = 326] = "triangleUp";
IconEnum[IconEnum["trophy"] = 327] = "trophy";
IconEnum[IconEnum["underline"] = 328] = "underline";
IconEnum[IconEnum["unsubscribe"] = 329] = "unsubscribe";
IconEnum[IconEnum["upload"] = 330] = "upload";
IconEnum[IconEnum["video"] = 331] = "video";
IconEnum[IconEnum["voicemail"] = 332] = "voicemail";
IconEnum[IconEnum["voicemailForward"] = 333] = "voicemailForward";
IconEnum[IconEnum["voicemailReply"] = 334] = "voicemailReply";
IconEnum[IconEnum["waffle"] = 335] = "waffle";
IconEnum[IconEnum["work"] = 336] = "work";
IconEnum[IconEnum["wrench"] = 337] = "wrench";
IconEnum[IconEnum["x"] = 338] = "x";
IconEnum[IconEnum["xCircle"] = 339] = "xCircle";
})(exports.IconEnum || (exports.IconEnum = {}));
var IconEnum = exports.IconEnum;
;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var LabelDirective = (function () {
function LabelDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = false;
this.scope = false;
this.template = '<label class="ms-Label"><ng-transclude/></label>';
}
LabelDirective.factory = function () {
var directive = function () { return new LabelDirective(); };
return directive;
};
LabelDirective.prototype.link = function (scope, instanceElement, attributes) {
if (ng.isDefined(attributes.disabled)) {
instanceElement.find('label').eq(0).addClass('is-disabled');
}
if (ng.isDefined(attributes.required)) {
instanceElement.find('label').eq(0).addClass('is-required');
}
};
return LabelDirective;
})();
exports.LabelDirective = LabelDirective;
exports.module = ng.module('officeuifabric.components.label', ['officeuifabric.components'])
.directive('uifLabel', LabelDirective.factory());
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var LinkDirective = (function () {
function LinkDirective() {
this.restrict = 'E';
this.template = '<a ng-href="{{ ngHref }}" class="ms-Link" ng-transclude></a>';
this.scope = {
ngHref: '@'
};
this.transclude = true;
this.replace = true;
}
LinkDirective.factory = function () {
var directive = function () { return new LinkDirective(); };
return directive;
};
return LinkDirective;
})();
exports.LinkDirective = LinkDirective;
exports.module = ng.module('officeuifabric.components.link', [
'officeuifabric.components'
])
.directive('uifLink', LinkDirective.factory());
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var overlayModeEnum_ts_1 = __webpack_require__(19);
var OverlayController = (function () {
function OverlayController(log) {
this.log = log;
}
OverlayController.$inject = ['$log'];
return OverlayController;
})();
var OverlayDirective = (function () {
function OverlayDirective(log) {
this.log = log;
this.restrict = 'E';
this.template = '<div class="ms-Overlay" ng-class="{\'ms-Overlay--dark\': uifMode == \'dark\'}" ng-transclude></div>';
this.scope = {
uifMode: '@'
};
this.transclude = true;
OverlayDirective.log = log;
}
OverlayDirective.factory = function () {
var directive = function (log) { return new OverlayDirective(log); };
directive.$inject = ['$log'];
return directive;
};
OverlayDirective.prototype.link = function (scope) {
scope.$watch('uifMode', function (newValue, oldValue) {
if (overlayModeEnum_ts_1.OverlayMode[newValue] === undefined) {
OverlayDirective.log.error('Error [ngOfficeUiFabric] officeuifabric.components.overlay - Unsupported overlay mode: ' +
'The overlay mode (\'' + scope.uifMode + '\') is not supported by the Office UI Fabric. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/overlay/overlayModeEnum.ts');
}
});
};
;
return OverlayDirective;
})();
exports.OverlayDirective = OverlayDirective;
exports.module = ng.module('officeuifabric.components.overlay', [
'officeuifabric.components'
])
.directive('uifOverlay', OverlayDirective.factory());
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
(function (OverlayMode) {
OverlayMode[OverlayMode["light"] = 0] = "light";
OverlayMode[OverlayMode["dark"] = 1] = "dark";
})(exports.OverlayMode || (exports.OverlayMode = {}));
var OverlayMode = exports.OverlayMode;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var ProgressIndicatorDirective = (function () {
function ProgressIndicatorDirective(log) {
this.log = log;
this.restrict = 'E';
this.template = '<div class="ms-ProgressIndicator">' +
'<div class="ms-ProgressIndicator-itemName">{{uifName}}</div>' +
'<div class="ms-ProgressIndicator-itemProgress">' +
'<div class="ms-ProgressIndicator-progressTrack"></div>' +
'<div class="ms-ProgressIndicator-progressBar" ng-style="{width: uifPercentComplete+\'%\'}"></div>' +
'</div>' +
'<div class="ms-ProgressIndicator-itemDescription">{{uifDescription}}</div>' +
'</div>';
this.scope = {
uifDescription: '@',
uifName: '@',
uifPercentComplete: '@'
};
ProgressIndicatorDirective.log = log;
}
ProgressIndicatorDirective.factory = function () {
var directive = function (log) { return new ProgressIndicatorDirective(log); };
directive.$inject = ['$log'];
return directive;
};
ProgressIndicatorDirective.prototype.link = function (scope) {
scope.$watch('uifPercentComplete', function (newValue, oldValue) {
if (newValue == null || newValue === '') {
scope.uifPercentComplete = 0;
return;
}
var newPercentComplete = parseFloat(newValue);
if (isNaN(newPercentComplete) || newPercentComplete < 0 || newPercentComplete > 100) {
ProgressIndicatorDirective.log.error('Error [ngOfficeUiFabric] officeuifabric.components.progressindicator - ' +
'Percent complete must be a valid number between 0 and 100.');
scope.uifPercentComplete = Math.max(Math.min(newPercentComplete, 100), 0);
}
});
};
;
return ProgressIndicatorDirective;
})();
exports.ProgressIndicatorDirective = ProgressIndicatorDirective;
exports.module = ng.module('officeuifabric.components.progressindicator', [
'officeuifabric.components'
])
.directive('uifProgressIndicator', ProgressIndicatorDirective.factory());
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var SearchBoxDirective = (function () {
function SearchBoxDirective() {
this.template = '<div class="ms-SearchBox" ng-class="{\'is-active\':isActive}">' +
'<input class="ms-SearchBox-field" ng-focus="inputFocus()" ng-blur="inputBlur()"' +
' ng-model="value" id="{{::\'searchBox_\'+$id}}" />' +
'<label class="ms-SearchBox-label" for="{{::\'searchBox_\'+$id}}" ng-hide="isLabelHidden">' +
'<i class="ms-SearchBox-icon ms-Icon ms-Icon--search" ></i> {{placeholder}}</label>' +
'<button class="ms-SearchBox-closeButton" ng-mousedown="btnMousedown()" type="button"><i class="ms-Icon ms-Icon--x"></i></button>' +
'</div>';
this.scope = {
placeholder: '=?',
value: '=?'
};
}
SearchBoxDirective.factory = function () {
var directive = function () { return new SearchBoxDirective(); };
return directive;
};
SearchBoxDirective.prototype.link = function (scope, elem, attrs) {
scope.isFocus = false;
scope.isCancel = false;
scope.isLabelHidden = false;
scope.isActive = false;
scope.inputFocus = function () {
scope.isFocus = true;
scope.isLabelHidden = true;
scope.isActive = true;
};
scope.inputBlur = function () {
if (scope.isCancel) {
scope.value = '';
scope.isLabelHidden = false;
}
scope.isActive = false;
if (typeof (scope.value) === 'undefined' || scope.value === '') {
scope.isLabelHidden = false;
}
scope.isFocus = scope.isCancel = false;
};
scope.btnMousedown = function () {
scope.isCancel = true;
};
scope.$watch('value', function (val) {
if (!scope.isFocus) {
if (val && val !== '') {
scope.isLabelHidden = true;
}
else {
scope.isLabelHidden = false;
}
scope.value = val;
}
});
scope.$watch('placeholder', function (search) {
scope.placeholder = search;
});
};
return SearchBoxDirective;
})();
exports.SearchBoxDirective = SearchBoxDirective;
exports.module = ng.module('officeuifabric.components.searchbox', ['officeuifabric.components'])
.directive('uifSearchbox', SearchBoxDirective.factory());
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var spinnerSizeEnum_1 = __webpack_require__(23);
var SpinnerDirective = (function () {
function SpinnerDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = true;
this.template = '<div class="ms-Spinner"></div>';
this.controller = SpinnerController;
this.scope = {
'ngShow': '=',
'uifSize': '@'
};
}
SpinnerDirective.factory = function () {
var directive = function () { return new SpinnerDirective(); };
return directive;
};
SpinnerDirective.prototype.link = function (scope, instanceElement, attrs, controller, $transclude) {
if (ng.isDefined(attrs.uifSize)) {
if (ng.isUndefined(spinnerSizeEnum_1.SpinnerSize[attrs.uifSize])) {
controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.spinner - Unsupported size: ' +
'Spinner size (\'' + attrs.uifSize + '\') is not supported by the Office UI Fabric.');
}
if (spinnerSizeEnum_1.SpinnerSize[attrs.uifSize] === spinnerSizeEnum_1.SpinnerSize.large) {
instanceElement.addClass('ms-Spinner--large');
}
}
if (attrs.ngShow != null) {
scope.$watch('ngShow', function (newVisible, oldVisible, spinnerScope) {
if (newVisible) {
spinnerScope.start();
}
else {
spinnerScope.stop();
}
});
}
else {
scope.start();
}
$transclude(function (clone) {
if (clone.length > 0) {
var wrapper = ng.element('<div></div>');
wrapper.addClass('ms-Spinner-label').append(clone);
instanceElement.append(wrapper);
}
});
scope.init();
};
return SpinnerDirective;
})();
exports.SpinnerDirective = SpinnerDirective;
var SpinnerController = (function () {
function SpinnerController($scope, $element, $interval, $log) {
var _this = this;
this.$scope = $scope;
this.$element = $element;
this.$interval = $interval;
this.$log = $log;
this._offsetSize = 0.179;
this._numCircles = 8;
this._animationSpeed = 90;
this._circles = [];
$scope.init = function () {
_this._parentSize = spinnerSizeEnum_1.SpinnerSize[_this.$scope.uifSize] === spinnerSizeEnum_1.SpinnerSize.large ? 28 : 20;
_this.createCirclesAndArrange();
_this.setInitialOpacity();
};
$scope.start = function () {
_this._animationInterval = $interval(function () {
var i = _this._circles.length;
while (i--) {
_this.fadeCircle(_this._circles[i]);
}
}, _this._animationSpeed);
};
$scope.stop = function () {
$interval.cancel(_this._animationInterval);
};
}
SpinnerController.prototype.createCirclesAndArrange = function () {
var angle = 0;
var offset = this._parentSize * this._offsetSize;
var step = (2 * Math.PI) / this._numCircles;
var i = this._numCircles;
var radius = (this._parentSize - offset) * 0.5;
while (i--) {
var circle = this.createCircle();
var x = Math.round(this._parentSize * 0.5 + radius * Math.cos(angle) - circle[0].clientWidth * 0.5) - offset * 0.5;
var y = Math.round(this._parentSize * 0.5 + radius * Math.sin(angle) - circle[0].clientHeight * 0.5) - offset * 0.5;
this.$element.append(circle);
circle.css('left', (x + 'px'));
circle.css('top', (y + 'px'));
angle += step;
var circleObject = new CircleObject(circle, i);
this._circles.push(circleObject);
}
};
SpinnerController.prototype.createCircle = function () {
var circle = ng.element('<div></div>');
var dotSize = (this._parentSize * this._offsetSize) + 'px';
circle.addClass('ms-Spinner-circle').css('width', dotSize).css('height', dotSize);
return circle;
};
;
SpinnerController.prototype.setInitialOpacity = function () {
var _this = this;
var opcaityToSet;
this._fadeIncrement = 1 / this._numCircles;
this._circles.forEach(function (circle, index) {
opcaityToSet = (_this._fadeIncrement * (index + 1));
circle.opacity = opcaityToSet;
});
};
SpinnerController.prototype.fadeCircle = function (circle) {
var newOpacity = circle.opacity - this._fadeIncrement;
if (newOpacity <= 0) {
newOpacity = 1;
}
circle.opacity = newOpacity;
};
SpinnerController.$inject = ['$scope', '$element', '$interval', '$log'];
return SpinnerController;
})();
var CircleObject = (function () {
function CircleObject(circleElement, circleIndex) {
this.circleElement = circleElement;
this.circleIndex = circleIndex;
}
Object.defineProperty(CircleObject.prototype, "opacity", {
get: function () {
return +(this.circleElement.css('opacity'));
},
set: function (opacity) {
this.circleElement.css('opacity', opacity);
},
enumerable: true,
configurable: true
});
return CircleObject;
})();
exports.module = ng.module('officeuifabric.components.spinner', ['officeuifabric.components'])
.directive('uifSpinner', SpinnerDirective.factory());
/***/ },
/* 23 */
/***/ function(module, exports) {
'use strict';
(function (SpinnerSize) {
SpinnerSize[SpinnerSize['small'] = 0] = 'small';
SpinnerSize[SpinnerSize['large'] = 1] = 'large';
})(exports.SpinnerSize || (exports.SpinnerSize = {}));
var SpinnerSize = exports.SpinnerSize;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var tableRowSelectModeEnum_1 = __webpack_require__(25);
var TableController = (function () {
function TableController($scope, $log) {
this.$scope = $scope;
this.$log = $log;
this.$scope.orderBy = null;
this.$scope.orderAsc = true;
this.$scope.rows = [];
}
Object.defineProperty(TableController.prototype, "orderBy", {
get: function () {
return this.$scope.orderBy;
},
set: function (property) {
this.$scope.orderBy = property;
this.$scope.$digest();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TableController.prototype, "orderAsc", {
get: function () {
return this.$scope.orderAsc;
},
set: function (orderAsc) {
this.$scope.orderAsc = orderAsc;
this.$scope.$digest();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TableController.prototype, "rowSelectMode", {
get: function () {
return this.$scope.rowSelectMode;
},
set: function (rowSelectMode) {
if (tableRowSelectModeEnum_1.TableRowSelectModeEnum[rowSelectMode] === undefined) {
this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' +
'\'' + rowSelectMode + '\' is not a valid option for \'uif-row-select-mode\'. ' +
'Valid options are none|single|multiple.');
}
this.$scope.rowSelectMode = rowSelectMode;
this.$scope.$digest();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TableController.prototype, "rows", {
get: function () {
return this.$scope.rows;
},
set: function (rows) {
this.$scope.rows = rows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TableController.prototype, "selectedItems", {
get: function () {
var selectedItems = [];
for (var i = 0; i < this.rows.length; i++) {
if (this.rows[i].selected === true) {
selectedItems.push(this.rows[i].item);
}
}
return selectedItems;
},
enumerable: true,
configurable: true
});
TableController.$inject = ['$scope', '$log'];
return TableController;
})();
var TableDirective = (function () {
function TableDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = true;
this.template = '<div class="ms-Table" ng-transclude></div>';
this.controller = TableController;
this.controllerAs = 'table';
}
TableDirective.factory = function () {
var directive = function () { return new TableDirective(); };
return directive;
};
TableDirective.prototype.link = function (scope, instanceElement, attrs, controller) {
if (attrs.uifRowSelectMode !== undefined && attrs.uifRowSelectMode !== null) {
if (tableRowSelectModeEnum_1.TableRowSelectModeEnum[attrs.uifRowSelectMode] === undefined) {
controller.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' +
'\'' + attrs.uifRowSelectMode + '\' is not a valid option for \'uif-row-select-mode\'. ' +
'Valid options are none|single|multiple.');
}
else {
scope.rowSelectMode = attrs.uifRowSelectMode;
}
}
if (scope.rowSelectMode === undefined) {
scope.rowSelectMode = tableRowSelectModeEnum_1.TableRowSelectModeEnum[tableRowSelectModeEnum_1.TableRowSelectModeEnum.none];
}
};
return TableDirective;
})();
exports.TableDirective = TableDirective;
var TableRowController = (function () {
function TableRowController($scope, $log) {
this.$scope = $scope;
this.$log = $log;
}
Object.defineProperty(TableRowController.prototype, "item", {
get: function () {
return this.$scope.item;
},
set: function (item) {
this.$scope.item = item;
this.$scope.$digest();
},
enumerable: true,
configurable: true
});
Object.defineProperty(TableRowController.prototype, "selected", {
get: function () {
return this.$scope.selected;
},
set: function (selected) {
this.$scope.selected = selected;
this.$scope.$digest();
},
enumerable: true,
configurable: true
});
TableRowController.$inject = ['$scope', '$log'];
return TableRowController;
})();
var TableRowDirective = (function () {
function TableRowDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = true;
this.template = '<div class="ms-Table-row" ng-transclude></div>';
this.require = '^uifTable';
this.scope = {
item: '=uifItem'
};
this.controller = TableRowController;
}
TableRowDirective.factory = function () {
var directive = function () { return new TableRowDirective(); };
return directive;
};
TableRowDirective.prototype.link = function (scope, instanceElement, attrs, table) {
if (attrs.uifSelected !== undefined &&
attrs.uifSelected !== null) {
var selectedString = attrs.uifSelected.toLowerCase();
if (selectedString !== 'true' && selectedString !== 'false') {
table.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.table. ' +
'\'' + attrs.uifSelected + '\' is not a valid boolean value. ' +
'Valid options are true|false.');
}
else {
if (selectedString === 'true') {
scope.selected = true;
}
}
}
if (scope.item !== undefined) {
table.rows.push(scope);
}
scope.rowClick = function (ev) {
scope.selected = !scope.selected;
scope.$apply();
};
scope.$watch('selected', function (newValue, oldValue, tableRowScope) {
if (newValue === true) {
if (table.rowSelectMode === tableRowSelectModeEnum_1.TableRowSelectModeEnum[tableRowSelectModeEnum_1.TableRowSelectModeEnum.single]) {
if (table.rows) {
for (var i = 0; i < table.rows.length; i++) {
if (table.rows[i] !== tableRowScope) {
table.rows[i].selected = false;
}
}
}
}
instanceElement.addClass('is-selected');
}
else {
instanceElement.removeClass('is-selected');
}
});
if (table.rowSelectMode !== tableRowSelectModeEnum_1.TableRowSelectModeEnum[tableRowSelectModeEnum_1.TableRowSelectModeEnum.none] &&
scope.item !== undefined) {
instanceElement.on('click', scope.rowClick);
}
if (table.rowSelectMode === tableRowSelectModeEnum_1.TableRowSelectModeEnum[tableRowSelectModeEnum_1.TableRowSelectModeEnum.none]) {
instanceElement.css('cursor', 'default');
}
};
return TableRowDirective;
})();
exports.TableRowDirective = TableRowDirective;
var TableRowSelectDirective = (function () {
function TableRowSelectDirective() {
this.restrict = 'E';
this.template = '<span class="ms-Table-rowCheck"></span>';
this.replace = true;
this.require = ['^uifTable', '^uifTableRow'];
}
TableRowSelectDirective.factory = function () {
var directive = function () { return new TableRowSelectDirective(); };
return directive;
};
TableRowSelectDirective.prototype.link = function (scope, instanceElement, attrs, controllers) {
scope.rowSelectClick = function (ev) {
var table = controllers[0];
var row = controllers[1];
if (table.rowSelectMode !== tableRowSelectModeEnum_1.TableRowSelectModeEnum[tableRowSelectModeEnum_1.TableRowSelectModeEnum.multiple]) {
return;
}
if (row.item === undefined || row.item === null) {
var shouldSelectAll = false;
for (var i = 0; i < table.rows.length; i++) {
if (table.rows[i].selected !== true) {
shouldSelectAll = true;
break;
}
}
for (var i = 0; i < table.rows.length; i++) {
if (table.rows[i].selected !== shouldSelectAll) {
table.rows[i].selected = shouldSelectAll;
}
}
scope.$apply();
}
};
instanceElement.on('click', scope.rowSelectClick);
};
return TableRowSelectDirective;
})();
exports.TableRowSelectDirective = TableRowSelectDirective;
var TableCellDirective = (function () {
function TableCellDirective() {
this.restrict = 'E';
this.transclude = true;
this.template = '<span class="ms-Table-cell" ng-transclude></span>';
this.replace = true;
}
TableCellDirective.factory = function () {
var directive = function () { return new TableCellDirective(); };
return directive;
};
return TableCellDirective;
})();
exports.TableCellDirective = TableCellDirective;
var TableHeaderDirective = (function () {
function TableHeaderDirective() {
this.restrict = 'E';
this.transclude = true;
this.replace = true;
this.template = '<span class="ms-Table-cell" ng-transclude></span>';
this.require = '^uifTable';
}
TableHeaderDirective.factory = function () {
var directive = function () { return new TableHeaderDirective(); };
return directive;
};
TableHeaderDirective.prototype.link = function (scope, instanceElement, attrs, table) {
scope.headerClick = function (ev) {
if (table.orderBy === attrs.uifOrderBy) {
table.orderAsc = !table.orderAsc;
}
else {
table.orderBy = attrs.uifOrderBy;
table.orderAsc = true;
}
};
scope.$watch('table.orderBy', function (newOrderBy, oldOrderBy, tableHeaderScope) {
if (oldOrderBy !== newOrderBy &&
newOrderBy === attrs.uifOrderBy) {
var cells = instanceElement.parent().children();
for (var i = 0; i < cells.length; i++) {
if (cells.eq(i).children().length === 2) {
cells.eq(i).children().eq(1).remove();
}
}
instanceElement.append('<span class="uif-sort-order"> \
<i class="ms-Icon ms-Icon--caretDown" aria-hidden="true"></i></span>');
}
});
scope.$watch('table.orderAsc', function (newOrderAsc, oldOrderAsc, tableHeaderScope) {
if (instanceElement.children().length === 2) {
var oldCssClass = oldOrderAsc ? 'ms-Icon--caretDown' : 'ms-Icon--caretUp';
var newCssClass = newOrderAsc ? 'ms-Icon--caretDown' : 'ms-Icon--caretUp';
instanceElement.children().eq(1).children().eq(0).removeClass(oldCssClass).addClass(newCssClass);
}
});
if ('uifOrderBy' in attrs) {
instanceElement.on('click', scope.headerClick);
}
};
return TableHeaderDirective;
})();
exports.TableHeaderDirective = TableHeaderDirective;
exports.module = ng.module('officeuifabric.components.table', ['officeuifabric.components'])
.directive('uifTable', TableDirective.factory())
.directive('uifTableRow', TableRowDirective.factory())
.directive('uifTableRowSelect', TableRowSelectDirective.factory())
.directive('uifTableCell', TableCellDirective.factory())
.directive('uifTableHeader', TableHeaderDirective.factory());
/***/ },
/* 25 */
/***/ function(module, exports) {
'use strict';
(function (TableRowSelectModeEnum) {
TableRowSelectModeEnum[TableRowSelectModeEnum["none"] = 0] = "none";
TableRowSelectModeEnum[TableRowSelectModeEnum["single"] = 1] = "single";
TableRowSelectModeEnum[TableRowSelectModeEnum["multiple"] = 2] = "multiple";
})(exports.TableRowSelectModeEnum || (exports.TableRowSelectModeEnum = {}));
var TableRowSelectModeEnum = exports.TableRowSelectModeEnum;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var TextFieldDirective = (function () {
function TextFieldDirective() {
this.template = '<div ng-class="{\'is-active\': isActive, \'ms-TextField\': true, ' +
'\'ms-TextField--underlined\': uifUnderlined, \'ms-TextField--placeholder\': placeholder}">' +
'<label ng-show="labelShown" class="ms-Label">{{uifLabel || placeholder}}</label>' +
'<input ng-model="ngModel" ng-blur="inputBlur()" ng-focus="inputFocus()" ng-click="inputClick()" class="ms-TextField-field" />' +
'<span class="ms-TextField-description">{{uifDescription}}</span>' +
'</div>';
this.scope = {
ngModel: '=',
placeholder: '@',
uifDescription: '@',
uifLabel: '@'
};
this.require = '?ngModel';
this.restrict = 'E';
}
TextFieldDirective.factory = function () {
var directive = function () { return new TextFieldDirective(); };
return directive;
};
TextFieldDirective.prototype.link = function (scope, instanceElement, attrs, ngModel) {
scope.labelShown = true;
scope.uifUnderlined = 'uifUnderlined' in attrs;
scope.inputFocus = function (ev) {
if (scope.uifUnderlined) {
scope.isActive = true;
}
};
scope.inputClick = function (ev) {
if (scope.placeholder) {
scope.labelShown = false;
}
};
scope.inputBlur = function (ev) {
var input = instanceElement.find('input');
if (scope.placeholder && input.val().length === 0) {
scope.labelShown = true;
}
if (scope.uifUnderlined) {
scope.isActive = false;
}
};
if (ngModel != null) {
ngModel.$render = function () {
scope.labelShown = !ngModel.$viewValue;
};
}
};
return TextFieldDirective;
})();
exports.TextFieldDirective = TextFieldDirective;
exports.module = ng.module('officeuifabric.components.textfield', [
'officeuifabric.components'
])
.directive('uifTextfield', TextFieldDirective.factory());
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ng = __webpack_require__(2);
var ToggleDirective = (function () {
function ToggleDirective() {
this.template = '<div ng-class="toggleClass">' +
'<span class="ms-Toggle-description"><ng-transclude/></span>' +
'<input type="checkbox" id="{{::$id}}" class="ms-Toggle-input" ng-model="ngModel" />' +
'<label for="{{::$id}}" class="ms-Toggle-field">' +
'<span class="ms-Label ms-Label--off">{{uifLabelOff}}</span>' +
'<span class="ms-Label ms-Label--on">{{uifLabelOn}}</span>' +
'</label>' +
'</div>';
this.restrict = 'E';
this.transclude = true;
this.scope = {
ngModel: '=?',
uifLabelOff: '@',
uifLabelOn: '@',
uifTextLocation: '@'
};
}
ToggleDirective.factory = function () {
var directive = function () { return new ToggleDirective(); };
return directive;
};
ToggleDirective.prototype.link = function (scope, elem, attrs) {
scope.toggleClass = 'ms-Toggle';
if (scope.uifTextLocation) {
var loc = scope.uifTextLocation;
loc = loc.charAt(0).toUpperCase() + loc.slice(1);
scope.toggleClass += ' ms-Toggle--text' + loc;
}
};
return ToggleDirective;
})();
exports.ToggleDirective = ToggleDirective;
exports.module = ng.module('officeuifabric.components.toggle', [
'officeuifabric.components'
])
.directive('uifToggle', ToggleDirective.factory());
/***/ }
/******/ ])
});
;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uIiwid2VicGFjazovLy93ZWJwYWNrL2Jvb3RzdHJhcCAwNjg3YWU4ODY0MjNmNzc5MTM4MyIsIndlYnBhY2s6Ly8vLi9zcmMvY29yZS9jb3JlLnRzIiwid2VicGFjazovLy9leHRlcm5hbCBcImFuZ3VsYXJcIiIsIndlYnBhY2s6Ly8vLi9zcmMvY29yZS9jb21wb25lbnRzLnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL2NhbGxvdXQvY2FsbG91dERpcmVjdGl2ZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9jYWxsb3V0L2NhbGxvdXRUeXBlRW51bS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9jYWxsb3V0L2NhbGxvdXRBcnJvd0VudW0udHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvYnV0dG9uL2J1dHRvbkRpcmVjdGl2ZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9idXR0b24vYnV0dG9uVHlwZUVudW0udHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvYnV0dG9uL2J1dHRvblRlbXBsYXRlVHlwZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9jaG9pY2VmaWVsZC9jaG9pY2VmaWVsZERpcmVjdGl2ZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9jaG9pY2VmaWVsZC9jaG9pY2VmaWVsZFR5cGVFbnVtLnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL2NvbnRleHR1YWxtZW51L2NvbnRleHR1YWxNZW51LnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL2Ryb3Bkb3duL2Ryb3Bkb3duRGlyZWN0aXZlLnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL2ljb24vaWNvbkRpcmVjdGl2ZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9pY29uL2ljb25FbnVtLnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL2xhYmVsL2xhYmVsRGlyZWN0aXZlLnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL2xpbmsvbGlua0RpcmVjdGl2ZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9vdmVybGF5L292ZXJsYXlEaXJlY3RpdmUudHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvb3ZlcmxheS9vdmVybGF5TW9kZUVudW0udHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvcHJvZ3Jlc3NpbmRpY2F0b3IvcHJvZ3Jlc3NJbmRpY2F0b3JEaXJlY3RpdmUudHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvc2VhcmNoYm94L3NlYXJjaGJveERpcmVjdGl2ZS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy9zcGlubmVyL3NwaW5uZXJEaXJlY3RpdmUudHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvc3Bpbm5lci9zcGlubmVyU2l6ZUVudW0udHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvdGFibGUvdGFibGVEaXJlY3RpdmUudHMiLCJ3ZWJwYWNrOi8vLy4vc3JjL2NvbXBvbmVudHMvdGFibGUvdGFibGVSb3dTZWxlY3RNb2RlRW51bS50cyIsIndlYnBhY2s6Ly8vLi9zcmMvY29tcG9uZW50cy90ZXh0ZmllbGQvdGV4dEZpZWxkRGlyZWN0aXZlLnRzIiwid2VicGFjazovLy8uL3NyYy9jb21wb25lbnRzL3RvZ2dsZS90b2dnbGVEaXJlY3RpdmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLENBQUM7QUFDRCxPO0FDVkE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0EsdUJBQWU7QUFDZjtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTs7O0FBR0E7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7Ozs7Ozs7Ozs7Ozs7O0FDdENBO0FBQ0E7QUFDQTs7Ozs7OztBQ0ZBLGdEOzs7Ozs7QUNBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQ2pDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLHFDQUFxQztBQUMxRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHNDQUFxQyxzQ0FBc0M7QUFDM0U7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBcUMsc0NBQXNDO0FBQzNFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDBDQUF5QyxxQ0FBcUM7QUFDOUU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDRDQUEyQyxnQ0FBZ0M7QUFDM0U7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsY0FBYTtBQUNiO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvRUFBbUUsZ0JBQWdCO0FBQ25GLHlCQUF3QjtBQUN4QiwyRkFBMEY7QUFDMUY7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLCtCQUErQjtBQUNwRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGNBQWE7QUFDYjtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQ3BMQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUMsa0RBQWtEO0FBQ25EOzs7Ozs7O0FDTEE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQyxvREFBb0Q7QUFDckQ7Ozs7Ozs7QUNQQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMENBQXlDLGtDQUFrQztBQUMzRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQ0FBbUMsa0JBQWtCO0FBQ3JEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esb0NBQW1DLGtCQUFrQjtBQUNyRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxvQ0FBbUMsa0JBQWtCO0FBQ3JEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQSxzREFBcUQsd0JBQXdCO0FBQzdFO0FBQ0EsaURBQWdELHdCQUF3QjtBQUN4RTtBQUNBLHlFQUF3RSx3QkFBd0I7QUFDaEc7QUFDQSxvRUFBbUUsd0JBQXdCO0FBQzNGO0FBQ0EseUVBQXdFLHdCQUF3QjtBQUNoRztBQUNBLG9FQUFtRSx3QkFBd0I7QUFDM0Y7QUFDQSwwRUFBeUUsd0JBQXdCO0FBQ2pHO0FBQ0EscUVBQW9FLHdCQUF3QjtBQUM1RjtBQUNBLHNFQUFxRSx3QkFBd0I7QUFDN0Y7QUFDQSxpRUFBZ0Usd0JBQXdCO0FBQ3hGO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHNDQUFxQyx5Q0FBeUM7QUFDOUU7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQ25MQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDLHdEQUF3RDtBQUN6RDtBQUNBOzs7Ozs7O0FDUkE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQyxnRUFBZ0U7QUFDakU7QUFDQTs7Ozs7OztBQ2RBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBLDJCQUEwQixPQUFPLHVDQUF1QyxTQUFTLFdBQVcsT0FBTztBQUNuRyxrREFBaUQsYUFBYSxvQkFBb0IsY0FBYztBQUNoRyw0QkFBMkIsT0FBTztBQUNsQztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxjQUFhO0FBQ2I7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxjQUFhO0FBQ2IsVUFBUztBQUNUO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHdCQUF1QiwyQkFBMkI7QUFDbEQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBcUMsd0NBQXdDO0FBQzdFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNyS0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDLDBEQUEwRDtBQUMzRDtBQUNBOzs7Ozs7O0FDTkE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUMsc0NBQXNDO0FBQ3ZDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHNLQUFxSyxxREFBcUQsb0NBQW9DLE1BQU07QUFDcFE7QUFDQSxxSEFBb0gscURBQXFELHFEQUFxRCxNQUFNO0FBQ3BPLDJIQUEwSCxNQUFNO0FBQ2hJO0FBQ0E7QUFDQTtBQUNBLDBDQUF5Qyw4Q0FBOEM7QUFDdkY7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHNDQUFxQyxzQ0FBc0M7QUFDM0U7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQ2hOQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLHNDQUFzQztBQUMzRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxjQUFhO0FBQ2IsVUFBUztBQUNUO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBLGdDQUErQixvQkFBb0I7QUFDbkQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0EseUJBQXdCLHVFQUF1RTtBQUMvRjtBQUNBLGdEQUErQyxlQUFlO0FBQzlEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLGdDQUFnQztBQUNyRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOzs7Ozs7O0FDOUdBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQSx1REFBc0QsU0FBUztBQUMvRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLDRCQUE0QjtBQUNqRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQzFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDLDRDQUE0QztBQUM3QztBQUNBOzs7Ozs7O0FDeFZBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBcUMsNkJBQTZCO0FBQ2xFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBOzs7Ozs7O0FDMUJBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSx3Q0FBdUMsVUFBVTtBQUNqRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHNDQUFxQyw0QkFBNEI7QUFDakU7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUN0QkE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNkRBQTRELDBDQUEwQztBQUN0RztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHlDQUF3QyxrQ0FBa0M7QUFDMUU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7Ozs7OztBQzNDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUMsa0RBQWtEO0FBQ25EOzs7Ozs7O0FDTEE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwyREFBMEQsU0FBUztBQUNuRTtBQUNBO0FBQ0EsdUVBQXNFLGdDQUFnQztBQUN0RztBQUNBLGtFQUFpRSxnQkFBZ0I7QUFDakY7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EseUNBQXdDLDRDQUE0QztBQUNwRjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUMvQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwrREFBOEQsdUJBQXVCO0FBQ3JGO0FBQ0Esc0NBQXFDLHNCQUFzQjtBQUMzRCx1REFBc0Qsc0JBQXNCO0FBQzVFLDJFQUEwRSxhQUFhO0FBQ3ZGO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBcUMsaUNBQWlDO0FBQ3RFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBOzs7Ozs7O0FDL0RBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLCtCQUErQjtBQUNwRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsY0FBYTtBQUNiO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsY0FBYTtBQUNiO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0EsRUFBQztBQUNEO0FBQ0E7Ozs7Ozs7QUNoSkE7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDLGtEQUFrRDtBQUNuRDs7Ozs7OztBQ0xBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQSxNQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0E7QUFDQSw0QkFBMkIsc0JBQXNCO0FBQ2pEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLDZCQUE2QjtBQUNsRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0EsTUFBSztBQUNMO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBLE1BQUs7QUFDTDtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLGdDQUFnQztBQUNyRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHdDQUF1Qyx1QkFBdUI7QUFDOUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFVBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLHNDQUFzQztBQUMzRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0NBQStCLHVCQUF1QjtBQUN0RDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0NBQStCLHVCQUF1QjtBQUN0RDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBcUMsaUNBQWlDO0FBQ3RFO0FBQ0E7QUFDQTtBQUNBLEVBQUM7QUFDRDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHNDQUFxQyxtQ0FBbUM7QUFDeEU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxnQ0FBK0Isa0JBQWtCO0FBQ2pEO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNEVBQTJFO0FBQzNFO0FBQ0E7QUFDQSxVQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsVUFBUztBQUNUO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxFQUFDO0FBQ0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUNyVEE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEVBQUMsd0VBQXdFO0FBQ3pFOzs7Ozs7O0FDTkE7QUFDQTtBQUNBO0FBQ0E7QUFDQSwwQ0FBeUM7QUFDekMsc0dBQXFHO0FBQ3JHLDZEQUE0RCx5QkFBeUI7QUFDckY7QUFDQSx1REFBc0QsZ0JBQWdCO0FBQ3RFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBcUMsaUNBQWlDO0FBQ3RFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Ozs7Ozs7QUN6REE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMkNBQTBDLE9BQU87QUFDakQsNEJBQTJCLE9BQU87QUFDbEMscURBQW9ELGFBQWE7QUFDakUsb0RBQW1ELFlBQVk7QUFDL0Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esc0NBQXFDLDhCQUE4QjtBQUNuRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsRUFBQztBQUNEO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoibmdPZmZpY2VVaUZhYnJpYy5qcyIsInNvdXJjZXNDb250ZW50IjpbIihmdW5jdGlvbiB3ZWJwYWNrVW5pdmVyc2FsTW9kdWxlRGVmaW5pdGlvbihyb290LCBmYWN0b3J5KSB7XG5cdGlmKHR5cGVvZiBleHBvcnRzID09PSAnb2JqZWN0JyAmJiB0eXBlb2YgbW9kdWxlID09PSAnb2JqZWN0Jylcblx0XHRtb2R1bGUuZXhwb3J0cyA9IGZhY3RvcnkocmVxdWlyZShcImFuZ3VsYXJcIikpO1xuXHRlbHNlIGlmKHR5cGVvZiBkZWZpbmUgPT09ICdmdW5jdGlvbicgJiYgZGVmaW5lLmFtZClcblx0XHRkZWZpbmUoW1wiYW5ndWxhclwiXSwgZmFjdG9yeSk7XG5cdGVsc2Uge1xuXHRcdHZhciBhID0gdHlwZW9mIGV4cG9ydHMgPT09ICdvYmplY3QnID8gZmFjdG9yeShyZXF1aXJlKFwiYW5ndWxhclwiKSkgOiBmYWN0b3J5KHJvb3RbXCJhbmd1bGFyXCJdKTtcblx0XHRmb3IodmFyIGkgaW4gYSkgKHR5cGVvZiBleHBvcnRzID09PSAnb2JqZWN0JyA/IGV4cG9ydHMgOiByb290KVtpXSA9IGFbaV07XG5cdH1cbn0pKHRoaXMsIGZ1bmN0aW9uKF9fV0VCUEFDS19FWFRFUk5BTF9NT0RVTEVfMl9fKSB7XG5yZXR1cm4gXG5cblxuLyoqIFdFQlBBQ0sgRk9PVEVSICoqXG4gKiogd2VicGFjay91bml2ZXJzYWxNb2R1bGVEZWZpbml0aW9uXG4gKiovIiwiIFx0Ly8gVGhlIG1vZHVsZSBjYWNoZVxuIFx0dmFyIGluc3RhbGxlZE1vZHVsZXMgPSB7fTtcblxuIFx0Ly8gVGhlIHJlcXVpcmUgZnVuY3Rpb25cbiBcdGZ1bmN0aW9uIF9fd2VicGFja19yZXF1aXJlX18obW9kdWxlSWQpIHtcblxuIFx0XHQvLyBDaGVjayBpZiBtb2R1bGUgaXMgaW4gY2FjaGVcbiBcdFx0aWYoaW5zdGFsbGVkTW9kdWxlc1ttb2R1bGVJZF0pXG4gXHRcdFx0cmV0dXJuIGluc3RhbGxlZE1vZHVsZXNbbW9kdWxlSWRdLmV4cG9ydHM7XG5cbiBcdFx0Ly8gQ3JlYXRlIGEgbmV3IG1vZHVsZSAoYW5kIHB1dCBpdCBpbnRvIHRoZSBjYWNoZSlcbiBcdFx0dmFyIG1vZHVsZSA9IGluc3RhbGxlZE1vZHVsZXNbbW9kdWxlSWRdID0ge1xuIFx0XHRcdGV4cG9ydHM6IHt9LFxuIFx0XHRcdGlkOiBtb2R1bGVJZCxcbiBcdFx0XHRsb2FkZWQ6IGZhbHNlXG4gXHRcdH07XG5cbiBcdFx0Ly8gRXhlY3V0ZSB0aGUgbW9kdWxlIGZ1bmN0aW9uXG4gXHRcdG1vZHVsZXNbbW9kdWxlSWRdLmNhbGwobW9kdWxlLmV4cG9ydHMsIG1vZHVsZSwgbW9kdWxlLmV4cG9ydHMsIF9fd2VicGFja19yZXF1aXJlX18pO1xuXG4gXHRcdC8vIEZsYWcgdGhlIG1vZHVsZSBhcyBsb2FkZWRcbiBcdFx0bW9kdWxlLmxvYWRlZCA9IHRydWU7XG5cbiBcdFx0Ly8gUmV0dXJuIHRoZSBleHBvcnRzIG9mIHRoZSBtb2R1bGVcbiBcdFx0cmV0dXJuIG1vZHVsZS5leHBvcnRzO1xuIFx0fVxuXG5cbiBcdC8vIGV4cG9zZSB0aGUgbW9kdWxlcyBvYmplY3QgKF9fd2VicGFja19tb2R1bGVzX18pXG4gXHRfX3dlYnBhY2tfcmVxdWlyZV9fLm0gPSBtb2R1bGVzO1xuXG4gXHQvLyBleHBvc2UgdGhlIG1vZHVsZSBjYWNoZVxuIFx0X193ZWJwYWNrX3JlcXVpcmVfXy5jID0gaW5zdGFsbGVkTW9kdWxlcztcblxuIFx0Ly8gX193ZWJwYWNrX3B1YmxpY19wYXRoX19cbiBcdF9fd2VicGFja19yZXF1aXJlX18ucCA9IFwiXCI7XG5cbiBcdC8vIExvYWQgZW50cnkgbW9kdWxlIGFuZCByZXR1cm4gZXhwb3J0c1xuIFx0cmV0dXJuIF9fd2VicGFja19yZXF1aXJlX18oMCk7XG5cblxuXG4vKiogV0VCUEFDSyBGT09URVIgKipcbiAqKiB3ZWJwYWNrL2Jvb3RzdHJhcCAwNjg3YWU4ODY0MjNmNzc5MTM4M1xuICoqLyIsIid1c2Ugc3RyaWN0JztcbnZhciBuZyA9IHJlcXVpcmUoJ2FuZ3VsYXInKTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb3JlJywgW10pO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb3JlL2NvcmUudHNcbiAqKiBtb2R1bGUgaWQgPSAxXG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCJtb2R1bGUuZXhwb3J0cyA9IF9fV0VCUEFDS19FWFRFUk5BTF9NT0RVTEVfMl9fO1xuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogZXh0ZXJuYWwgXCJhbmd1bGFyXCJcbiAqKiBtb2R1bGUgaWQgPSAyXG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgY2FsbG91dE1vZHVsZSA9IHJlcXVpcmUoJy4uL2NvbXBvbmVudHMvY2FsbG91dC9jYWxsb3V0RGlyZWN0aXZlJyk7XG52YXIgYnV0dG9uTW9kdWxlID0gcmVxdWlyZSgnLi4vY29tcG9uZW50cy9idXR0b24vYnV0dG9uRGlyZWN0aXZlJyk7XG52YXIgY2hvaWNlZmllbGRNb2R1bGUgPSByZXF1aXJlKCcuLi9jb21wb25lbnRzL2Nob2ljZWZpZWxkL2Nob2ljZWZpZWxkRGlyZWN0aXZlJyk7XG52YXIgY29udGV4dHVhbE1lbnVNb2R1bGUgPSByZXF1aXJlKCcuLi9jb21wb25lbnRzL2NvbnRleHR1YWxtZW51L2NvbnRleHR1YWxNZW51Jyk7XG52YXIgZHJvcGRvd25Nb2R1bGUgPSByZXF1aXJlKCcuLi9jb21wb25lbnRzL2Ryb3Bkb3duL2Ryb3Bkb3duRGlyZWN0aXZlJyk7XG52YXIgaWNvbk1vZHVsZSA9IHJlcXVpcmUoJy4uL2NvbXBvbmVudHMvaWNvbi9pY29uRGlyZWN0aXZlJyk7XG52YXIgbGFiZWxNb2R1bGUgPSByZXF1aXJlKCcuLi9jb21wb25lbnRzL2xhYmVsL2xhYmVsRGlyZWN0aXZlJyk7XG52YXIgbGlua01vZHVsZSA9IHJlcXVpcmUoJy4uL2NvbXBvbmVudHMvbGluay9saW5rRGlyZWN0aXZlJyk7XG52YXIgb3ZlcmxheU1vZHVsZSA9IHJlcXVpcmUoJy4uL2NvbXBvbmVudHMvb3ZlcmxheS9vdmVybGF5RGlyZWN0aXZlJyk7XG52YXIgcHJvZ3Jlc3NJbmRpY2F0b3JNb2R1bGUgPSByZXF1aXJlKCcuLi9jb21wb25lbnRzL3Byb2dyZXNzaW5kaWNhdG9yL3Byb2dyZXNzSW5kaWNhdG9yRGlyZWN0aXZlJyk7XG52YXIgc2VhcmNoYm94TW9kdWxlID0gcmVxdWlyZSgnLi4vY29tcG9uZW50cy9zZWFyY2hib3gvc2VhcmNoYm94RGlyZWN0aXZlJyk7XG52YXIgc3Bpbm5lck1vZHVsZSA9IHJlcXVpcmUoJy4uL2NvbXBvbmVudHMvc3Bpbm5lci9zcGlubmVyRGlyZWN0aXZlJyk7XG52YXIgdGFibGVNb2R1bGUgPSByZXF1aXJlKCcuLi9jb21wb25lbnRzL3RhYmxlL3RhYmxlRGlyZWN0aXZlJyk7XG52YXIgdGV4dEZpZWxkTW9kdWxlID0gcmVxdWlyZSgnLi4vY29tcG9uZW50cy90ZXh0ZmllbGQvdGV4dEZpZWxkRGlyZWN0aXZlJyk7XG52YXIgdG9nZ2xlTW9kdWxlID0gcmVxdWlyZSgnLi4vY29tcG9uZW50cy90b2dnbGUvdG9nZ2xlRGlyZWN0aXZlJyk7XG5leHBvcnRzLm1vZHVsZSA9IG5nLm1vZHVsZSgnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cycsIFtcbiAgICBjYWxsb3V0TW9kdWxlLm1vZHVsZS5uYW1lLFxuICAgIGJ1dHRvbk1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICBjaG9pY2VmaWVsZE1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICBjb250ZXh0dWFsTWVudU1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICBkcm9wZG93bk1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICBpY29uTW9kdWxlLm1vZHVsZS5uYW1lLFxuICAgIGxhYmVsTW9kdWxlLm1vZHVsZS5uYW1lLFxuICAgIGxpbmtNb2R1bGUubW9kdWxlLm5hbWUsXG4gICAgb3ZlcmxheU1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICBwcm9ncmVzc0luZGljYXRvck1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICBzZWFyY2hib3hNb2R1bGUubW9kdWxlLm5hbWUsXG4gICAgc3Bpbm5lck1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICB0YWJsZU1vZHVsZS5tb2R1bGUubmFtZSxcbiAgICB0ZXh0RmllbGRNb2R1bGUubW9kdWxlLm5hbWUsXG4gICAgdG9nZ2xlTW9kdWxlLm1vZHVsZS5uYW1lXG5dKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29yZS9jb21wb25lbnRzLnRzXG4gKiogbW9kdWxlIGlkID0gM1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xudmFyIG5nID0gcmVxdWlyZSgnYW5ndWxhcicpO1xudmFyIGNhbGxvdXRUeXBlRW51bV8xID0gcmVxdWlyZSgnLi9jYWxsb3V0VHlwZUVudW0nKTtcbnZhciBjYWxsb3V0QXJyb3dFbnVtXzEgPSByZXF1aXJlKCcuL2NhbGxvdXRBcnJvd0VudW0nKTtcbnZhciBDYWxsb3V0Q29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ2FsbG91dENvbnRyb2xsZXIoJHNjb3BlLCAkbG9nKSB7XG4gICAgICAgIHRoaXMuJHNjb3BlID0gJHNjb3BlO1xuICAgICAgICB0aGlzLiRsb2cgPSAkbG9nO1xuICAgIH1cbiAgICBDYWxsb3V0Q29udHJvbGxlci4kaW5qZWN0ID0gWyckc2NvcGUnLCAnJGxvZyddO1xuICAgIHJldHVybiBDYWxsb3V0Q29udHJvbGxlcjtcbn0pKCk7XG5leHBvcnRzLkNhbGxvdXRDb250cm9sbGVyID0gQ2FsbG91dENvbnRyb2xsZXI7XG52YXIgQ2FsbG91dEhlYWRlckRpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ2FsbG91dEhlYWRlckRpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gZmFsc2U7XG4gICAgICAgIHRoaXMuc2NvcGUgPSBmYWxzZTtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IGNsYXNzPVwibXMtQ2FsbG91dC1oZWFkZXJcIj48cCBjbGFzcz1cIm1zLUNhbGxvdXQtdGl0bGVcIiBuZy10cmFuc2NsdWRlPjwvcD48L2Rpdj4nO1xuICAgIH1cbiAgICBDYWxsb3V0SGVhZGVyRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgQ2FsbG91dEhlYWRlckRpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgQ2FsbG91dEhlYWRlckRpcmVjdGl2ZS5wcm90b3R5cGUubGluayA9IGZ1bmN0aW9uIChzY29wZSwgaW5zdGFuY2VFbGVtZW50LCBhdHRycywgY3RybHMpIHtcbiAgICAgICAgdmFyIG1haW5XcmFwcGVyID0gaW5zdGFuY2VFbGVtZW50LnBhcmVudCgpLnBhcmVudCgpO1xuICAgICAgICBpZiAoIW5nLmlzVW5kZWZpbmVkKG1haW5XcmFwcGVyKSAmJiBtYWluV3JhcHBlci5oYXNDbGFzcygnbXMtQ2FsbG91dC1tYWluJykpIHtcbiAgICAgICAgICAgIHZhciBkZXRhY2hlZEhlYWRlciA9IGluc3RhbmNlRWxlbWVudC5kZXRhY2goKTtcbiAgICAgICAgICAgIG1haW5XcmFwcGVyLnByZXBlbmQoZGV0YWNoZWRIZWFkZXIpO1xuICAgICAgICB9XG4gICAgfTtcbiAgICByZXR1cm4gQ2FsbG91dEhlYWRlckRpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLkNhbGxvdXRIZWFkZXJEaXJlY3RpdmUgPSBDYWxsb3V0SGVhZGVyRGlyZWN0aXZlO1xudmFyIENhbGxvdXRDb250ZW50RGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBDYWxsb3V0Q29udGVudERpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gZmFsc2U7XG4gICAgICAgIHRoaXMuc2NvcGUgPSBmYWxzZTtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IGNsYXNzPVwibXMtQ2FsbG91dC1jb250ZW50XCI+PHAgY2xhc3M9XCJtcy1DYWxsb3V0LXN1YlRleHRcIiBuZy10cmFuc2NsdWRlPjwvcD48L2Rpdj4nO1xuICAgIH1cbiAgICBDYWxsb3V0Q29udGVudERpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IENhbGxvdXRDb250ZW50RGlyZWN0aXZlKCk7IH07XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICByZXR1cm4gQ2FsbG91dENvbnRlbnREaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5DYWxsb3V0Q29udGVudERpcmVjdGl2ZSA9IENhbGxvdXRDb250ZW50RGlyZWN0aXZlO1xudmFyIENhbGxvdXRBY3Rpb25zRGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBDYWxsb3V0QWN0aW9uc0RpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gZmFsc2U7XG4gICAgICAgIHRoaXMuc2NvcGUgPSBmYWxzZTtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IGNsYXNzPVwibXMtQ2FsbG91dC1hY3Rpb25zXCIgbmctdHJhbnNjbHVkZT48L2Rpdj4nO1xuICAgICAgICB0aGlzLnJlcXVpcmUgPSAnXj91aWZDYWxsb3V0JztcbiAgICB9XG4gICAgQ2FsbG91dEFjdGlvbnNEaXJlY3RpdmUuZmFjdG9yeSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgdmFyIGRpcmVjdGl2ZSA9IGZ1bmN0aW9uICgpIHsgcmV0dXJuIG5ldyBDYWxsb3V0QWN0aW9uc0RpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgQ2FsbG91dEFjdGlvbnNEaXJlY3RpdmUucHJvdG90eXBlLmxpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGluc3RhbmNlRWxlbWVudCwgYXR0cnMsIGNhbGxvdXRDb250cm9sbGVyKSB7XG4gICAgICAgIGlmIChuZy5pc09iamVjdChjYWxsb3V0Q29udHJvbGxlcikpIHtcbiAgICAgICAgICAgIGNhbGxvdXRDb250cm9sbGVyLiRzY29wZS4kd2F0Y2goJ2hhc1NlcGFyYXRvcicsIGZ1bmN0aW9uIChoYXNTZXBhcmF0b3IpIHtcbiAgICAgICAgICAgICAgICB2YXIgYWN0aW9uQ2hpbGRyZW4gPSBpbnN0YW5jZUVsZW1lbnQuY2hpbGRyZW4oKS5lcSgwKS5jaGlsZHJlbigpO1xuICAgICAgICAgICAgICAgIGZvciAodmFyIGJ1dHRvbkluZGV4ID0gMDsgYnV0dG9uSW5kZXggPCBhY3Rpb25DaGlsZHJlbi5sZW5ndGg7IGJ1dHRvbkluZGV4KyspIHtcbiAgICAgICAgICAgICAgICAgICAgdmFyIGFjdGlvbiA9IGFjdGlvbkNoaWxkcmVuLmVxKGJ1dHRvbkluZGV4KTtcbiAgICAgICAgICAgICAgICAgICAgaWYgKGhhc1NlcGFyYXRvcikge1xuICAgICAgICAgICAgICAgICAgICAgICAgYWN0aW9uLmFkZENsYXNzKCdtcy1DYWxsb3V0LWFjdGlvbicpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICAgICAgYWN0aW9uLnJlbW92ZUNsYXNzKCdtcy1DYWxsb3V0LWFjdGlvbicpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIHZhciBhY3Rpb25TcGFucyA9IGFjdGlvbi5maW5kKCdzcGFuJyk7XG4gICAgICAgICAgICAgICAgICAgIGZvciAodmFyIHNwYW5JbmRleCA9IDA7IHNwYW5JbmRleCA8IGFjdGlvblNwYW5zLmxlbmd0aDsgc3BhbkluZGV4KyspIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHZhciBhY3Rpb25TcGFuID0gYWN0aW9uU3BhbnMuZXEoc3BhbkluZGV4KTtcbiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChoYXNTZXBhcmF0b3IpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBhY3Rpb25TcGFuLmFkZENsYXNzKCdtcy1DYWxsb3V0LWFjdGlvblRleHQnKTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFjdGlvblNwYW4ucmVtb3ZlQ2xhc3MoJ21zLUNhbGxvdXQtYWN0aW9uVGV4dCcpO1xuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSk7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIHJldHVybiBDYWxsb3V0QWN0aW9uc0RpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLkNhbGxvdXRBY3Rpb25zRGlyZWN0aXZlID0gQ2FsbG91dEFjdGlvbnNEaXJlY3RpdmU7XG52YXIgQ2FsbG91dERpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ2FsbG91dERpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gZmFsc2U7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPGRpdiBjbGFzcz1cIm1zLUNhbGxvdXQgbXMtQ2FsbG91dC0tYXJyb3d7e2Fycm93RGlyZWN0aW9ufX1cIiAnICtcbiAgICAgICAgICAgICduZy1jbGFzcz1cIntcXCdtcy1DYWxsb3V0LS1hY3Rpb25UZXh0XFwnOiBoYXNTZXBhcmF0b3IsIFxcJ21zLUNhbGxvdXQtLU9PQkVcXCc6IHVpZlR5cGU9PVxcJ29vYmVcXCcsJyArXG4gICAgICAgICAgICAnIFxcJ21zLUNhbGxvdXQtLVBlZWtcXCc6IHVpZlR5cGU9PVxcJ3BlZWtcXCcsIFxcJ21zLUNhbGxvdXQtLWNsb3NlXFwnOiBjbG9zZUJ1dHRvbn1cIj4nICtcbiAgICAgICAgICAgICc8ZGl2IGNsYXNzPVwibXMtQ2FsbG91dC1tYWluXCI+PGRpdiBjbGFzcz1cIm1zLUNhbGxvdXQtaW5uZXJcIiBuZy10cmFuc2NsdWRlPjwvZGl2PjwvZGl2PjwvZGl2Pic7XG4gICAgICAgIHRoaXMucmVxdWlyZSA9IFsndWlmQ2FsbG91dCddO1xuICAgICAgICB0aGlzLnNjb3BlID0ge1xuICAgICAgICAgICAgbmdTaG93OiAnPT8nLFxuICAgICAgICAgICAgdWlmVHlwZTogJ0AnXG4gICAgICAgIH07XG4gICAgICAgIHRoaXMuY29udHJvbGxlciA9IENhbGxvdXRDb250cm9sbGVyO1xuICAgIH1cbiAgICBDYWxsb3V0RGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgQ2FsbG91dERpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgQ2FsbG91dERpcmVjdGl2ZS5wcm90b3R5cGUubGluayA9IGZ1bmN0aW9uIChzY29wZSwgaW5zdGFuY2VFbGVtZW50LCBhdHRycywgY3RybHMpIHtcbiAgICAgICAgdmFyIGNhbGxvdXRDb250cm9sbGVyID0gY3RybHNbMF07XG4gICAgICAgIGF0dHJzLiRvYnNlcnZlKCd1aWZUeXBlJywgZnVuY3Rpb24gKGNhbGxvdXRUeXBlKSB7XG4gICAgICAgICAgICBpZiAobmcuaXNVbmRlZmluZWQoY2FsbG91dFR5cGVFbnVtXzEuQ2FsbG91dFR5cGVbY2FsbG91dFR5cGVdKSkge1xuICAgICAgICAgICAgICAgIGNhbGxvdXRDb250cm9sbGVyLiRsb2cuZXJyb3IoJ0Vycm9yIFtuZ09mZmljZVVpRmFicmljXSBvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmNhbGxvdXQgLSBcIicgK1xuICAgICAgICAgICAgICAgICAgICBjYWxsb3V0VHlwZSArICdcIiBpcyBub3QgYSB2YWxpZCB2YWx1ZSBmb3IgdWlmVHlwZS4gSXQgc2hvdWxkIGJlIG9vYmUgb3IgcGVlaycpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICAgICAgaWYgKCFhdHRycy51aWZBcnJvdykge1xuICAgICAgICAgICAgc2NvcGUuYXJyb3dEaXJlY3Rpb24gPSAnTGVmdCc7XG4gICAgICAgIH1cbiAgICAgICAgYXR0cnMuJG9ic2VydmUoJ3VpZkFycm93JywgZnVuY3Rpb24gKGF0dHJBcnJvd0RpcmVjdGlvbikge1xuICAgICAgICAgICAgaWYgKG5nLmlzVW5kZWZpbmVkKGNhbGxvdXRBcnJvd0VudW1fMS5DYWxsb3V0QXJyb3dbYXR0ckFycm93RGlyZWN0aW9uXSkpIHtcbiAgICAgICAgICAgICAgICBjYWxsb3V0Q29udHJvbGxlci4kbG9nLmVycm9yKCdFcnJvciBbbmdPZmZpY2VVaUZhYnJpY10gb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5jYWxsb3V0IC0gXCInICtcbiAgICAgICAgICAgICAgICAgICAgYXR0ckFycm93RGlyZWN0aW9uICsgJ1wiIGlzIG5vdCBhIHZhbGlkIHZhbHVlIGZvciB1aWZBcnJvdy4gSXQgc2hvdWxkIGJlIGxlZnQsIHJpZ2h0LCB0b3AsIGJvdHRvbS4nKTtcbiAgICAgICAgICAgICAgICByZXR1cm47XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICB2YXIgY2FwaXRhbGl6ZWREaXJlY3Rpb24gPSAoYXR0ckFycm93RGlyZWN0aW9uLmNoYXJBdCgwKSkudG9VcHBlckNhc2UoKTtcbiAgICAgICAgICAgIGNhcGl0YWxpemVkRGlyZWN0aW9uICs9IChhdHRyQXJyb3dEaXJlY3Rpb24uc2xpY2UoMSkpLnRvTG93ZXJDYXNlKCk7XG4gICAgICAgICAgICBzY29wZS5hcnJvd0RpcmVjdGlvbiA9IGNhcGl0YWxpemVkRGlyZWN0aW9uO1xuICAgICAgICB9KTtcbiAgICAgICAgc2NvcGUuaGFzU2VwYXJhdG9yID0gKCFuZy5pc1VuZGVmaW5lZChhdHRycy51aWZBY3Rpb25UZXh0KSB8fCAhbmcuaXNVbmRlZmluZWQoYXR0cnMudWlmU2VwYXJhdG9yKSk7XG4gICAgICAgIGlmICghbmcuaXNVbmRlZmluZWQoYXR0cnMudWlmQ2xvc2UpKSB7XG4gICAgICAgICAgICBzY29wZS5jbG9zZUJ1dHRvbiA9IHRydWU7XG4gICAgICAgICAgICB2YXIgY2xvc2VCdXR0b25FbGVtZW50ID0gbmcuZWxlbWVudCgnPGJ1dHRvbiBjbGFzcz1cIm1zLUNhbGxvdXQtY2xvc2VcIj4nICtcbiAgICAgICAgICAgICAgICAnPGkgY2xhc3M9XCJtcy1JY29uIG1zLUljb24tLXhcIj48L2k+JyArXG4gICAgICAgICAgICAgICAgJzwvYnV0dG9uPicpO1xuICAgICAgICAgICAgdmFyIGNhbGxvdXREaXYgPSBpbnN0YW5jZUVsZW1lbnQuZmluZCgnZGl2JykuZXEoMCk7XG4gICAgICAgICAgICBjYWxsb3V0RGl2LmFwcGVuZChjbG9zZUJ1dHRvbkVsZW1lbnQpO1xuICAgICAgICAgICAgY2xvc2VCdXR0b25FbGVtZW50LmJpbmQoJ2NsaWNrJywgZnVuY3Rpb24gKGV2ZW50T2JqZWN0KSB7XG4gICAgICAgICAgICAgICAgc2NvcGUubmdTaG93ID0gZmFsc2U7XG4gICAgICAgICAgICAgICAgc2NvcGUuY2xvc2VCdXR0b25DbGlja2VkID0gdHJ1ZTtcbiAgICAgICAgICAgICAgICBzY29wZS4kYXBwbHkoKTtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9XG4gICAgICAgIGluc3RhbmNlRWxlbWVudC5iaW5kKCdtb3VzZWVudGVyJywgZnVuY3Rpb24gKGV2ZW50T2JqZWN0KSB7XG4gICAgICAgICAgICBzY29wZS5pc01vdXNlT3ZlciA9IHRydWU7XG4gICAgICAgICAgICBzY29wZS4kYXBwbHkoKTtcbiAgICAgICAgfSk7XG4gICAgICAgIGluc3RhbmNlRWxlbWVudC5iaW5kKCdtb3VzZWxlYXZlJywgZnVuY3Rpb24gKGV2ZW50T2JqZWN0KSB7XG4gICAgICAgICAgICBzY29wZS5pc01vdXNlT3ZlciA9IGZhbHNlO1xuICAgICAgICAgICAgc2NvcGUuJGFwcGx5KCk7XG4gICAgICAgIH0pO1xuICAgICAgICBzY29wZS4kd2F0Y2goJ25nU2hvdycsIGZ1bmN0aW9uIChuZXdWYWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgICAgIHZhciBpc0Nsb3NpbmdCeUJ1dHRvbkNsaWNrID0gIW5ld1ZhbHVlICYmIHNjb3BlLmNsb3NlQnV0dG9uQ2xpY2tlZDtcbiAgICAgICAgICAgIGlmIChpc0Nsb3NpbmdCeUJ1dHRvbkNsaWNrKSB7XG4gICAgICAgICAgICAgICAgc2NvcGUubmdTaG93ID0gc2NvcGUuY2xvc2VCdXR0b25DbGlja2VkID0gZmFsc2U7XG4gICAgICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKCFuZXdWYWx1ZSkge1xuICAgICAgICAgICAgICAgIHNjb3BlLm5nU2hvdyA9IHNjb3BlLmlzTW91c2VPdmVyO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICAgICAgc2NvcGUuJHdhdGNoKCdpc01vdXNlT3ZlcicsIGZ1bmN0aW9uIChuZXdWYWwsIG9sZFZhbCkge1xuICAgICAgICAgICAgaWYgKCFuZXdWYWwgJiYgb2xkVmFsKSB7XG4gICAgICAgICAgICAgICAgaWYgKCFzY29wZS5jbG9zZUJ1dHRvbikge1xuICAgICAgICAgICAgICAgICAgICBzY29wZS5uZ1Nob3cgPSBmYWxzZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgIH0pO1xuICAgIH07XG4gICAgcmV0dXJuIENhbGxvdXREaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5DYWxsb3V0RGlyZWN0aXZlID0gQ2FsbG91dERpcmVjdGl2ZTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmNhbGxvdXQnLCBbJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMnXSlcbiAgICAuZGlyZWN0aXZlKCd1aWZDYWxsb3V0JywgQ2FsbG91dERpcmVjdGl2ZS5mYWN0b3J5KCkpXG4gICAgLmRpcmVjdGl2ZSgndWlmQ2FsbG91dEhlYWRlcicsIENhbGxvdXRIZWFkZXJEaXJlY3RpdmUuZmFjdG9yeSgpKVxuICAgIC5kaXJlY3RpdmUoJ3VpZkNhbGxvdXRDb250ZW50JywgQ2FsbG91dENvbnRlbnREaXJlY3RpdmUuZmFjdG9yeSgpKVxuICAgIC5kaXJlY3RpdmUoJ3VpZkNhbGxvdXRBY3Rpb25zJywgQ2FsbG91dEFjdGlvbnNEaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9jYWxsb3V0L2NhbGxvdXREaXJlY3RpdmUudHNcbiAqKiBtb2R1bGUgaWQgPSA0XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG4oZnVuY3Rpb24gKENhbGxvdXRUeXBlKSB7XG4gICAgQ2FsbG91dFR5cGVbQ2FsbG91dFR5cGVbXCJvb2JlXCJdID0gMF0gPSBcIm9vYmVcIjtcbiAgICBDYWxsb3V0VHlwZVtDYWxsb3V0VHlwZVtcInBlZWtcIl0gPSAxXSA9IFwicGVla1wiO1xufSkoZXhwb3J0cy5DYWxsb3V0VHlwZSB8fCAoZXhwb3J0cy5DYWxsb3V0VHlwZSA9IHt9KSk7XG52YXIgQ2FsbG91dFR5cGUgPSBleHBvcnRzLkNhbGxvdXRUeXBlO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2NhbGxvdXQvY2FsbG91dFR5cGVFbnVtLnRzXG4gKiogbW9kdWxlIGlkID0gNVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xuKGZ1bmN0aW9uIChDYWxsb3V0QXJyb3cpIHtcbiAgICBDYWxsb3V0QXJyb3dbQ2FsbG91dEFycm93W1wibGVmdFwiXSA9IDBdID0gXCJsZWZ0XCI7XG4gICAgQ2FsbG91dEFycm93W0NhbGxvdXRBcnJvd1tcInJpZ2h0XCJdID0gMV0gPSBcInJpZ2h0XCI7XG4gICAgQ2FsbG91dEFycm93W0NhbGxvdXRBcnJvd1tcInRvcFwiXSA9IDJdID0gXCJ0b3BcIjtcbiAgICBDYWxsb3V0QXJyb3dbQ2FsbG91dEFycm93W1wiYm90dG9tXCJdID0gM10gPSBcImJvdHRvbVwiO1xufSkoZXhwb3J0cy5DYWxsb3V0QXJyb3cgfHwgKGV4cG9ydHMuQ2FsbG91dEFycm93ID0ge30pKTtcbnZhciBDYWxsb3V0QXJyb3cgPSBleHBvcnRzLkNhbGxvdXRBcnJvdztcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9jYWxsb3V0L2NhbGxvdXRBcnJvd0VudW0udHNcbiAqKiBtb2R1bGUgaWQgPSA2XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgYnV0dG9uVHlwZUVudW1fdHNfMSA9IHJlcXVpcmUoJy4vYnV0dG9uVHlwZUVudW0udHMnKTtcbnZhciBidXR0b25UZW1wbGF0ZVR5cGVfdHNfMSA9IHJlcXVpcmUoJy4vYnV0dG9uVGVtcGxhdGVUeXBlLnRzJyk7XG52YXIgQnV0dG9uQ29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQnV0dG9uQ29udHJvbGxlcigkbG9nKSB7XG4gICAgICAgIHRoaXMuJGxvZyA9ICRsb2c7XG4gICAgfVxuICAgIEJ1dHRvbkNvbnRyb2xsZXIuJGluamVjdCA9IFsnJGxvZyddO1xuICAgIHJldHVybiBCdXR0b25Db250cm9sbGVyO1xufSkoKTtcbnZhciBCdXR0b25EaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIEJ1dHRvbkRpcmVjdGl2ZSgkbG9nKSB7XG4gICAgICAgIHZhciBfdGhpcyA9IHRoaXM7XG4gICAgICAgIHRoaXMuJGxvZyA9ICRsb2c7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7fTtcbiAgICAgICAgdGhpcy5jb250cm9sbGVyID0gQnV0dG9uQ29udHJvbGxlcjtcbiAgICAgICAgdGhpcy5jb250cm9sbGVyQXMgPSAnYnV0dG9uJztcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9IGZ1bmN0aW9uICgkZWxlbWVudCwgJGF0dHJzKSB7XG4gICAgICAgICAgICBpZiAoIW5nLmlzVW5kZWZpbmVkKCRhdHRycy51aWZUeXBlKSAmJiBuZy5pc1VuZGVmaW5lZChidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtWyRhdHRycy51aWZUeXBlXSkpIHtcbiAgICAgICAgICAgICAgICBfdGhpcy4kbG9nLmVycm9yKCdFcnJvciBbbmdPZmZpY2VVaUZhYnJpY10gb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5idXR0b24gLSBVbnN1cHBvcnRlZCBidXR0b246ICcgK1xuICAgICAgICAgICAgICAgICAgICAnVGhlIGJ1dHRvbiAoXFwnJyArICRhdHRycy51aWZUeXBlICsgJ1xcJykgaXMgbm90IHN1cHBvcnRlZCBieSB0aGUgT2ZmaWNlIFVJIEZhYnJpYy4gJyArXG4gICAgICAgICAgICAgICAgICAgICdTdXBwb3J0ZWQgb3B0aW9ucyBhcmUgbGlzdGVkIGhlcmU6ICcgK1xuICAgICAgICAgICAgICAgICAgICAnaHR0cHM6Ly9naXRodWIuY29tL25nT2ZmaWNlVUlGYWJyaWMvbmctb2ZmaWNldWlmYWJyaWMvYmxvYi9tYXN0ZXIvc3JjL2NvbXBvbmVudHMvYnV0dG9uL2J1dHRvblR5cGVFbnVtLnRzJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBzd2l0Y2ggKCRhdHRycy51aWZUeXBlKSB7XG4gICAgICAgICAgICAgICAgY2FzZSBidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtW2J1dHRvblR5cGVFbnVtX3RzXzEuQnV0dG9uVHlwZUVudW0ucHJpbWFyeV06XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBuZy5pc1VuZGVmaW5lZCgkYXR0cnMubmdIcmVmKVxuICAgICAgICAgICAgICAgICAgICAgICAgPyBfdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLnByaW1hcnlCdXR0b25dXG4gICAgICAgICAgICAgICAgICAgICAgICA6IF90aGlzLnRlbXBsYXRlT3B0aW9uc1tidXR0b25UZW1wbGF0ZVR5cGVfdHNfMS5CdXR0b25UZW1wbGF0ZVR5cGUucHJpbWFyeUxpbmtdO1xuICAgICAgICAgICAgICAgIGNhc2UgYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bVtidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtLmNvbW1hbmRdOlxuICAgICAgICAgICAgICAgICAgICByZXR1cm4gbmcuaXNVbmRlZmluZWQoJGF0dHJzLm5nSHJlZilcbiAgICAgICAgICAgICAgICAgICAgICAgID8gX3RoaXMudGVtcGxhdGVPcHRpb25zW2J1dHRvblRlbXBsYXRlVHlwZV90c18xLkJ1dHRvblRlbXBsYXRlVHlwZS5jb21tYW5kQnV0dG9uXVxuICAgICAgICAgICAgICAgICAgICAgICAgOiBfdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmNvbW1hbmRMaW5rXTtcbiAgICAgICAgICAgICAgICBjYXNlIGJ1dHRvblR5cGVFbnVtX3RzXzEuQnV0dG9uVHlwZUVudW1bYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bS5jb21wb3VuZF06XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBuZy5pc1VuZGVmaW5lZCgkYXR0cnMubmdIcmVmKVxuICAgICAgICAgICAgICAgICAgICAgICAgPyBfdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmNvbXBvdW5kQnV0dG9uXVxuICAgICAgICAgICAgICAgICAgICAgICAgOiBfdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmNvbXBvdW5kTGlua107XG4gICAgICAgICAgICAgICAgY2FzZSBidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtW2J1dHRvblR5cGVFbnVtX3RzXzEuQnV0dG9uVHlwZUVudW0uaGVyb106XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBuZy5pc1VuZGVmaW5lZCgkYXR0cnMubmdIcmVmKVxuICAgICAgICAgICAgICAgICAgICAgICAgPyBfdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmhlcm9CdXR0b25dXG4gICAgICAgICAgICAgICAgICAgICAgICA6IF90aGlzLnRlbXBsYXRlT3B0aW9uc1tidXR0b25UZW1wbGF0ZVR5cGVfdHNfMS5CdXR0b25UZW1wbGF0ZVR5cGUuaGVyb0xpbmtdO1xuICAgICAgICAgICAgICAgIGRlZmF1bHQ6XG4gICAgICAgICAgICAgICAgICAgIHJldHVybiBuZy5pc1VuZGVmaW5lZCgkYXR0cnMubmdIcmVmKVxuICAgICAgICAgICAgICAgICAgICAgICAgPyBfdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmFjdGlvbkJ1dHRvbl1cbiAgICAgICAgICAgICAgICAgICAgICAgIDogX3RoaXMudGVtcGxhdGVPcHRpb25zW2J1dHRvblRlbXBsYXRlVHlwZV90c18xLkJ1dHRvblRlbXBsYXRlVHlwZS5hY3Rpb25MaW5rXTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfTtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZU9wdGlvbnMgPSB7fTtcbiAgICAgICAgdGhpcy5fcG9wdWxhdGVIdG1sVGVtcGxhdGVzKCk7XG4gICAgfVxuICAgIEJ1dHRvbkRpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCRsb2cpIHsgcmV0dXJuIG5ldyBCdXR0b25EaXJlY3RpdmUoJGxvZyk7IH07XG4gICAgICAgIGRpcmVjdGl2ZS4kaW5qZWN0ID0gWyckbG9nJ107XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICBCdXR0b25EaXJlY3RpdmUucHJvdG90eXBlLmNvbXBpbGUgPSBmdW5jdGlvbiAoZWxlbWVudCwgYXR0cnMsIHRyYW5zY2x1ZGUpIHtcbiAgICAgICAgcmV0dXJuIHtcbiAgICAgICAgICAgIHBvc3Q6IHRoaXMucG9zdExpbmssXG4gICAgICAgICAgICBwcmU6IHRoaXMucHJlTGlua1xuICAgICAgICB9O1xuICAgIH07XG4gICAgQnV0dG9uRGlyZWN0aXZlLnByb3RvdHlwZS5wcmVMaW5rID0gZnVuY3Rpb24gKHNjb3BlLCBlbGVtZW50LCBhdHRycywgY29udHJvbGxlcnMsIHRyYW5zY2x1ZGUpIHtcbiAgICAgICAgdmFyIGRpc2FibGVkID0gJ2Rpc2FibGVkJyBpbiBhdHRycztcbiAgICAgICAgc2NvcGUuZGlzYWJsZWQgPSBkaXNhYmxlZDtcbiAgICB9O1xuICAgIEJ1dHRvbkRpcmVjdGl2ZS5wcm90b3R5cGUucG9zdExpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGVsZW1lbnQsIGF0dHJzLCBjb250cm9sbGVycywgdHJhbnNjbHVkZSkge1xuICAgICAgICBpZiAobmcuaXNVbmRlZmluZWQoYXR0cnMudWlmVHlwZSkgfHxcbiAgICAgICAgICAgIGF0dHJzLnVpZlR5cGUgPT09IGJ1dHRvblR5cGVFbnVtX3RzXzEuQnV0dG9uVHlwZUVudW1bYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bS5wcmltYXJ5XSB8fFxuICAgICAgICAgICAgYXR0cnMudWlmVHlwZSA9PT0gYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bVtidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtLmNvbXBvdW5kXSkge1xuICAgICAgICAgICAgdmFyIGljb25FbGVtZW50ID0gZWxlbWVudC5maW5kKCd1aWYtaWNvbicpO1xuICAgICAgICAgICAgaWYgKGljb25FbGVtZW50Lmxlbmd0aCAhPT0gMCkge1xuICAgICAgICAgICAgICAgIGljb25FbGVtZW50LnJlbW92ZSgpO1xuICAgICAgICAgICAgICAgIGNvbnRyb2xsZXJzLiRsb2cuZXJyb3IoJ0Vycm9yIFtuZ09mZmljZVVpRmFicmljXSBvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmJ1dHRvbiAtICcgK1xuICAgICAgICAgICAgICAgICAgICAnSWNvbiBub3QgYWxsb3dlZCBpbiBwcmltYXJ5IG9yIGNvbXBvdW5kIGJ1dHRvbnM6ICcgK1xuICAgICAgICAgICAgICAgICAgICAnVGhlIHByaW1hcnkgJiBjb21wb3VuZCBidXR0b24gZG9lcyBub3Qgc3VwcG9ydCBpbmNsdWRpbmcgaWNvbnMgaW4gdGhlIGJvZHkuICcgK1xuICAgICAgICAgICAgICAgICAgICAnVGhlIGljb24gaGFzIGJlZW4gcmVtb3ZlZCBidXQgbWF5IGNhdXNlIHJlbmRlcmluZyBlcnJvcnMuIENvbnNpZGVyIGJ1dHRvbnMgdGhhdCBzdXBwb3J0IGljb25zIHN1Y2ggYXMgY29tbWFuZCBvciBoZXJvLicpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIHRyYW5zY2x1ZGUoZnVuY3Rpb24gKGNsb25lKSB7XG4gICAgICAgICAgICB2YXIgd3JhcHBlcjtcbiAgICAgICAgICAgIHN3aXRjaCAoYXR0cnMudWlmVHlwZSkge1xuICAgICAgICAgICAgICAgIGNhc2UgYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bVtidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtLmNvbW1hbmRdOlxuICAgICAgICAgICAgICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IGNsb25lLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAoY2xvbmVbaV0udGFnTmFtZSA9PT0gJ1NQQU4nKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgd3JhcHBlciA9IG5nLmVsZW1lbnQoJzxzcGFuPjwvc3Bhbj4nKTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB3cmFwcGVyLmFkZENsYXNzKCdtcy1CdXR0b24tbGFiZWwnKS5hcHBlbmQoY2xvbmVbaV0pO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGVsZW1lbnQuYXBwZW5kKHdyYXBwZXIpO1xuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgaWYgKGNsb25lW2ldLnRhZ05hbWUgPT09ICdVSUYtSUNPTicpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB3cmFwcGVyID0gbmcuZWxlbWVudCgnPHNwYW4+PC9zcGFuPicpO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHdyYXBwZXIuYWRkQ2xhc3MoJ21zLUJ1dHRvbi1pY29uJykuYXBwZW5kKGNsb25lW2ldKTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBlbGVtZW50LmFwcGVuZCh3cmFwcGVyKTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICBjYXNlIGJ1dHRvblR5cGVFbnVtX3RzXzEuQnV0dG9uVHlwZUVudW1bYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bS5jb21wb3VuZF06XG4gICAgICAgICAgICAgICAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgY2xvbmUubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChjbG9uZVtpXS50YWdOYW1lICE9PSAnU1BBTicpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBjb250aW51ZTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChjbG9uZVtpXS5jbGFzc0xpc3RbMF0gPT09ICduZy1zY29wZScgJiZcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBjbG9uZVtpXS5jbGFzc0xpc3QubGVuZ3RoID09PSAxKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgd3JhcHBlciA9IG5nLmVsZW1lbnQoJzxzcGFuPjwvc3Bhbj4nKTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB3cmFwcGVyLmFkZENsYXNzKCdtcy1CdXR0b24tbGFiZWwnKS5hcHBlbmQoY2xvbmVbaV0pO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGVsZW1lbnQuYXBwZW5kKHdyYXBwZXIpO1xuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgZWxlbWVudC5hcHBlbmQoY2xvbmVbaV0pO1xuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgICAgIGNhc2UgYnV0dG9uVHlwZUVudW1fdHNfMS5CdXR0b25UeXBlRW51bVtidXR0b25UeXBlRW51bV90c18xLkJ1dHRvblR5cGVFbnVtLmhlcm9dOlxuICAgICAgICAgICAgICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IGNsb25lLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBpZiAoY2xvbmVbaV0udGFnTmFtZSA9PT0gJ1NQQU4nKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgd3JhcHBlciA9IG5nLmVsZW1lbnQoJzxzcGFuPjwvc3Bhbj4nKTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB3cmFwcGVyLmFkZENsYXNzKCdtcy1CdXR0b24tbGFiZWwnKS5hcHBlbmQoY2xvbmVbaV0pO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIGVsZW1lbnQuYXBwZW5kKHdyYXBwZXIpO1xuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgaWYgKGNsb25lW2ldLnRhZ05hbWUgPT09ICdVSUYtSUNPTicpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB3cmFwcGVyID0gbmcuZWxlbWVudCgnPHNwYW4+PC9zcGFuPicpO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHdyYXBwZXIuYWRkQ2xhc3MoJ21zLUJ1dHRvbi1pY29uJykuYXBwZW5kKGNsb25lW2ldKTtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBlbGVtZW50LmFwcGVuZCh3cmFwcGVyKTtcbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICBkZWZhdWx0OlxuICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgfTtcbiAgICBCdXR0b25EaXJlY3RpdmUucHJvdG90eXBlLl9wb3B1bGF0ZUh0bWxUZW1wbGF0ZXMgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHRoaXMudGVtcGxhdGVPcHRpb25zW2J1dHRvblRlbXBsYXRlVHlwZV90c18xLkJ1dHRvblRlbXBsYXRlVHlwZS5hY3Rpb25CdXR0b25dID1cbiAgICAgICAgICAgIFwiPGJ1dHRvbiBjbGFzcz1cXFwibXMtQnV0dG9uXFxcIiBuZy1jbGFzcz1cXFwieydpcy1kaXNhYmxlZCc6IGRpc2FibGVkfVxcXCI+XFxuICAgICAgICAgPHNwYW4gY2xhc3M9XFxcIm1zLUJ1dHRvbi1sYWJlbFxcXCIgbmctdHJhbnNjbHVkZT48L3NwYW4+XFxuICAgICAgIDwvYnV0dG9uPlwiO1xuICAgICAgICB0aGlzLnRlbXBsYXRlT3B0aW9uc1tidXR0b25UZW1wbGF0ZVR5cGVfdHNfMS5CdXR0b25UZW1wbGF0ZVR5cGUuYWN0aW9uTGlua10gPVxuICAgICAgICAgICAgXCI8YSBjbGFzcz1cXFwibXMtQnV0dG9uXFxcIiBuZy1jbGFzcz1cXFwieydpcy1kaXNhYmxlZCc6IGRpc2FibGVkfVxcXCI+XFxuICAgICAgICAgPHNwYW4gY2xhc3M9XFxcIm1zLUJ1dHRvbi1sYWJlbFxcXCIgbmctdHJhbnNjbHVkZT48L3NwYW4+XFxuICAgICAgIDwvYT5cIjtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLnByaW1hcnlCdXR0b25dID1cbiAgICAgICAgICAgIFwiPGJ1dHRvbiBjbGFzcz1cXFwibXMtQnV0dG9uIG1zLUJ1dHRvbi0tcHJpbWFyeVxcXCIgbmctY2xhc3M9XFxcInsnaXMtZGlzYWJsZWQnOiBkaXNhYmxlZH1cXFwiPlxcbiAgICAgICAgIDxzcGFuIGNsYXNzPVxcXCJtcy1CdXR0b24tbGFiZWxcXFwiIG5nLXRyYW5zY2x1ZGU+PC9zcGFuPlxcbiAgICAgICA8L2J1dHRvbj5cIjtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLnByaW1hcnlMaW5rXSA9XG4gICAgICAgICAgICBcIjxhIGNsYXNzPVxcXCJtcy1CdXR0b24gbXMtQnV0dG9uLS1wcmltYXJ5XFxcIiBuZy1jbGFzcz1cXFwieydpcy1kaXNhYmxlZCc6IGRpc2FibGVkfVxcXCI+XFxuICAgICAgICAgPHNwYW4gY2xhc3M9XFxcIm1zLUJ1dHRvbi1sYWJlbFxcXCIgbmctdHJhbnNjbHVkZT48L3NwYW4+XFxuICAgICAgIDwvYT5cIjtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmNvbW1hbmRCdXR0b25dID1cbiAgICAgICAgICAgIFwiPGJ1dHRvbiBjbGFzcz1cXFwibXMtQnV0dG9uIG1zLUJ1dHRvbi0tY29tbWFuZFxcXCIgbmctY2xhc3M9XFxcInsnaXMtZGlzYWJsZWQnOiBkaXNhYmxlZH1cXFwiPjwvYnV0dG9uPlwiO1xuICAgICAgICB0aGlzLnRlbXBsYXRlT3B0aW9uc1tidXR0b25UZW1wbGF0ZVR5cGVfdHNfMS5CdXR0b25UZW1wbGF0ZVR5cGUuY29tbWFuZExpbmtdID1cbiAgICAgICAgICAgIFwiPGEgY2xhc3M9XFxcIm1zLUJ1dHRvbiBtcy1CdXR0b24tLWNvbW1hbmRcXFwiIG5nLWNsYXNzPVxcXCJ7J2lzLWRpc2FibGVkJzogZGlzYWJsZWR9XFxcIj48L2E+XCI7XG4gICAgICAgIHRoaXMudGVtcGxhdGVPcHRpb25zW2J1dHRvblRlbXBsYXRlVHlwZV90c18xLkJ1dHRvblRlbXBsYXRlVHlwZS5jb21wb3VuZEJ1dHRvbl0gPVxuICAgICAgICAgICAgXCI8YnV0dG9uIGNsYXNzPVxcXCJtcy1CdXR0b24gbXMtQnV0dG9uLS1jb21wb3VuZFxcXCIgbmctY2xhc3M9XFxcInsnaXMtZGlzYWJsZWQnOiBkaXNhYmxlZH1cXFwiPjwvYnV0dG9uPlwiO1xuICAgICAgICB0aGlzLnRlbXBsYXRlT3B0aW9uc1tidXR0b25UZW1wbGF0ZVR5cGVfdHNfMS5CdXR0b25UZW1wbGF0ZVR5cGUuY29tcG91bmRMaW5rXSA9XG4gICAgICAgICAgICBcIjxhIGNsYXNzPVxcXCJtcy1CdXR0b24gbXMtQnV0dG9uLS1jb21wb3VuZFxcXCIgbmctY2xhc3M9XFxcInsnaXMtZGlzYWJsZWQnOiBkaXNhYmxlZH1cXFwiPjwvYT5cIjtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZU9wdGlvbnNbYnV0dG9uVGVtcGxhdGVUeXBlX3RzXzEuQnV0dG9uVGVtcGxhdGVUeXBlLmhlcm9CdXR0b25dID1cbiAgICAgICAgICAgIFwiPGJ1dHRvbiBjbGFzcz1cXFwibXMtQnV0dG9uIG1zLUJ1dHRvbi0taGVyb1xcXCIgbmctY2xhc3M9XFxcInsnaXMtZGlzYWJsZWQnOiBkaXNhYmxlZH1cXFwiPjwvYnV0dG9uPlwiO1xuICAgICAgICB0aGlzLnRlbXBsYXRlT3B0aW9uc1tidXR0b25UZW1wbGF0ZVR5cGVfdHNfMS5CdXR0b25UZW1wbGF0ZVR5cGUuaGVyb0xpbmtdID1cbiAgICAgICAgICAgIFwiPGEgY2xhc3M9XFxcIm1zLUJ1dHRvbiBtcy1CdXR0b24tLWhlcm9cXFwiIG5nLWNsYXNzPVxcXCJ7J2lzLWRpc2FibGVkJzogZGlzYWJsZWR9XFxcIj48L2E+XCI7XG4gICAgfTtcbiAgICByZXR1cm4gQnV0dG9uRGlyZWN0aXZlO1xufSkoKTtcbmV4cG9ydHMuQnV0dG9uRGlyZWN0aXZlID0gQnV0dG9uRGlyZWN0aXZlO1xudmFyIEJ1dHRvbkRlc2NyaXB0aW9uRGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBCdXR0b25EZXNjcmlwdGlvbkRpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gJ151aWZCdXR0b24nO1xuICAgICAgICB0aGlzLnRyYW5zY2x1ZGUgPSB0cnVlO1xuICAgICAgICB0aGlzLnJlcGxhY2UgPSB0cnVlO1xuICAgICAgICB0aGlzLnNjb3BlID0gZmFsc2U7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPHNwYW4gY2xhc3M9XCJtcy1CdXR0b24tZGVzY3JpcHRpb25cIiBuZy10cmFuc2NsdWRlPjwvc3Bhbj4nO1xuICAgIH1cbiAgICBCdXR0b25EZXNjcmlwdGlvbkRpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IEJ1dHRvbkRlc2NyaXB0aW9uRGlyZWN0aXZlKCk7IH07XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICByZXR1cm4gQnV0dG9uRGVzY3JpcHRpb25EaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5CdXR0b25EZXNjcmlwdGlvbkRpcmVjdGl2ZSA9IEJ1dHRvbkRlc2NyaXB0aW9uRGlyZWN0aXZlO1xuZXhwb3J0cy5tb2R1bGUgPSBuZy5tb2R1bGUoJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMuYnV0dG9uJywgW1xuICAgICdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzJ1xuXSlcbiAgICAuZGlyZWN0aXZlKCd1aWZCdXR0b24nLCBCdXR0b25EaXJlY3RpdmUuZmFjdG9yeSgpKVxuICAgIC5kaXJlY3RpdmUoJ3VpZkJ1dHRvbkRlc2NyaXB0aW9uJywgQnV0dG9uRGVzY3JpcHRpb25EaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9idXR0b24vYnV0dG9uRGlyZWN0aXZlLnRzXG4gKiogbW9kdWxlIGlkID0gN1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xuKGZ1bmN0aW9uIChCdXR0b25UeXBlRW51bSkge1xuICAgIEJ1dHRvblR5cGVFbnVtW0J1dHRvblR5cGVFbnVtW1wicHJpbWFyeVwiXSA9IDBdID0gXCJwcmltYXJ5XCI7XG4gICAgQnV0dG9uVHlwZUVudW1bQnV0dG9uVHlwZUVudW1bXCJjb21tYW5kXCJdID0gMV0gPSBcImNvbW1hbmRcIjtcbiAgICBCdXR0b25UeXBlRW51bVtCdXR0b25UeXBlRW51bVtcImNvbXBvdW5kXCJdID0gMl0gPSBcImNvbXBvdW5kXCI7XG4gICAgQnV0dG9uVHlwZUVudW1bQnV0dG9uVHlwZUVudW1bXCJoZXJvXCJdID0gM10gPSBcImhlcm9cIjtcbn0pKGV4cG9ydHMuQnV0dG9uVHlwZUVudW0gfHwgKGV4cG9ydHMuQnV0dG9uVHlwZUVudW0gPSB7fSkpO1xudmFyIEJ1dHRvblR5cGVFbnVtID0gZXhwb3J0cy5CdXR0b25UeXBlRW51bTtcbjtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9idXR0b24vYnV0dG9uVHlwZUVudW0udHNcbiAqKiBtb2R1bGUgaWQgPSA4XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG4oZnVuY3Rpb24gKEJ1dHRvblRlbXBsYXRlVHlwZSkge1xuICAgIEJ1dHRvblRlbXBsYXRlVHlwZVtCdXR0b25UZW1wbGF0ZVR5cGVbXCJhY3Rpb25CdXR0b25cIl0gPSAwXSA9IFwiYWN0aW9uQnV0dG9uXCI7XG4gICAgQnV0dG9uVGVtcGxhdGVUeXBlW0J1dHRvblRlbXBsYXRlVHlwZVtcImFjdGlvbkxpbmtcIl0gPSAxXSA9IFwiYWN0aW9uTGlua1wiO1xuICAgIEJ1dHRvblRlbXBsYXRlVHlwZVtCdXR0b25UZW1wbGF0ZVR5cGVbXCJwcmltYXJ5QnV0dG9uXCJdID0gMl0gPSBcInByaW1hcnlCdXR0b25cIjtcbiAgICBCdXR0b25UZW1wbGF0ZVR5cGVbQnV0dG9uVGVtcGxhdGVUeXBlW1wicHJpbWFyeUxpbmtcIl0gPSAzXSA9IFwicHJpbWFyeUxpbmtcIjtcbiAgICBCdXR0b25UZW1wbGF0ZVR5cGVbQnV0dG9uVGVtcGxhdGVUeXBlW1wiY29tbWFuZEJ1dHRvblwiXSA9IDRdID0gXCJjb21tYW5kQnV0dG9uXCI7XG4gICAgQnV0dG9uVGVtcGxhdGVUeXBlW0J1dHRvblRlbXBsYXRlVHlwZVtcImNvbW1hbmRMaW5rXCJdID0gNV0gPSBcImNvbW1hbmRMaW5rXCI7XG4gICAgQnV0dG9uVGVtcGxhdGVUeXBlW0J1dHRvblRlbXBsYXRlVHlwZVtcImNvbXBvdW5kQnV0dG9uXCJdID0gNl0gPSBcImNvbXBvdW5kQnV0dG9uXCI7XG4gICAgQnV0dG9uVGVtcGxhdGVUeXBlW0J1dHRvblRlbXBsYXRlVHlwZVtcImNvbXBvdW5kTGlua1wiXSA9IDddID0gXCJjb21wb3VuZExpbmtcIjtcbiAgICBCdXR0b25UZW1wbGF0ZVR5cGVbQnV0dG9uVGVtcGxhdGVUeXBlW1wiaGVyb0J1dHRvblwiXSA9IDhdID0gXCJoZXJvQnV0dG9uXCI7XG4gICAgQnV0dG9uVGVtcGxhdGVUeXBlW0J1dHRvblRlbXBsYXRlVHlwZVtcImhlcm9MaW5rXCJdID0gOV0gPSBcImhlcm9MaW5rXCI7XG59KShleHBvcnRzLkJ1dHRvblRlbXBsYXRlVHlwZSB8fCAoZXhwb3J0cy5CdXR0b25UZW1wbGF0ZVR5cGUgPSB7fSkpO1xudmFyIEJ1dHRvblRlbXBsYXRlVHlwZSA9IGV4cG9ydHMuQnV0dG9uVGVtcGxhdGVUeXBlO1xuO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2J1dHRvbi9idXR0b25UZW1wbGF0ZVR5cGUudHNcbiAqKiBtb2R1bGUgaWQgPSA5XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgY2hvaWNlZmllbGRUeXBlRW51bV8xID0gcmVxdWlyZSgnLi9jaG9pY2VmaWVsZFR5cGVFbnVtJyk7XG52YXIgQ2hvaWNlZmllbGRPcHRpb25Db250cm9sbGVyID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBDaG9pY2VmaWVsZE9wdGlvbkNvbnRyb2xsZXIoJGxvZykge1xuICAgICAgICB0aGlzLiRsb2cgPSAkbG9nO1xuICAgIH1cbiAgICBDaG9pY2VmaWVsZE9wdGlvbkNvbnRyb2xsZXIuJGluamVjdCA9IFsnJGxvZyddO1xuICAgIHJldHVybiBDaG9pY2VmaWVsZE9wdGlvbkNvbnRyb2xsZXI7XG59KSgpO1xuZXhwb3J0cy5DaG9pY2VmaWVsZE9wdGlvbkNvbnRyb2xsZXIgPSBDaG9pY2VmaWVsZE9wdGlvbkNvbnRyb2xsZXI7XG52YXIgQ2hvaWNlZmllbGRPcHRpb25EaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIENob2ljZWZpZWxkT3B0aW9uRGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxkaXYgY2xhc3M9XCJtcy1DaG9pY2VGaWVsZFwiPicgK1xuICAgICAgICAgICAgJzxpbnB1dCBpZD1cInt7OjokaWR9fVwiIGNsYXNzPVwibXMtQ2hvaWNlRmllbGQtaW5wdXRcIiB0eXBlPVwie3t1aWZUeXBlfX1cIiB2YWx1ZT1cInt7dmFsdWV9fVwiICcgK1xuICAgICAgICAgICAgJ25nLW1vZGVsPVwibmdNb2RlbFwiIG5nLXRydWUtdmFsdWU9XCJ7e25nVHJ1ZVZhbHVlfX1cIiBuZy1mYWxzZS12YWx1ZT1cInt7bmdGYWxzZVZhbHVlfX1cIiAvPicgK1xuICAgICAgICAgICAgJzxsYWJlbCBmb3I9XCJ7ezo6JGlkfX1cIiBjbGFzcz1cIm1zLUNob2ljZUZpZWxkLWZpZWxkXCI+PHNwYW4gY2xhc3M9XCJtcy1MYWJlbFwiIG5nLXRyYW5zY2x1ZGU+PC9zcGFuPjwvbGFiZWw+JyArXG4gICAgICAgICAgICAnPC9kaXY+JztcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gWyd1aWZDaG9pY2VmaWVsZE9wdGlvbicsICdeP3VpZkNob2ljZWZpZWxkR3JvdXAnXTtcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5zY29wZSA9IHtcbiAgICAgICAgICAgIG5nRmFsc2VWYWx1ZTogJ0AnLFxuICAgICAgICAgICAgbmdNb2RlbDogJz0nLFxuICAgICAgICAgICAgbmdUcnVlVmFsdWU6ICdAJyxcbiAgICAgICAgICAgIHVpZlR5cGU6ICdAJyxcbiAgICAgICAgICAgIHZhbHVlOiAnQCdcbiAgICAgICAgfTtcbiAgICAgICAgdGhpcy5jb250cm9sbGVyID0gQ2hvaWNlZmllbGRPcHRpb25Db250cm9sbGVyO1xuICAgIH1cbiAgICBDaG9pY2VmaWVsZE9wdGlvbkRpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgcmV0dXJuIG5ldyBDaG9pY2VmaWVsZE9wdGlvbkRpcmVjdGl2ZSgpO1xuICAgICAgICB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgQ2hvaWNlZmllbGRPcHRpb25EaXJlY3RpdmUucHJvdG90eXBlLmNvbXBpbGUgPSBmdW5jdGlvbiAodGVtcGxhdGVFbGVtZW50LCB0ZW1wbGF0ZUF0dHJpYnV0ZXMsIHRyYW5zY2x1ZGUpIHtcbiAgICAgICAgdmFyIGlucHV0ID0gdGVtcGxhdGVFbGVtZW50LmZpbmQoJ2lucHV0Jyk7XG4gICAgICAgIGlmICghKCduZ01vZGVsJyBpbiB0ZW1wbGF0ZUF0dHJpYnV0ZXMpKSB7XG4gICAgICAgICAgICBpbnB1dC5yZW1vdmVBdHRyKCduZy1tb2RlbCcpO1xuICAgICAgICB9XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBwcmU6IHRoaXMucHJlTGlua1xuICAgICAgICB9O1xuICAgIH07XG4gICAgQ2hvaWNlZmllbGRPcHRpb25EaXJlY3RpdmUucHJvdG90eXBlLnByZUxpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGluc3RhbmNlRWxlbWVudCwgYXR0cnMsIGN0cmxzLCB0cmFuc2NsdWRlKSB7XG4gICAgICAgIHZhciBjaG9pY2VmaWVsZE9wdGlvbkNvbnRyb2xsZXIgPSBjdHJsc1swXTtcbiAgICAgICAgdmFyIGNob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyID0gY3RybHNbMV07XG4gICAgICAgIHNjb3BlLiR3YXRjaCgndWlmVHlwZScsIGZ1bmN0aW9uIChuZXdWYWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgICAgIGlmIChjaG9pY2VmaWVsZFR5cGVFbnVtXzEuQ2hvaWNlZmllbGRUeXBlW25ld1ZhbHVlXSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgY2hvaWNlZmllbGRPcHRpb25Db250cm9sbGVyLiRsb2cuZXJyb3IoJ0Vycm9yIFtuZ09mZmljZVVpRmFicmljXSBvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmNob2ljZWZpZWxkIC0gXCInICtcbiAgICAgICAgICAgICAgICAgICAgbmV3VmFsdWUgKyAnXCIgaXMgbm90IGEgdmFsaWQgdmFsdWUgZm9yIHVpZlR5cGUuICcgK1xuICAgICAgICAgICAgICAgICAgICAnU3VwcG9ydGVkIG9wdGlvbnMgYXJlIGxpc3RlZCBoZXJlOiAnICtcbiAgICAgICAgICAgICAgICAgICAgJ2h0dHBzOi8vZ2l0aHViLmNvbS9uZ09mZmljZVVJRmFicmljL25nLW9mZmljZXVpZmFicmljL2Jsb2IvbWFzdGVyL3NyYy9jb21wb25lbnRzL2Nob2ljZWZpZWxkL2Nob2ljZWZpZWxkVHlwZUVudW0udHMnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgICAgIGlmIChjaG9pY2VmaWVsZEdyb3VwQ29udHJvbGxlciAhPSBudWxsKSB7XG4gICAgICAgICAgICB2YXIgcmVuZGVyID0gZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgICAgIHZhciBjaGVja2VkID0gKGNob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyLmdldFZpZXdWYWx1ZSgpID09PSBhdHRycy52YWx1ZSk7XG4gICAgICAgICAgICAgICAgaW5zdGFuY2VFbGVtZW50LmZpbmQoJ2lucHV0JykucHJvcCgnY2hlY2tlZCcsIGNoZWNrZWQpO1xuICAgICAgICAgICAgfTtcbiAgICAgICAgICAgIGNob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyLmFkZFJlbmRlcihyZW5kZXIpO1xuICAgICAgICAgICAgYXR0cnMuJG9ic2VydmUoJ3ZhbHVlJywgcmVuZGVyKTtcbiAgICAgICAgICAgIGluc3RhbmNlRWxlbWVudFxuICAgICAgICAgICAgICAgIC5vbignJGRlc3Ryb3knLCBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgY2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIucmVtb3ZlUmVuZGVyKHJlbmRlcik7XG4gICAgICAgICAgICB9KTtcbiAgICAgICAgfVxuICAgICAgICB2YXIgZGlzYWJsZWQgPSAnZGlzYWJsZWQnIGluIGF0dHJzO1xuICAgICAgICB2YXIgcGFyZW50U2NvcGUgPSBzY29wZS4kcGFyZW50LiRwYXJlbnQ7XG4gICAgICAgIGRpc2FibGVkID0gZGlzYWJsZWQgfHwgKHBhcmVudFNjb3BlICE9IG51bGwgJiYgcGFyZW50U2NvcGUuZGlzYWJsZWQpO1xuICAgICAgICBpZiAoZGlzYWJsZWQpIHtcbiAgICAgICAgICAgIGluc3RhbmNlRWxlbWVudC5maW5kKCdpbnB1dCcpLmF0dHIoJ2Rpc2FibGVkJywgJ2Rpc2FibGVkJyk7XG4gICAgICAgIH1cbiAgICAgICAgaW5zdGFuY2VFbGVtZW50XG4gICAgICAgICAgICAub24oJ2NsaWNrJywgZnVuY3Rpb24gKGV2KSB7XG4gICAgICAgICAgICBpZiAoZGlzYWJsZWQpIHtcbiAgICAgICAgICAgICAgICByZXR1cm47XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBzY29wZS4kYXBwbHkoZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgICAgIGlmIChjaG9pY2VmaWVsZEdyb3VwQ29udHJvbGxlciAhPSBudWxsKSB7XG4gICAgICAgICAgICAgICAgICAgIGNob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyLnNldFZpZXdWYWx1ZShhdHRycy52YWx1ZSwgZXYpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0pO1xuICAgICAgICB9KTtcbiAgICB9O1xuICAgIHJldHVybiBDaG9pY2VmaWVsZE9wdGlvbkRpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLkNob2ljZWZpZWxkT3B0aW9uRGlyZWN0aXZlID0gQ2hvaWNlZmllbGRPcHRpb25EaXJlY3RpdmU7XG52YXIgQ2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIENob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyKCRlbGVtZW50LCAkc2NvcGUpIHtcbiAgICAgICAgdGhpcy4kZWxlbWVudCA9ICRlbGVtZW50O1xuICAgICAgICB0aGlzLiRzY29wZSA9ICRzY29wZTtcbiAgICAgICAgdGhpcy5yZW5kZXJGbnMgPSBbXTtcbiAgICB9XG4gICAgQ2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIucHJvdG90eXBlLmluaXQgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBfdGhpcyA9IHRoaXM7XG4gICAgICAgIGlmICh0eXBlb2YgdGhpcy4kc2NvcGUubmdNb2RlbCAhPT0gJ3VuZGVmaW5lZCcgJiYgdGhpcy4kc2NvcGUubmdNb2RlbCAhPSBudWxsKSB7XG4gICAgICAgICAgICB0aGlzLiRzY29wZS5uZ01vZGVsLiRyZW5kZXIgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgX3RoaXMucmVuZGVyKCk7XG4gICAgICAgICAgICB9O1xuICAgICAgICAgICAgdGhpcy5yZW5kZXIoKTtcbiAgICAgICAgfVxuICAgIH07XG4gICAgQ2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIucHJvdG90eXBlLmFkZFJlbmRlciA9IGZ1bmN0aW9uIChmbikge1xuICAgICAgICB0aGlzLnJlbmRlckZucy5wdXNoKGZuKTtcbiAgICB9O1xuICAgIENob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyLnByb3RvdHlwZS5yZW1vdmVSZW5kZXIgPSBmdW5jdGlvbiAoZm4pIHtcbiAgICAgICAgdGhpcy5yZW5kZXJGbnMuc3BsaWNlKHRoaXMucmVuZGVyRm5zLmluZGV4T2YoZm4pKTtcbiAgICB9O1xuICAgIENob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyLnByb3RvdHlwZS5zZXRWaWV3VmFsdWUgPSBmdW5jdGlvbiAodmFsdWUsIGV2ZW50VHlwZSkge1xuICAgICAgICB0aGlzLiRzY29wZS5uZ01vZGVsLiRzZXRWaWV3VmFsdWUodmFsdWUsIGV2ZW50VHlwZSk7XG4gICAgICAgIHRoaXMucmVuZGVyKCk7XG4gICAgfTtcbiAgICBDaG9pY2VmaWVsZEdyb3VwQ29udHJvbGxlci5wcm90b3R5cGUuZ2V0Vmlld1ZhbHVlID0gZnVuY3Rpb24gKCkge1xuICAgICAgICBpZiAodHlwZW9mIHRoaXMuJHNjb3BlLm5nTW9kZWwgIT09ICd1bmRlZmluZWQnICYmIHRoaXMuJHNjb3BlLm5nTW9kZWwgIT0gbnVsbCkge1xuICAgICAgICAgICAgcmV0dXJuIHRoaXMuJHNjb3BlLm5nTW9kZWwuJHZpZXdWYWx1ZTtcbiAgICAgICAgfVxuICAgIH07XG4gICAgQ2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIucHJvdG90eXBlLnJlbmRlciA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0aGlzLnJlbmRlckZucy5sZW5ndGg7IGkrKykge1xuICAgICAgICAgICAgdGhpcy5yZW5kZXJGbnNbaV0oKTtcbiAgICAgICAgfVxuICAgIH07XG4gICAgQ2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIuJGluamVjdCA9IFsnJGVsZW1lbnQnLCAnJHNjb3BlJ107XG4gICAgcmV0dXJuIENob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyO1xufSkoKTtcbmV4cG9ydHMuQ2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIgPSBDaG9pY2VmaWVsZEdyb3VwQ29udHJvbGxlcjtcbnZhciBDaG9pY2VmaWVsZEdyb3VwRGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBDaG9pY2VmaWVsZEdyb3VwRGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxkaXYgY2xhc3M9XCJtcy1DaG9pY2VGaWVsZEdyb3VwXCI+JyArXG4gICAgICAgICAgICAnPGRpdiBjbGFzcz1cIm1zLUNob2ljZUZpZWxkR3JvdXAtdGl0bGVcIj4nICtcbiAgICAgICAgICAgICc8bGFiZWwgY2xhc3M9XCJtcy1MYWJlbCBpcy1yZXF1aXJlZFwiPlBpY2sgb25lPC9sYWJlbD4nICtcbiAgICAgICAgICAgICc8L2Rpdj4nICtcbiAgICAgICAgICAgICc8bmctdHJhbnNjbHVkZSAvPicgK1xuICAgICAgICAgICAgJzwvZGl2Pic7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMucmVxdWlyZSA9IFsndWlmQ2hvaWNlZmllbGRHcm91cCcsICc/bmdNb2RlbCddO1xuICAgICAgICB0aGlzLmNvbnRyb2xsZXIgPSBDaG9pY2VmaWVsZEdyb3VwQ29udHJvbGxlcjtcbiAgICB9XG4gICAgQ2hvaWNlZmllbGRHcm91cERpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IENob2ljZWZpZWxkR3JvdXBEaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIENob2ljZWZpZWxkR3JvdXBEaXJlY3RpdmUucHJvdG90eXBlLmNvbXBpbGUgPSBmdW5jdGlvbiAodGVtcGxhdGVFbGVtZW50LCB0ZW1wbGF0ZUF0dHJpYnV0ZXMsIHRyYW5zY2x1ZGUpIHtcbiAgICAgICAgcmV0dXJuIHtcbiAgICAgICAgICAgIHByZTogdGhpcy5wcmVMaW5rXG4gICAgICAgIH07XG4gICAgfTtcbiAgICBDaG9pY2VmaWVsZEdyb3VwRGlyZWN0aXZlLnByb3RvdHlwZS5wcmVMaW5rID0gZnVuY3Rpb24gKHNjb3BlLCBpbnN0YW5jZUVsZW1lbnQsIGluc3RhbmNlQXR0cmlidXRlcywgY3RybHMpIHtcbiAgICAgICAgdmFyIGNob2ljZWZpZWxkR3JvdXBDb250cm9sbGVyID0gY3RybHNbMF07XG4gICAgICAgIHZhciBtb2RlbENvbnRyb2xsZXIgPSBjdHJsc1sxXTtcbiAgICAgICAgc2NvcGUubmdNb2RlbCA9IG1vZGVsQ29udHJvbGxlcjtcbiAgICAgICAgY2hvaWNlZmllbGRHcm91cENvbnRyb2xsZXIuaW5pdCgpO1xuICAgICAgICBzY29wZS5kaXNhYmxlZCA9ICdkaXNhYmxlZCcgaW4gaW5zdGFuY2VBdHRyaWJ1dGVzO1xuICAgIH07XG4gICAgcmV0dXJuIENob2ljZWZpZWxkR3JvdXBEaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5DaG9pY2VmaWVsZEdyb3VwRGlyZWN0aXZlID0gQ2hvaWNlZmllbGRHcm91cERpcmVjdGl2ZTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmNob2ljZWZpZWxkJywgW1xuICAgICdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzJ1xuXSlcbiAgICAuZGlyZWN0aXZlKCd1aWZDaG9pY2VmaWVsZE9wdGlvbicsIENob2ljZWZpZWxkT3B0aW9uRGlyZWN0aXZlLmZhY3RvcnkoKSlcbiAgICAuZGlyZWN0aXZlKCd1aWZDaG9pY2VmaWVsZEdyb3VwJywgQ2hvaWNlZmllbGRHcm91cERpcmVjdGl2ZS5mYWN0b3J5KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2Nob2ljZWZpZWxkL2Nob2ljZWZpZWxkRGlyZWN0aXZlLnRzXG4gKiogbW9kdWxlIGlkID0gMTBcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyIsIid1c2Ugc3RyaWN0JztcbihmdW5jdGlvbiAoQ2hvaWNlZmllbGRUeXBlKSB7XG4gICAgQ2hvaWNlZmllbGRUeXBlW0Nob2ljZWZpZWxkVHlwZVtcInJhZGlvXCJdID0gMF0gPSBcInJhZGlvXCI7XG4gICAgQ2hvaWNlZmllbGRUeXBlW0Nob2ljZWZpZWxkVHlwZVtcImNoZWNrYm94XCJdID0gMV0gPSBcImNoZWNrYm94XCI7XG59KShleHBvcnRzLkNob2ljZWZpZWxkVHlwZSB8fCAoZXhwb3J0cy5DaG9pY2VmaWVsZFR5cGUgPSB7fSkpO1xudmFyIENob2ljZWZpZWxkVHlwZSA9IGV4cG9ydHMuQ2hvaWNlZmllbGRUeXBlO1xuO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2Nob2ljZWZpZWxkL2Nob2ljZWZpZWxkVHlwZUVudW0udHNcbiAqKiBtb2R1bGUgaWQgPSAxMVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xudmFyIG5nID0gcmVxdWlyZSgnYW5ndWxhcicpO1xudmFyIE1lbnVJdGVtVHlwZXM7XG4oZnVuY3Rpb24gKE1lbnVJdGVtVHlwZXMpIHtcbiAgICBNZW51SXRlbVR5cGVzW01lbnVJdGVtVHlwZXNbXCJsaW5rXCJdID0gMF0gPSBcImxpbmtcIjtcbiAgICBNZW51SXRlbVR5cGVzW01lbnVJdGVtVHlwZXNbXCJkaXZpZGVyXCJdID0gMV0gPSBcImRpdmlkZXJcIjtcbiAgICBNZW51SXRlbVR5cGVzW01lbnVJdGVtVHlwZXNbXCJoZWFkZXJcIl0gPSAyXSA9IFwiaGVhZGVyXCI7XG4gICAgTWVudUl0ZW1UeXBlc1tNZW51SXRlbVR5cGVzW1wic3ViTWVudVwiXSA9IDNdID0gXCJzdWJNZW51XCI7XG59KShNZW51SXRlbVR5cGVzIHx8IChNZW51SXRlbVR5cGVzID0ge30pKTtcbmV4cG9ydHMuY29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlTmFtZSA9ICd1aWZDb250ZXh0dWFsTWVudUl0ZW0nO1xuZXhwb3J0cy5jb250ZXh0dWFsTWVudURpcmVjdGl2ZU5hbWUgPSAndWlmQ29udGV4dHVhbE1lbnUnO1xudmFyIENvbnRleHR1YWxNZW51SXRlbURpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlKCRsb2cpIHtcbiAgICAgICAgdmFyIF90aGlzID0gdGhpcztcbiAgICAgICAgdGhpcy4kbG9nID0gJGxvZztcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gJ151aWZDb250ZXh0dWFsTWVudSc7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMuY29udHJvbGxlciA9IENvbnRleHR1YWxNZW51SXRlbUNvbnRyb2xsZXI7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSBmdW5jdGlvbiAoJGVsZW1lbnQsICRhdHRycykge1xuICAgICAgICAgICAgdmFyIHR5cGUgPSAkYXR0cnMudWlmVHlwZTtcbiAgICAgICAgICAgIGlmIChuZy5pc1VuZGVmaW5lZCh0eXBlKSkge1xuICAgICAgICAgICAgICAgIHJldHVybiBfdGhpcy50ZW1wbGF0ZVR5cGVzW01lbnVJdGVtVHlwZXMubGlua107XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAoTWVudUl0ZW1UeXBlc1t0eXBlXSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgX3RoaXMuJGxvZy5lcnJvcignRXJyb3IgW25nT2ZmaWNlVWlGYWJyaWNdIG9mZmljZXVpZmFicmljLmNvbXBvbmVudHMuY29udGV4dHVhbG1lbnUgLSB1bnN1cHBvcnRlZCBtZW51IHR5cGU6XFxuJyArXG4gICAgICAgICAgICAgICAgICAgICd0aGUgdHlwZSBcXCcnICsgdHlwZSArICdcXCcgaXMgbm90IHN1cHBvcnRlZCBieSBuZy1PZmZpY2UgVUkgRmFicmljIGFzIHZhbGlkIHR5cGUgZm9yIGNvbnRleHQgbWVudS4nICtcbiAgICAgICAgICAgICAgICAgICAgJ1N1cHBvcnRlZCB0eXBlcyBjYW4gYmUgZm91bmQgdW5kZXIgTWVudUl0ZW1UeXBlcyBlbnVtIGhlcmU6XFxuJyArXG4gICAgICAgICAgICAgICAgICAgICdodHRwczovL2dpdGh1Yi5jb20vbmdPZmZpY2VVSUZhYnJpYy9uZy1vZmZpY2V1aWZhYnJpYy9ibG9iL21hc3Rlci9zcmMvY29tcG9uZW50cy9jb250ZXh0dWFsbWVudS9jb250ZXh0dWFsTWVudS50cycpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgcmV0dXJuIF90aGlzLnRlbXBsYXRlVHlwZXNbTWVudUl0ZW1UeXBlc1t0eXBlXV07XG4gICAgICAgIH07XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7XG4gICAgICAgICAgICBpc0Rpc2FibGVkOiAnPT91aWZJc0Rpc2FibGVkJyxcbiAgICAgICAgICAgIGlzU2VsZWN0ZWQ6ICc9P3VpZklzU2VsZWN0ZWQnLFxuICAgICAgICAgICAgb25DbGljazogJyZ1aWZDbGljaycsXG4gICAgICAgICAgICB0ZXh0OiAnPXVpZlRleHQnLFxuICAgICAgICAgICAgdHlwZTogJ0B1aWZUeXBlJ1xuICAgICAgICB9O1xuICAgICAgICB0aGlzLnRlbXBsYXRlVHlwZXMgPSB7fTtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZVR5cGVzW01lbnVJdGVtVHlwZXMuc3ViTWVudV0gPVxuICAgICAgICAgICAgXCI8bGkgY2xhc3M9XFxcIm1zLUNvbnRleHR1YWxNZW51LWl0ZW1cXFwiPlxcbiAgICAgICAgICAgICAgICA8YSBjbGFzcz1cXFwibXMtQ29udGV4dHVhbE1lbnUtbGluayBtcy1Db250ZXh0dWFsTWVudS1saW5rLS1oYXNNZW51XFxcIlxcbiAgICAgICAgICAgICAgICBuZy1jbGFzcz1cXFwieydpcy1zZWxlY3RlZCc6IGlzU2VsZWN0ZWQsICdpcy1kaXNhYmxlZCc6IGlzRGlzYWJsZWR9XFxcIiBuZy1jbGljaz1cXFwic2VsZWN0SXRlbSgpXFxcIiBocmVmPnt7dGV4dH19PC9hPlxcbiAgICAgICAgICAgICAgICA8aSBjbGFzcz1cXFwibXMtQ29udGV4dHVhbE1lbnUtc3ViTWVudUljb24gbXMtSWNvbiBtcy1JY29uLS1jaGV2cm9uUmlnaHRcXFwiPjwvaT5cXG4gICAgICAgICAgICAgICAgPGRpdiBjbGFzcz1cXFwiY29udGVudFxcXCI+PC9kaXY+XFxuICAgICAgICAgICAgPC9saT5cIjtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZVR5cGVzW01lbnVJdGVtVHlwZXMubGlua10gPVxuICAgICAgICAgICAgXCI8bGkgY2xhc3M9XFxcIm1zLUNvbnRleHR1YWxNZW51LWl0ZW1cXFwiPlxcbiAgICAgICAgICAgICAgICA8YSBjbGFzcz1cXFwibXMtQ29udGV4dHVhbE1lbnUtbGlua1xcXCIgbmctY2xhc3M9XFxcInsnaXMtc2VsZWN0ZWQnOiBpc1NlbGVjdGVkLCAnaXMtZGlzYWJsZWQnOiBpc0Rpc2FibGVkfVxcXCJcXG4gICAgICAgICAgICAgICAgbmctY2xpY2s9XFxcInNlbGVjdEl0ZW0oKVxcXCIgaHJlZj57e3RleHR9fTwvYT5cXG4gICAgICAgICAgICA8L2xpPlwiO1xuICAgICAgICB0aGlzLnRlbXBsYXRlVHlwZXNbTWVudUl0ZW1UeXBlcy5oZWFkZXJdID0gXCI8bGkgY2xhc3M9XFxcIm1zLUNvbnRleHR1YWxNZW51LWl0ZW0gbXMtQ29udGV4dHVhbE1lbnUtaXRlbS0taGVhZGVyXFxcIj57e3RleHR9fTwvbGk+XCI7XG4gICAgICAgIHRoaXMudGVtcGxhdGVUeXBlc1tNZW51SXRlbVR5cGVzLmRpdmlkZXJdID0gXCI8bGkgY2xhc3M9XFxcIm1zLUNvbnRleHR1YWxNZW51LWl0ZW0gbXMtQ29udGV4dHVhbE1lbnUtaXRlbS0tZGl2aWRlclxcXCI+PC9saT5cIjtcbiAgICB9XG4gICAgQ29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoJGxvZykgeyByZXR1cm4gbmV3IENvbnRleHR1YWxNZW51SXRlbURpcmVjdGl2ZSgkbG9nKTsgfTtcbiAgICAgICAgZGlyZWN0aXZlLiRpbmplY3QgPSBbJyRsb2cnXTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIENvbnRleHR1YWxNZW51SXRlbURpcmVjdGl2ZS5wcm90b3R5cGUubGluayA9IGZ1bmN0aW9uICgkc2NvcGUsICRlbGVtZW50LCAkYXR0cnMsIGNvbnRleHR1YWxNZW51Q29udHJvbGxlciwgJHRyYW5zY2x1ZGUpIHtcbiAgICAgICAgaWYgKHR5cGVvZiAkc2NvcGUuaXNEaXNhYmxlZCAhPT0gJ2Jvb2xlYW4nICYmICRzY29wZS5pc0Rpc2FibGVkICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgIGNvbnRleHR1YWxNZW51Q29udHJvbGxlci4kbG9nLmVycm9yKCdFcnJvciBbbmdPZmZpY2VVaUZhYnJpY10gb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5jb250ZXh0dWFsbWVudSAtICcgK1xuICAgICAgICAgICAgICAgICdpbnZhbGlkIGF0dHJpYnV0ZSB0eXBlOiBcXCd1aWYtaXMtZGlzYWJsZWRcXCcuXFxuJyArXG4gICAgICAgICAgICAgICAgJ1RoZSB0eXBlIFxcJycgKyB0eXBlb2YgJHNjb3BlLmlzRGlzYWJsZWQgKyAnXFwnIGlzIG5vdCBzdXBwb3J0ZWQgYXMgdmFsaWQgdHlwZSBmb3IgXFwndWlmLWlzLWRpc2FibGVkXFwnIGF0dHJpYnV0ZSBmb3IgJyArXG4gICAgICAgICAgICAgICAgJzx1aWYtY29udGV4dHVhbC1tZW51LWl0ZW0gLz4uIFRoZSB2YWxpZCB0eXBlIGlzIGJvb2xlYW4uJyk7XG4gICAgICAgIH1cbiAgICAgICAgaWYgKHR5cGVvZiAkc2NvcGUuaXNTZWxlY3RlZCAhPT0gJ2Jvb2xlYW4nICYmICRzY29wZS5pc1NlbGVjdGVkICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgIGNvbnRleHR1YWxNZW51Q29udHJvbGxlci4kbG9nLmVycm9yKCdFcnJvciBbbmdPZmZpY2VVaUZhYnJpY10gb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5jb250ZXh0dWFsbWVudSAtICcgK1xuICAgICAgICAgICAgICAgICdpbnZhbGlkIGF0dHJpYnV0ZSB0eXBlOiBcXCd1aWYtaXMtc2VsZWN0ZWRcXCcuXFxuJyArXG4gICAgICAgICAgICAgICAgJ1RoZSB0eXBlIFxcJycgKyB0eXBlb2YgJHNjb3BlLmlzU2VsZWN0ZWQgKyAnXFwnIGlzIG5vdCBzdXBwb3J0ZWQgYXMgdmFsaWQgdHlwZSBmb3IgXFwndWlmLWlzLXNlbGVjdGVkXFwnIGF0dHJpYnV0ZSBmb3IgJyArXG4gICAgICAgICAgICAgICAgJzx1aWYtY29udGV4dHVhbC1tZW51LWl0ZW0gLz4uIFRoZSB2YWxpZCB0eXBlIGlzIGJvb2xlYW4uJyk7XG4gICAgICAgIH1cbiAgICAgICAgJHRyYW5zY2x1ZGUoZnVuY3Rpb24gKGNsb25lKSB7XG4gICAgICAgICAgICAkZWxlbWVudC5maW5kKCdkaXYnKS5yZXBsYWNlV2l0aChjbG9uZSk7XG4gICAgICAgIH0pO1xuICAgICAgICAkc2NvcGUuc2VsZWN0SXRlbSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIGlmICghY29udGV4dHVhbE1lbnVDb250cm9sbGVyLmlzTXVsdGlTZWxlY3Rpb25NZW51KCkpIHtcbiAgICAgICAgICAgICAgICBjb250ZXh0dWFsTWVudUNvbnRyb2xsZXIub25EZXNlbGVjdEl0ZW1zKCk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBpZiAobmcuaXNVbmRlZmluZWQoJHNjb3BlLmlzU2VsZWN0ZWQpICYmICEkc2NvcGUuaXNEaXNhYmxlZCkge1xuICAgICAgICAgICAgICAgICRzY29wZS5pc1NlbGVjdGVkID0gdHJ1ZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICRzY29wZS5pc1NlbGVjdGVkID0gISRzY29wZS5pc1NlbGVjdGVkO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKGNvbnRleHR1YWxNZW51Q29udHJvbGxlci5pc1Jvb3RNZW51KCkpIHtcbiAgICAgICAgICAgICAgICBjb250ZXh0dWFsTWVudUNvbnRyb2xsZXIub25DbG9zZU1lbnVzKCRzY29wZS4kaWQpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgaWYgKCEkc2NvcGUuaGFzQ2hpbGRNZW51KSB7XG4gICAgICAgICAgICAgICAgICAgIGNvbnRleHR1YWxNZW51Q29udHJvbGxlci5vbkNsb3NlTWVudXMobnVsbCwgdHJ1ZSk7XG4gICAgICAgICAgICAgICAgICAgIGNvbnRleHR1YWxNZW51Q29udHJvbGxlci5vbkRlc2VsZWN0SXRlbXModHJ1ZSk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgICAgICBjb250ZXh0dWFsTWVudUNvbnRyb2xsZXIub25DbG9zZU1lbnVzKCRzY29wZS4kaWQpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGlmICgkc2NvcGUuaGFzQ2hpbGRNZW51KSB7XG4gICAgICAgICAgICAgICAgJHNjb3BlLmNoaWxkTWVudUN0cmwub3Blbk1lbnUoKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGlmICghbmcuaXNVbmRlZmluZWQoJHNjb3BlLm9uQ2xpY2spKSB7XG4gICAgICAgICAgICAgICAgJHNjb3BlLm9uQ2xpY2soKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfTtcbiAgICAgICAgJHNjb3BlLiRvbigndWlmLW1lbnUtZGVzZWxlY3QnLCBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAkc2NvcGUuaXNTZWxlY3RlZCA9IGZhbHNlO1xuICAgICAgICB9KTtcbiAgICAgICAgJHNjb3BlLiRvbigndWlmLW1lbnUtY2xvc2UnLCBmdW5jdGlvbiAoZXZlbnQsIG1lbnVJdGVtSWQpIHtcbiAgICAgICAgICAgIGlmICgkc2NvcGUuaGFzQ2hpbGRNZW51ICYmICRzY29wZS4kaWQgIT09IG1lbnVJdGVtSWQpIHtcbiAgICAgICAgICAgICAgICAkc2NvcGUuY2hpbGRNZW51Q3RybC5jbG9zZU1lbnUoKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgfTtcbiAgICByZXR1cm4gQ29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlO1xufSkoKTtcbmV4cG9ydHMuQ29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlID0gQ29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlO1xudmFyIENvbnRleHR1YWxNZW51SXRlbUNvbnRyb2xsZXIgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIENvbnRleHR1YWxNZW51SXRlbUNvbnRyb2xsZXIoJHNjb3BlLCAkZWxlbWVudCkge1xuICAgICAgICB0aGlzLiRzY29wZSA9ICRzY29wZTtcbiAgICAgICAgdGhpcy4kZWxlbWVudCA9ICRlbGVtZW50O1xuICAgIH1cbiAgICBDb250ZXh0dWFsTWVudUl0ZW1Db250cm9sbGVyLnByb3RvdHlwZS5zZXRDaGlsZE1lbnUgPSBmdW5jdGlvbiAoY2hpbGRNZW51Q3RybCkge1xuICAgICAgICB0aGlzLiRzY29wZS5oYXNDaGlsZE1lbnUgPSB0cnVlO1xuICAgICAgICB0aGlzLiRzY29wZS5jaGlsZE1lbnVDdHJsID0gY2hpbGRNZW51Q3RybDtcbiAgICB9O1xuICAgIENvbnRleHR1YWxNZW51SXRlbUNvbnRyb2xsZXIuJGluamVjdCA9IFsnJHNjb3BlJywgJyRlbGVtZW50J107XG4gICAgcmV0dXJuIENvbnRleHR1YWxNZW51SXRlbUNvbnRyb2xsZXI7XG59KSgpO1xuZXhwb3J0cy5Db250ZXh0dWFsTWVudUl0ZW1Db250cm9sbGVyID0gQ29udGV4dHVhbE1lbnVJdGVtQ29udHJvbGxlcjtcbnZhciBDb250ZXh0dWFsTWVudURpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ29udGV4dHVhbE1lbnVEaXJlY3RpdmUoKSB7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMucmVxdWlyZSA9IGV4cG9ydHMuY29udGV4dHVhbE1lbnVEaXJlY3RpdmVOYW1lO1xuICAgICAgICB0aGlzLnRyYW5zY2x1ZGUgPSB0cnVlO1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gXCI8dWwgY2xhc3M9XFxcIm1zLUNvbnRleHR1YWxNZW51XFxcIiBuZy10cmFuc2NsdWRlPjwvdWw+XCI7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgICAgIHRoaXMuY29udHJvbGxlciA9IENvbnRleHR1YWxNZW51Q29udHJvbGxlcjtcbiAgICAgICAgdGhpcy5zY29wZSA9IHtcbiAgICAgICAgICAgIGlzT3BlbjogJz0/dWlmSXNPcGVuJyxcbiAgICAgICAgICAgIG11bHRpc2VsZWN0OiAnQHVpZk11bHRpc2VsZWN0J1xuICAgICAgICB9O1xuICAgIH1cbiAgICBDb250ZXh0dWFsTWVudURpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IENvbnRleHR1YWxNZW51RGlyZWN0aXZlKCk7IH07XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICBDb250ZXh0dWFsTWVudURpcmVjdGl2ZS5wcm90b3R5cGUubGluayA9IGZ1bmN0aW9uICgkc2NvcGUsICRlbGVtZW50LCAkYXR0cnMsIGNvbnRleHR1YWxNZW51Q29udHJvbGxlcikge1xuICAgICAgICB2YXIgcGFyZW50TWVudUl0ZW1DdHJsID0gJGVsZW1lbnQuY29udHJvbGxlcihleHBvcnRzLmNvbnRleHR1YWxNZW51SXRlbURpcmVjdGl2ZU5hbWUpO1xuICAgICAgICBpZiAoIW5nLmlzVW5kZWZpbmVkKHBhcmVudE1lbnVJdGVtQ3RybCkpIHtcbiAgICAgICAgICAgIHBhcmVudE1lbnVJdGVtQ3RybC5zZXRDaGlsZE1lbnUoY29udGV4dHVhbE1lbnVDb250cm9sbGVyKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAoIW5nLmlzVW5kZWZpbmVkKCRzY29wZS5tdWx0aXNlbGVjdCkgJiYgJHNjb3BlLm11bHRpc2VsZWN0LnRvTG93ZXJDYXNlKCkgPT09ICd0cnVlJykge1xuICAgICAgICAgICAgJGVsZW1lbnQuYWRkQ2xhc3MoJ21zLUNvbnRleHR1YWxNZW51LS1tdWx0aXNlbGVjdCcpO1xuICAgICAgICB9XG4gICAgfTtcbiAgICByZXR1cm4gQ29udGV4dHVhbE1lbnVEaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5Db250ZXh0dWFsTWVudURpcmVjdGl2ZSA9IENvbnRleHR1YWxNZW51RGlyZWN0aXZlO1xudmFyIENvbnRleHR1YWxNZW51Q29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ29udGV4dHVhbE1lbnVDb250cm9sbGVyKCRzY29wZSwgJGFuaW1hdGUsICRlbGVtZW50LCAkbG9nKSB7XG4gICAgICAgIHZhciBfdGhpcyA9IHRoaXM7XG4gICAgICAgIHRoaXMuJHNjb3BlID0gJHNjb3BlO1xuICAgICAgICB0aGlzLiRhbmltYXRlID0gJGFuaW1hdGU7XG4gICAgICAgIHRoaXMuJGVsZW1lbnQgPSAkZWxlbWVudDtcbiAgICAgICAgdGhpcy4kbG9nID0gJGxvZztcbiAgICAgICAgdGhpcy5pc09wZW5DbGFzc05hbWUgPSAnaXMtb3Blbic7XG4gICAgICAgIGlmIChuZy5pc1VuZGVmaW5lZCgkZWxlbWVudC5jb250cm9sbGVyKGV4cG9ydHMuY29udGV4dHVhbE1lbnVJdGVtRGlyZWN0aXZlTmFtZSkpKSB7XG4gICAgICAgICAgICAkc2NvcGUuaXNSb290TWVudSA9IHRydWU7XG4gICAgICAgIH1cbiAgICAgICAgJHNjb3BlLiR3YXRjaCgnaXNPcGVuJywgZnVuY3Rpb24gKG5ld1ZhbHVlKSB7XG4gICAgICAgICAgICBpZiAodHlwZW9mIG5ld1ZhbHVlICE9PSAnYm9vbGVhbicgJiYgbmV3VmFsdWUgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgICAgIF90aGlzLiRsb2cuZXJyb3IoJ0Vycm9yIFtuZ09mZmljZVVpRmFicmljXSBvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmNvbnRleHR1YWxtZW51IC0gaW52YWxpZCBhdHRyaWJ1dGUgdHlwZTogXFwndWlmLWlzLW9wZW5cXCcuXFxuJyArXG4gICAgICAgICAgICAgICAgICAgICdUaGUgdHlwZSBcXCcnICsgdHlwZW9mIG5ld1ZhbHVlICsgJ1xcJyBpcyBub3Qgc3VwcG9ydGVkIGFzIHZhbGlkIHR5cGUgZm9yIFxcJ3VpZi1pcy1vcGVuXFwnIGF0dHJpYnV0ZSBmb3IgJyArXG4gICAgICAgICAgICAgICAgICAgICc8dWlmLWNvbnRleHR1YWwtbWVudSAvPi4gVGhlIHZhbGlkIHR5cGUgaXMgYm9vbGVhbi4nKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgICRhbmltYXRlW25ld1ZhbHVlID8gJ2FkZENsYXNzJyA6ICdyZW1vdmVDbGFzcyddKCRlbGVtZW50LCBfdGhpcy5pc09wZW5DbGFzc05hbWUpO1xuICAgICAgICB9KTtcbiAgICB9XG4gICAgQ29udGV4dHVhbE1lbnVDb250cm9sbGVyLnByb3RvdHlwZS5vbkRlc2VsZWN0SXRlbXMgPSBmdW5jdGlvbiAoZGVzZWxlY3RQYXJlbnRNZW51cykge1xuICAgICAgICB0aGlzLiRzY29wZS4kYnJvYWRjYXN0KCd1aWYtbWVudS1kZXNlbGVjdCcpO1xuICAgICAgICBpZiAoZGVzZWxlY3RQYXJlbnRNZW51cykge1xuICAgICAgICAgICAgdGhpcy4kc2NvcGUuJGVtaXQoJ3VpZi1tZW51LWRlc2VsZWN0Jyk7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIENvbnRleHR1YWxNZW51Q29udHJvbGxlci5wcm90b3R5cGUub25DbG9zZU1lbnVzID0gZnVuY3Rpb24gKG1lbnVJdGVtVG9Ta2lwLCBjbG9zZVJvb3RNZW51KSB7XG4gICAgICAgIGlmIChjbG9zZVJvb3RNZW51KSB7XG4gICAgICAgICAgICB0aGlzLiRzY29wZS4kZW1pdCgndWlmLW1lbnUtY2xvc2UnKTtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgIHRoaXMuJHNjb3BlLiRicm9hZGNhc3QoJ3VpZi1tZW51LWNsb3NlJywgbWVudUl0ZW1Ub1NraXApO1xuICAgICAgICB9XG4gICAgfTtcbiAgICBDb250ZXh0dWFsTWVudUNvbnRyb2xsZXIucHJvdG90eXBlLm9wZW5NZW51ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB0aGlzLiRzY29wZS5pc09wZW4gPSB0cnVlO1xuICAgIH07XG4gICAgQ29udGV4dHVhbE1lbnVDb250cm9sbGVyLnByb3RvdHlwZS5jbG9zZU1lbnUgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHRoaXMuJHNjb3BlLmlzT3BlbiA9IGZhbHNlO1xuICAgIH07XG4gICAgQ29udGV4dHVhbE1lbnVDb250cm9sbGVyLnByb3RvdHlwZS5pc1Jvb3RNZW51ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUuaXNSb290TWVudTtcbiAgICB9O1xuICAgIENvbnRleHR1YWxNZW51Q29udHJvbGxlci5wcm90b3R5cGUuaXNNdWx0aVNlbGVjdGlvbk1lbnUgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIGlmIChuZy5pc1VuZGVmaW5lZCh0aGlzLiRzY29wZS5tdWx0aXNlbGVjdCkpIHtcbiAgICAgICAgICAgIHJldHVybiBmYWxzZTtcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUubXVsdGlzZWxlY3QudG9Mb3dlckNhc2UoKSA9PT0gJ3RydWUnO1xuICAgIH07XG4gICAgQ29udGV4dHVhbE1lbnVDb250cm9sbGVyLiRpbmplY3QgPSBbJyRzY29wZScsICckYW5pbWF0ZScsICckZWxlbWVudCcsICckbG9nJ107XG4gICAgcmV0dXJuIENvbnRleHR1YWxNZW51Q29udHJvbGxlcjtcbn0pKCk7XG5leHBvcnRzLkNvbnRleHR1YWxNZW51Q29udHJvbGxlciA9IENvbnRleHR1YWxNZW51Q29udHJvbGxlcjtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLmNvbnRleHR1YWxtZW51JywgW1xuICAgICdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzJ10pXG4gICAgLmRpcmVjdGl2ZShleHBvcnRzLmNvbnRleHR1YWxNZW51RGlyZWN0aXZlTmFtZSwgQ29udGV4dHVhbE1lbnVEaXJlY3RpdmUuZmFjdG9yeSgpKVxuICAgIC5kaXJlY3RpdmUoZXhwb3J0cy5jb250ZXh0dWFsTWVudUl0ZW1EaXJlY3RpdmVOYW1lLCBDb250ZXh0dWFsTWVudUl0ZW1EaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9jb250ZXh0dWFsbWVudS9jb250ZXh0dWFsTWVudS50c1xuICoqIG1vZHVsZSBpZCA9IDEyXG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgRHJvcGRvd25PcHRpb25EaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIERyb3Bkb3duT3B0aW9uRGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxsaSBjbGFzcz1cIm1zLURyb3Bkb3duLWl0ZW1cIiBuZy10cmFuc2NsdWRlPjwvbGk+JztcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gJ151aWZEcm9wZG93bic7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgfVxuICAgIERyb3Bkb3duT3B0aW9uRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgRHJvcGRvd25PcHRpb25EaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIERyb3Bkb3duT3B0aW9uRGlyZWN0aXZlLnByb3RvdHlwZS5jb21waWxlID0gZnVuY3Rpb24gKHRlbXBsYXRlRWxlbWVudCwgdGVtcGxhdGVBdHRyaWJ1dGVzLCB0cmFuc2NsdWRlKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBwb3N0OiB0aGlzLnBvc3RMaW5rXG4gICAgICAgIH07XG4gICAgfTtcbiAgICBEcm9wZG93bk9wdGlvbkRpcmVjdGl2ZS5wcm90b3R5cGUucG9zdExpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGluc3RhbmNlRWxlbWVudCwgYXR0cnMsIGRyb3Bkb3duQ29udHJvbGxlciwgdHJhbnNjbHVkZSkge1xuICAgICAgICBpZiAoIWRyb3Bkb3duQ29udHJvbGxlcikge1xuICAgICAgICAgICAgdGhyb3cgJ0Ryb3Bkb3duIGNvbnRyb2xsZXIgbm90IGZvdW5kISc7XG4gICAgICAgIH1cbiAgICAgICAgaW5zdGFuY2VFbGVtZW50XG4gICAgICAgICAgICAub24oJ2NsaWNrJywgZnVuY3Rpb24gKGV2KSB7XG4gICAgICAgICAgICBzY29wZS4kYXBwbHkoZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgICAgIGRyb3Bkb3duQ29udHJvbGxlci5zZXRWaWV3VmFsdWUoaW5zdGFuY2VFbGVtZW50LmZpbmQoJ3NwYW4nKS5odG1sKCksIGF0dHJzLnZhbHVlLCBldik7XG4gICAgICAgICAgICB9KTtcbiAgICAgICAgfSk7XG4gICAgfTtcbiAgICByZXR1cm4gRHJvcGRvd25PcHRpb25EaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5Ecm9wZG93bk9wdGlvbkRpcmVjdGl2ZSA9IERyb3Bkb3duT3B0aW9uRGlyZWN0aXZlO1xudmFyIERyb3Bkb3duQ29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gRHJvcGRvd25Db250cm9sbGVyKCRlbGVtZW50LCAkc2NvcGUpIHtcbiAgICAgICAgdGhpcy4kZWxlbWVudCA9ICRlbGVtZW50O1xuICAgICAgICB0aGlzLiRzY29wZSA9ICRzY29wZTtcbiAgICB9XG4gICAgRHJvcGRvd25Db250cm9sbGVyLnByb3RvdHlwZS5pbml0ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgc2VsZiA9IHRoaXM7XG4gICAgICAgIHRoaXMuJGVsZW1lbnQuYmluZCgnY2xpY2snLCBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICBpZiAoIXNlbGYuJHNjb3BlLmRpc2FibGVkKSB7XG4gICAgICAgICAgICAgICAgc2VsZi4kc2NvcGUuaXNPcGVuID0gIXNlbGYuJHNjb3BlLmlzT3BlbjtcbiAgICAgICAgICAgICAgICBzZWxmLiRzY29wZS4kYXBwbHkoKTtcbiAgICAgICAgICAgICAgICB2YXIgZHJvcGRvd25XaWR0aCA9IGFuZ3VsYXIuZWxlbWVudCh0aGlzLnF1ZXJ5U2VsZWN0b3IoJy5tcy1Ecm9wZG93bicpKVswXS5jbGllbnRXaWR0aDtcbiAgICAgICAgICAgICAgICBhbmd1bGFyLmVsZW1lbnQodGhpcy5xdWVyeVNlbGVjdG9yKCcubXMtRHJvcGRvd24taXRlbXMnKSlbMF0uc3R5bGUud2lkdGggPSBkcm9wZG93bldpZHRoICsgJ3B4JztcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgICAgIGlmICh0eXBlb2YgdGhpcy4kc2NvcGUubmdNb2RlbCAhPT0gJ3VuZGVmaW5lZCcgJiYgdGhpcy4kc2NvcGUubmdNb2RlbCAhPSBudWxsKSB7XG4gICAgICAgICAgICB0aGlzLiRzY29wZS5uZ01vZGVsLiRyZW5kZXIgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgdmFyIG9wdGlvbnMgPSBzZWxmLiRlbGVtZW50LmZpbmQoJ2xpJyk7XG4gICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCBvcHRpb25zLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICAgICAgICAgIHZhciBvcHRpb24gPSBvcHRpb25zW2ldO1xuICAgICAgICAgICAgICAgICAgICB2YXIgdmFsdWUgPSBvcHRpb24uZ2V0QXR0cmlidXRlKCd2YWx1ZScpO1xuICAgICAgICAgICAgICAgICAgICBpZiAodmFsdWUgPT09IHNlbGYuJHNjb3BlLm5nTW9kZWwuJHZpZXdWYWx1ZSkge1xuICAgICAgICAgICAgICAgICAgICAgICAgc2VsZi4kc2NvcGUuc2VsZWN0ZWRUaXRsZSA9IGFuZ3VsYXIuZWxlbWVudChvcHRpb24pLmZpbmQoJ3NwYW4nKS5odG1sKCk7XG4gICAgICAgICAgICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH07XG4gICAgICAgIH1cbiAgICB9O1xuICAgIERyb3Bkb3duQ29udHJvbGxlci5wcm90b3R5cGUuc2V0Vmlld1ZhbHVlID0gZnVuY3Rpb24gKHRpdGxlLCB2YWx1ZSwgZXZlbnRUeXBlKSB7XG4gICAgICAgIHRoaXMuJHNjb3BlLnNlbGVjdGVkVGl0bGUgPSB0aXRsZTtcbiAgICAgICAgdGhpcy4kc2NvcGUubmdNb2RlbC4kc2V0Vmlld1ZhbHVlKHZhbHVlLCBldmVudFR5cGUpO1xuICAgIH07XG4gICAgRHJvcGRvd25Db250cm9sbGVyLnByb3RvdHlwZS5nZXRWaWV3VmFsdWUgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIGlmICh0eXBlb2YgdGhpcy4kc2NvcGUubmdNb2RlbCAhPT0gJ3VuZGVmaW5lZCcgJiYgdGhpcy4kc2NvcGUubmdNb2RlbCAhPSBudWxsKSB7XG4gICAgICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUubmdNb2RlbC4kdmlld1ZhbHVlO1xuICAgICAgICB9XG4gICAgfTtcbiAgICBEcm9wZG93bkNvbnRyb2xsZXIuJGluamVjdCA9IFsnJGVsZW1lbnQnLCAnJHNjb3BlJ107XG4gICAgcmV0dXJuIERyb3Bkb3duQ29udHJvbGxlcjtcbn0pKCk7XG5leHBvcnRzLkRyb3Bkb3duQ29udHJvbGxlciA9IERyb3Bkb3duQ29udHJvbGxlcjtcbnZhciBEcm9wZG93bkRpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gRHJvcGRvd25EaXJlY3RpdmUoKSB7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPGRpdiBuZy1jbGljaz1cImRyb3Bkb3duQ2xpY2tcIiAnICtcbiAgICAgICAgICAgICduZy1jbGFzcz1cIntcXCdtcy1Ecm9wZG93blxcJyA6IHRydWUsIFxcJ2lzLW9wZW5cXCc6IGlzT3BlbiwgXFwnaXMtZGlzYWJsZWRcXCc6IGRpc2FibGVkfVwiIHRhYmluZGV4PVwiMFwiPicgK1xuICAgICAgICAgICAgJzxpIGNsYXNzPVwibXMtRHJvcGRvd24tY2FyZXREb3duIG1zLUljb24gbXMtSWNvbi0tY2FyZXREb3duXCI+PC9pPicgK1xuICAgICAgICAgICAgJzxzcGFuIGNsYXNzPVwibXMtRHJvcGRvd24tdGl0bGVcIj57e3NlbGVjdGVkVGl0bGV9fTwvc3Bhbj48dWwgY2xhc3M9XCJtcy1Ecm9wZG93bi1pdGVtc1wiPjxuZy10cmFuc2NsdWRlPjwvbmctdHJhbnNjbHVkZT48L3VsPjwvZGl2Pic7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMucmVxdWlyZSA9IFsndWlmRHJvcGRvd24nLCAnP25nTW9kZWwnXTtcbiAgICAgICAgdGhpcy5zY29wZSA9IHt9O1xuICAgICAgICB0aGlzLmNvbnRyb2xsZXIgPSBEcm9wZG93bkNvbnRyb2xsZXI7XG4gICAgfVxuICAgIERyb3Bkb3duRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgRHJvcGRvd25EaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIERyb3Bkb3duRGlyZWN0aXZlLnByb3RvdHlwZS5jb21waWxlID0gZnVuY3Rpb24gKHRlbXBsYXRlRWxlbWVudCwgdGVtcGxhdGVBdHRyaWJ1dGVzLCB0cmFuc2NsdWRlKSB7XG4gICAgICAgIHJldHVybiB7XG4gICAgICAgICAgICBwcmU6IHRoaXMucHJlTGlua1xuICAgICAgICB9O1xuICAgIH07XG4gICAgRHJvcGRvd25EaXJlY3RpdmUucHJvdG90eXBlLnByZUxpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGluc3RhbmNlRWxlbWVudCwgaW5zdGFuY2VBdHRyaWJ1dGVzLCBjdHJscykge1xuICAgICAgICB2YXIgZHJvcGRvd25Db250cm9sbGVyID0gY3RybHNbMF07XG4gICAgICAgIHZhciBtb2RlbENvbnRyb2xsZXIgPSBjdHJsc1sxXTtcbiAgICAgICAgc2NvcGUubmdNb2RlbCA9IG1vZGVsQ29udHJvbGxlcjtcbiAgICAgICAgZHJvcGRvd25Db250cm9sbGVyLmluaXQoKTtcbiAgICAgICAgc2NvcGUuZGlzYWJsZWQgPSAnZGlzYWJsZWQnIGluIGluc3RhbmNlQXR0cmlidXRlcztcbiAgICB9O1xuICAgIHJldHVybiBEcm9wZG93bkRpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLkRyb3Bkb3duRGlyZWN0aXZlID0gRHJvcGRvd25EaXJlY3RpdmU7XG5leHBvcnRzLm1vZHVsZSA9IG5nLm1vZHVsZSgnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5kcm9wZG93bicsIFtcbiAgICAnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cydcbl0pXG4gICAgLmRpcmVjdGl2ZSgndWlmRHJvcGRvd25PcHRpb24nLCBEcm9wZG93bk9wdGlvbkRpcmVjdGl2ZS5mYWN0b3J5KCkpXG4gICAgLmRpcmVjdGl2ZSgndWlmRHJvcGRvd24nLCBEcm9wZG93bkRpcmVjdGl2ZS5mYWN0b3J5KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2Ryb3Bkb3duL2Ryb3Bkb3duRGlyZWN0aXZlLnRzXG4gKiogbW9kdWxlIGlkID0gMTNcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyIsIid1c2Ugc3RyaWN0JztcbnZhciBuZyA9IHJlcXVpcmUoJ2FuZ3VsYXInKTtcbnZhciBpY29uRW51bV8xID0gcmVxdWlyZSgnLi9pY29uRW51bScpO1xudmFyIEljb25Db250cm9sbGVyID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBJY29uQ29udHJvbGxlcigkbG9nKSB7XG4gICAgICAgIHRoaXMuJGxvZyA9ICRsb2c7XG4gICAgfVxuICAgIEljb25Db250cm9sbGVyLiRpbmplY3QgPSBbJyRsb2cnXTtcbiAgICByZXR1cm4gSWNvbkNvbnRyb2xsZXI7XG59KSgpO1xudmFyIEljb25EaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIEljb25EaXJlY3RpdmUoKSB7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPGkgY2xhc3M9XCJtcy1JY29uIG1zLUljb24tLXt7dWlmVHlwZX19XCIgYXJpYS1oaWRkZW49XCJ0cnVlXCI+PC9pPic7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7XG4gICAgICAgICAgICB1aWZUeXBlOiAnQCdcbiAgICAgICAgfTtcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5jb250cm9sbGVyID0gSWNvbkNvbnRyb2xsZXI7XG4gICAgICAgIHRoaXMuY29udHJvbGxlckFzID0gJ2ljb24nO1xuICAgIH1cbiAgICBJY29uRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgSWNvbkRpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgSWNvbkRpcmVjdGl2ZS5wcm90b3R5cGUubGluayA9IGZ1bmN0aW9uIChzY29wZSwgaW5zdGFuY2VFbGVtZW50LCBhdHRycywgY29udHJvbGxlcikge1xuICAgICAgICBzY29wZS4kd2F0Y2goJ3VpZlR5cGUnLCBmdW5jdGlvbiAobmV3VmFsdWxlLCBvbGRWYWx1ZSkge1xuICAgICAgICAgICAgaWYgKGljb25FbnVtXzEuSWNvbkVudW1bbmV3VmFsdWxlXSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICAgICAgY29udHJvbGxlci4kbG9nLmVycm9yKCdFcnJvciBbbmdPZmZpY2VVaUZhYnJpY10gb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5pY29uIC0gVW5zdXBwb3J0ZWQgaWNvbjogJyArXG4gICAgICAgICAgICAgICAgICAgICdUaGUgaWNvbiAoXFwnJyArIHNjb3BlLnVpZlR5cGUgKyAnXFwnKSBpcyBub3Qgc3VwcG9ydGVkIGJ5IHRoZSBPZmZpY2UgVUkgRmFicmljLiAnICtcbiAgICAgICAgICAgICAgICAgICAgJ1N1cHBvcnRlZCBvcHRpb25zIGFyZSBsaXN0ZWQgaGVyZTogJyArXG4gICAgICAgICAgICAgICAgICAgICdodHRwczovL2dpdGh1Yi5jb20vbmdPZmZpY2VVSUZhYnJpYy9uZy1vZmZpY2V1aWZhYnJpYy9ibG9iL21hc3Rlci9zcmMvY29tcG9uZW50cy9pY29uL2ljb25FbnVtLnRzJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH0pO1xuICAgIH07XG4gICAgO1xuICAgIHJldHVybiBJY29uRGlyZWN0aXZlO1xufSkoKTtcbmV4cG9ydHMuSWNvbkRpcmVjdGl2ZSA9IEljb25EaXJlY3RpdmU7XG5leHBvcnRzLm1vZHVsZSA9IG5nLm1vZHVsZSgnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5pY29uJywgW1xuICAgICdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzJ1xuXSlcbiAgICAuZGlyZWN0aXZlKCd1aWZJY29uJywgSWNvbkRpcmVjdGl2ZS5mYWN0b3J5KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2ljb24vaWNvbkRpcmVjdGl2ZS50c1xuICoqIG1vZHVsZSBpZCA9IDE0XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG4oZnVuY3Rpb24gKEljb25FbnVtKSB7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhbGVydFwiXSA9IDBdID0gXCJhbGVydFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYWxlcnQyXCJdID0gMV0gPSBcImFsZXJ0MlwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYWxlcnRPdXRsaW5lXCJdID0gMl0gPSBcImFsZXJ0T3V0bGluZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYXJyb3dEb3duXCJdID0gM10gPSBcImFycm93RG93blwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYXJyb3dEb3duMlwiXSA9IDRdID0gXCJhcnJvd0Rvd24yXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhcnJvd0Rvd25MZWZ0XCJdID0gNV0gPSBcImFycm93RG93bkxlZnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImFycm93RG93blJpZ2h0XCJdID0gNl0gPSBcImFycm93RG93blJpZ2h0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhcnJvd0xlZnRcIl0gPSA3XSA9IFwiYXJyb3dMZWZ0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhcnJvd1JpZ2h0XCJdID0gOF0gPSBcImFycm93UmlnaHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImFycm93VXBcIl0gPSA5XSA9IFwiYXJyb3dVcFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYXJyb3dVcDJcIl0gPSAxMF0gPSBcImFycm93VXAyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhcnJvd1VwTGVmdFwiXSA9IDExXSA9IFwiYXJyb3dVcExlZnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImFycm93VXBSaWdodFwiXSA9IDEyXSA9IFwiYXJyb3dVcFJpZ2h0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhc2NlbmRpbmdcIl0gPSAxM10gPSBcImFzY2VuZGluZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYXRcIl0gPSAxNF0gPSBcImF0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJhdHRhY2htZW50XCJdID0gMTVdID0gXCJhdHRhY2htZW50XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJiYWdcIl0gPSAxNl0gPSBcImJhZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYmFsbG9vblwiXSA9IDE3XSA9IFwiYmFsbG9vblwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYmVsbFwiXSA9IDE4XSA9IFwiYmVsbFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYm9hcmRzXCJdID0gMTldID0gXCJib2FyZHNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImJvbGRcIl0gPSAyMF0gPSBcImJvbGRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImJvb2ttYXJrXCJdID0gMjFdID0gXCJib29rbWFya1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYm9va3NcIl0gPSAyMl0gPSBcImJvb2tzXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJicmllZmNhc2VcIl0gPSAyM10gPSBcImJyaWVmY2FzZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiYnVuZGxlXCJdID0gMjRdID0gXCJidW5kbGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNha2VcIl0gPSAyNV0gPSBcImNha2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNhbGVuZGFyXCJdID0gMjZdID0gXCJjYWxlbmRhclwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2FsZW5kYXJEYXlcIl0gPSAyN10gPSBcImNhbGVuZGFyRGF5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYWxlbmRhclB1YmxpY1wiXSA9IDI4XSA9IFwiY2FsZW5kYXJQdWJsaWNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNhbGVuZGFyV2Vla1wiXSA9IDI5XSA9IFwiY2FsZW5kYXJXZWVrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYWxlbmRhcldvcmtXZWVrXCJdID0gMzBdID0gXCJjYWxlbmRhcldvcmtXZWVrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYW1lcmFcIl0gPSAzMV0gPSBcImNhbWVyYVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2FyXCJdID0gMzJdID0gXCJjYXJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNhcmV0RG93blwiXSA9IDMzXSA9IFwiY2FyZXREb3duXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldERvd25MZWZ0XCJdID0gMzRdID0gXCJjYXJldERvd25MZWZ0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldERvd25PdXRsaW5lXCJdID0gMzVdID0gXCJjYXJldERvd25PdXRsaW5lXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldERvd25SaWdodFwiXSA9IDM2XSA9IFwiY2FyZXREb3duUmlnaHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNhcmV0TGVmdFwiXSA9IDM3XSA9IFwiY2FyZXRMZWZ0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldExlZnRPdXRsaW5lXCJdID0gMzhdID0gXCJjYXJldExlZnRPdXRsaW5lXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldFJpZ2h0XCJdID0gMzldID0gXCJjYXJldFJpZ2h0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldFJpZ2h0T3V0bGluZVwiXSA9IDQwXSA9IFwiY2FyZXRSaWdodE91dGxpbmVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNhcmV0VXBcIl0gPSA0MV0gPSBcImNhcmV0VXBcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNhcmV0VXBMZWZ0XCJdID0gNDJdID0gXCJjYXJldFVwTGVmdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2FyZXRVcE91dGxpbmVcIl0gPSA0M10gPSBcImNhcmV0VXBPdXRsaW5lXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjYXJldFVwUmlnaHRcIl0gPSA0NF0gPSBcImNhcmV0VXBSaWdodFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2FydFwiXSA9IDQ1XSA9IFwiY2FydFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2F0XCJdID0gNDZdID0gXCJjYXRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoYXJ0XCJdID0gNDddID0gXCJjaGFydFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hhdFwiXSA9IDQ4XSA9IFwiY2hhdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hhdEFkZFwiXSA9IDQ5XSA9IFwiY2hhdEFkZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hlY2tcIl0gPSA1MF0gPSBcImNoZWNrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaGVja2JveFwiXSA9IDUxXSA9IFwiY2hlY2tib3hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZWNrYm94Q2hlY2tcIl0gPSA1Ml0gPSBcImNoZWNrYm94Q2hlY2tcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZWNrYm94RW1wdHlcIl0gPSA1M10gPSBcImNoZWNrYm94RW1wdHlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZWNrYm94TWl4ZWRcIl0gPSA1NF0gPSBcImNoZWNrYm94TWl4ZWRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZWNrUGVvcGxlXCJdID0gNTVdID0gXCJjaGVja1Blb3BsZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hldnJvbkRvd25cIl0gPSA1Nl0gPSBcImNoZXZyb25Eb3duXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaGV2cm9uTGVmdFwiXSA9IDU3XSA9IFwiY2hldnJvbkxlZnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25SaWdodFwiXSA9IDU4XSA9IFwiY2hldnJvblJpZ2h0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaGV2cm9uc0Rvd25cIl0gPSA1OV0gPSBcImNoZXZyb25zRG93blwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hldnJvbnNMZWZ0XCJdID0gNjBdID0gXCJjaGV2cm9uc0xlZnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25zUmlnaHRcIl0gPSA2MV0gPSBcImNoZXZyb25zUmlnaHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25zVXBcIl0gPSA2Ml0gPSBcImNoZXZyb25zVXBcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25UaGlja0Rvd25cIl0gPSA2M10gPSBcImNoZXZyb25UaGlja0Rvd25cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25UaGlja0xlZnRcIl0gPSA2NF0gPSBcImNoZXZyb25UaGlja0xlZnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25UaGlja1JpZ2h0XCJdID0gNjVdID0gXCJjaGV2cm9uVGhpY2tSaWdodFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hldnJvblRoaWNrVXBcIl0gPSA2Nl0gPSBcImNoZXZyb25UaGlja1VwXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaGV2cm9uVGhpbkRvd25cIl0gPSA2N10gPSBcImNoZXZyb25UaGluRG93blwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2hldnJvblRoaW5MZWZ0XCJdID0gNjhdID0gXCJjaGV2cm9uVGhpbkxlZnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25UaGluUmlnaHRcIl0gPSA2OV0gPSBcImNoZXZyb25UaGluUmlnaHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25UaGluVXBcIl0gPSA3MF0gPSBcImNoZXZyb25UaGluVXBcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNoZXZyb25VcFwiXSA9IDcxXSA9IFwiY2hldnJvblVwXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaXJjbGVcIl0gPSA3Ml0gPSBcImNpcmNsZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlQmFsbFwiXSA9IDczXSA9IFwiY2lyY2xlQmFsbFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlQmFsbG9vbnNcIl0gPSA3NF0gPSBcImNpcmNsZUJhbGxvb25zXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaXJjbGVDYXJcIl0gPSA3NV0gPSBcImNpcmNsZUNhclwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlQ2F0XCJdID0gNzZdID0gXCJjaXJjbGVDYXRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNpcmNsZUNvZmZlZVwiXSA9IDc3XSA9IFwiY2lyY2xlQ29mZmVlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaXJjbGVEb2dcIl0gPSA3OF0gPSBcImNpcmNsZURvZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlRW1wdHlcIl0gPSA3OV0gPSBcImNpcmNsZUVtcHR5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaXJjbGVGaWxsXCJdID0gODBdID0gXCJjaXJjbGVGaWxsXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjaXJjbGVGaWxsZWRcIl0gPSA4MV0gPSBcImNpcmNsZUZpbGxlZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlSGFsZkZpbGxlZFwiXSA9IDgyXSA9IFwiY2lyY2xlSGFsZkZpbGxlZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlSW5mb1wiXSA9IDgzXSA9IFwiY2lyY2xlSW5mb1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlTGlnaHRuaW5nXCJdID0gODRdID0gXCJjaXJjbGVMaWdodG5pbmdcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNpcmNsZVBpbGxcIl0gPSA4NV0gPSBcImNpcmNsZVBpbGxcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNpcmNsZVBsYW5lXCJdID0gODZdID0gXCJjaXJjbGVQbGFuZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlUGx1c1wiXSA9IDg3XSA9IFwiY2lyY2xlUGx1c1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2lyY2xlUG9vZGxlXCJdID0gODhdID0gXCJjaXJjbGVQb29kbGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNpcmNsZVVuZmlsbGVkXCJdID0gODldID0gXCJjaXJjbGVVbmZpbGxlZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2xhc3NOb3RlYm9va1wiXSA9IDkwXSA9IFwiY2xhc3NOb3RlYm9va1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2xhc3Nyb29tXCJdID0gOTFdID0gXCJjbGFzc3Jvb21cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNsb2NrXCJdID0gOTJdID0gXCJjbG9ja1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY2x1dHRlclwiXSA9IDkzXSA9IFwiY2x1dHRlclwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY29mZmVlXCJdID0gOTRdID0gXCJjb2ZmZWVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNvbGxhcHNlXCJdID0gOTVdID0gXCJjb2xsYXBzZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY29uZmxpY3RcIl0gPSA5Nl0gPSBcImNvbmZsaWN0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjb250YWN0XCJdID0gOTddID0gXCJjb250YWN0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjb250YWN0Rm9ybVwiXSA9IDk4XSA9IFwiY29udGFjdEZvcm1cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNvbnRhY3RQdWJsaWNcIl0gPSA5OV0gPSBcImNvbnRhY3RQdWJsaWNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImNvcHlcIl0gPSAxMDBdID0gXCJjb3B5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJjcmVkaXRDYXJkXCJdID0gMTAxXSA9IFwiY3JlZGl0Q2FyZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiY3JlZGl0Q2FyZE91dGxpbmVcIl0gPSAxMDJdID0gXCJjcmVkaXRDYXJkT3V0bGluZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZGFzaGJvYXJkXCJdID0gMTAzXSA9IFwiZGFzaGJvYXJkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJkZXNjZW5kaW5nXCJdID0gMTA0XSA9IFwiZGVzY2VuZGluZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZGVza3RvcFwiXSA9IDEwNV0gPSBcImRlc2t0b3BcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImRldmljZVdpcGVcIl0gPSAxMDZdID0gXCJkZXZpY2VXaXBlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJkaWFscGFkXCJdID0gMTA3XSA9IFwiZGlhbHBhZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZGlyZWN0aW9uc1wiXSA9IDEwOF0gPSBcImRpcmVjdGlvbnNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImRvY3VtZW50XCJdID0gMTA5XSA9IFwiZG9jdW1lbnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImRvY3VtZW50QWRkXCJdID0gMTEwXSA9IFwiZG9jdW1lbnRBZGRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImRvY3VtZW50Rm9yd2FyZFwiXSA9IDExMV0gPSBcImRvY3VtZW50Rm9yd2FyZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZG9jdW1lbnRMYW5kc2NhcGVcIl0gPSAxMTJdID0gXCJkb2N1bWVudExhbmRzY2FwZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZG9jdW1lbnRQREZcIl0gPSAxMTNdID0gXCJkb2N1bWVudFBERlwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZG9jdW1lbnRSZXBseVwiXSA9IDExNF0gPSBcImRvY3VtZW50UmVwbHlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImRvY3VtZW50c1wiXSA9IDExNV0gPSBcImRvY3VtZW50c1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZG9jdW1lbnRTZWFyY2hcIl0gPSAxMTZdID0gXCJkb2N1bWVudFNlYXJjaFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZG9nXCJdID0gMTE3XSA9IFwiZG9nXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJkb2dBbHRcIl0gPSAxMThdID0gXCJkb2dBbHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImRvdFwiXSA9IDExOV0gPSBcImRvdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZG93bmxvYWRcIl0gPSAxMjBdID0gXCJkb3dubG9hZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZHJtXCJdID0gMTIxXSA9IFwiZHJtXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJkcm9wXCJdID0gMTIyXSA9IFwiZHJvcFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZHJvcGRvd25cIl0gPSAxMjNdID0gXCJkcm9wZG93blwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZWRpdEJveFwiXSA9IDEyNF0gPSBcImVkaXRCb3hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImVsbGlwc2lzXCJdID0gMTI1XSA9IFwiZWxsaXBzaXNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImVtYmVkXCJdID0gMTI2XSA9IFwiZW1iZWRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImV2ZW50XCJdID0gMTI3XSA9IFwiZXZlbnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImV2ZW50Q2FuY2VsXCJdID0gMTI4XSA9IFwiZXZlbnRDYW5jZWxcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImV2ZW50SW5mb1wiXSA9IDEyOV0gPSBcImV2ZW50SW5mb1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZXZlbnRSZWN1cnJpbmdcIl0gPSAxMzBdID0gXCJldmVudFJlY3VycmluZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZXZlbnRTaGFyZVwiXSA9IDEzMV0gPSBcImV2ZW50U2hhcmVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImV4Y2xhbWF0aW9uXCJdID0gMTMyXSA9IFwiZXhjbGFtYXRpb25cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImV4cGFuZFwiXSA9IDEzM10gPSBcImV4cGFuZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZXllXCJdID0gMTM0XSA9IFwiZXllXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmYXZvcml0ZXNcIl0gPSAxMzVdID0gXCJmYXZvcml0ZXNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZheFwiXSA9IDEzNl0gPSBcImZheFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZmllbGRNYWlsXCJdID0gMTM3XSA9IFwiZmllbGRNYWlsXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmaWVsZE51bWJlclwiXSA9IDEzOF0gPSBcImZpZWxkTnVtYmVyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmaWVsZFRleHRcIl0gPSAxMzldID0gXCJmaWVsZFRleHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZpZWxkVGV4dEJveFwiXSA9IDE0MF0gPSBcImZpZWxkVGV4dEJveFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZmlsZURvY3VtZW50XCJdID0gMTQxXSA9IFwiZmlsZURvY3VtZW50XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmaWxlSW1hZ2VcIl0gPSAxNDJdID0gXCJmaWxlSW1hZ2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZpbGVQREZcIl0gPSAxNDNdID0gXCJmaWxlUERGXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmaWx0ZXJcIl0gPSAxNDRdID0gXCJmaWx0ZXJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZpbHRlckNsZWFyXCJdID0gMTQ1XSA9IFwiZmlsdGVyQ2xlYXJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZpcnN0QWlkXCJdID0gMTQ2XSA9IFwiZmlyc3RBaWRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZsYWdcIl0gPSAxNDddID0gXCJmbGFnXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmb2xkZXJcIl0gPSAxNDhdID0gXCJmb2xkZXJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZvbGRlck1vdmVcIl0gPSAxNDldID0gXCJmb2xkZXJNb3ZlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmb2xkZXJQdWJsaWNcIl0gPSAxNTBdID0gXCJmb2xkZXJQdWJsaWNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZvbGRlclNlYXJjaFwiXSA9IDE1MV0gPSBcImZvbGRlclNlYXJjaFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZm9udENvbG9yXCJdID0gMTUyXSA9IFwiZm9udENvbG9yXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmb250RGVjcmVhc2VcIl0gPSAxNTNdID0gXCJmb250RGVjcmVhc2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImZvbnRJbmNyZWFzZVwiXSA9IDE1NF0gPSBcImZvbnRJbmNyZWFzZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZnJvd255XCJdID0gMTU1XSA9IFwiZnJvd255XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJmdWxsc2NyZWVuXCJdID0gMTU2XSA9IFwiZnVsbHNjcmVlblwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiZ2VhclwiXSA9IDE1N10gPSBcImdlYXJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImdsYXNzZXNcIl0gPSAxNThdID0gXCJnbGFzc2VzXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJnbG9iZVwiXSA9IDE1OV0gPSBcImdsb2JlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJncmFwaFwiXSA9IDE2MF0gPSBcImdyYXBoXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJncm91cFwiXSA9IDE2MV0gPSBcImdyb3VwXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJoZWFkZXJcIl0gPSAxNjJdID0gXCJoZWFkZXJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImhlYXJ0XCJdID0gMTYzXSA9IFwiaGVhcnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImhlYXJ0RW1wdHlcIl0gPSAxNjRdID0gXCJoZWFydEVtcHR5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJoaWRlXCJdID0gMTY1XSA9IFwiaGlkZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiaG9tZVwiXSA9IDE2Nl0gPSBcImhvbWVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImluYm94Q2hlY2tcIl0gPSAxNjddID0gXCJpbmJveENoZWNrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJpbmZvXCJdID0gMTY4XSA9IFwiaW5mb1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wiaW5mb0NpcmNsZVwiXSA9IDE2OV0gPSBcImluZm9DaXJjbGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIml0YWxpY1wiXSA9IDE3MF0gPSBcIml0YWxpY1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wia2V5XCJdID0gMTcxXSA9IFwia2V5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJsYXRlXCJdID0gMTcyXSA9IFwibGF0ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibGlmZXNhdmVyXCJdID0gMTczXSA9IFwibGlmZXNhdmVyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJsaWZlc2F2ZXJMb2NrXCJdID0gMTc0XSA9IFwibGlmZXNhdmVyTG9ja1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibGlnaHRCdWxiXCJdID0gMTc1XSA9IFwibGlnaHRCdWxiXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJsaWdodG5pbmdcIl0gPSAxNzZdID0gXCJsaWdodG5pbmdcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImxpbmtcIl0gPSAxNzddID0gXCJsaW5rXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJsaW5rUmVtb3ZlXCJdID0gMTc4XSA9IFwibGlua1JlbW92ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibGlzdEJ1bGxldHNcIl0gPSAxNzldID0gXCJsaXN0QnVsbGV0c1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibGlzdENoZWNrXCJdID0gMTgwXSA9IFwibGlzdENoZWNrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJsaXN0Q2hlY2tib3hcIl0gPSAxODFdID0gXCJsaXN0Q2hlY2tib3hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImxpc3RHcm91cFwiXSA9IDE4Ml0gPSBcImxpc3RHcm91cFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibGlzdEdyb3VwMlwiXSA9IDE4M10gPSBcImxpc3RHcm91cDJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcImxpc3ROdW1iZXJlZFwiXSA9IDE4NF0gPSBcImxpc3ROdW1iZXJlZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibG9ja1wiXSA9IDE4NV0gPSBcImxvY2tcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1haWxcIl0gPSAxODZdID0gXCJtYWlsXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsQ2hlY2tcIl0gPSAxODddID0gXCJtYWlsQ2hlY2tcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1haWxEb3duXCJdID0gMTg4XSA9IFwibWFpbERvd25cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1haWxFZGl0XCJdID0gMTg5XSA9IFwibWFpbEVkaXRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1haWxFbXB0eVwiXSA9IDE5MF0gPSBcIm1haWxFbXB0eVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibWFpbEVycm9yXCJdID0gMTkxXSA9IFwibWFpbEVycm9yXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsT3BlblwiXSA9IDE5Ml0gPSBcIm1haWxPcGVuXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsUGF1c2VcIl0gPSAxOTNdID0gXCJtYWlsUGF1c2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1haWxQdWJsaWNcIl0gPSAxOTRdID0gXCJtYWlsUHVibGljXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsUmVhZFwiXSA9IDE5NV0gPSBcIm1haWxSZWFkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsU2VuZFwiXSA9IDE5Nl0gPSBcIm1haWxTZW5kXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsU3luY1wiXSA9IDE5N10gPSBcIm1haWxTeW5jXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtYWlsVW5yZWFkXCJdID0gMTk4XSA9IFwibWFpbFVucmVhZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibWFwTWFya2VyXCJdID0gMTk5XSA9IFwibWFwTWFya2VyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtZWFsXCJdID0gMjAwXSA9IFwibWVhbFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibWVudVwiXSA9IDIwMV0gPSBcIm1lbnVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1lbnUyXCJdID0gMjAyXSA9IFwibWVudTJcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1lcmdlXCJdID0gMjAzXSA9IFwibWVyZ2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1ldGFkYXRhXCJdID0gMjA0XSA9IFwibWV0YWRhdGFcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm1pY3JvcGhvbmVcIl0gPSAyMDVdID0gXCJtaWNyb3Bob25lXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtaW5pYXR1cmVzXCJdID0gMjA2XSA9IFwibWluaWF0dXJlc1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibWludXNcIl0gPSAyMDddID0gXCJtaW51c1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibW9iaWxlXCJdID0gMjA4XSA9IFwibW9iaWxlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtb25leVwiXSA9IDIwOV0gPSBcIm1vbmV5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJtb3ZlXCJdID0gMjEwXSA9IFwibW92ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibXVsdGlDaG9pY2VcIl0gPSAyMTFdID0gXCJtdWx0aUNob2ljZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibXVzaWNcIl0gPSAyMTJdID0gXCJtdXNpY1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibmF2aWdhdGVcIl0gPSAyMTNdID0gXCJuYXZpZ2F0ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibmV3XCJdID0gMjE0XSA9IFwibmV3XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJuZXdzZmVlZFwiXSA9IDIxNV0gPSBcIm5ld3NmZWVkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJub3RlXCJdID0gMjE2XSA9IFwibm90ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibm90ZWJvb2tcIl0gPSAyMTddID0gXCJub3RlYm9va1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibm90ZUVkaXRcIl0gPSAyMThdID0gXCJub3RlRWRpdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibm90ZUZvcndhcmRcIl0gPSAyMTldID0gXCJub3RlRm9yd2FyZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wibm90ZVJlcGx5XCJdID0gMjIwXSA9IFwibm90ZVJlcGx5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJub3RSZWN1cnJpbmdcIl0gPSAyMjFdID0gXCJub3RSZWN1cnJpbmdcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm9ubGluZUFkZFwiXSA9IDIyMl0gPSBcIm9ubGluZUFkZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wib25saW5lSm9pblwiXSA9IDIyM10gPSBcIm9ubGluZUpvaW5cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm9vZlJlcGx5XCJdID0gMjI0XSA9IFwib29mUmVwbHlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIm9yZ1wiXSA9IDIyNV0gPSBcIm9yZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGFnZVwiXSA9IDIyNl0gPSBcInBhZ2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBhaW50XCJdID0gMjI3XSA9IFwicGFpbnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBhbmVsXCJdID0gMjI4XSA9IFwicGFuZWxcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBhcnRuZXJcIl0gPSAyMjldID0gXCJwYXJ0bmVyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwYXVzZVwiXSA9IDIzMF0gPSBcInBhdXNlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwZW5jaWxcIl0gPSAyMzFdID0gXCJwZW5jaWxcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBlb3BsZVwiXSA9IDIzMl0gPSBcInBlb3BsZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGVvcGxlQWRkXCJdID0gMjMzXSA9IFwicGVvcGxlQWRkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwZW9wbGVDaGVja1wiXSA9IDIzNF0gPSBcInBlb3BsZUNoZWNrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwZW9wbGVFcnJvclwiXSA9IDIzNV0gPSBcInBlb3BsZUVycm9yXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwZW9wbGVQYXVzZVwiXSA9IDIzNl0gPSBcInBlb3BsZVBhdXNlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwZW9wbGVSZW1vdmVcIl0gPSAyMzddID0gXCJwZW9wbGVSZW1vdmVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBlb3BsZVNlY3VyaXR5XCJdID0gMjM4XSA9IFwicGVvcGxlU2VjdXJpdHlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBlb3BsZVN5bmNcIl0gPSAyMzldID0gXCJwZW9wbGVTeW5jXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwZXJzb25cIl0gPSAyNDBdID0gXCJwZXJzb25cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBlcnNvbkFkZFwiXSA9IDI0MV0gPSBcInBlcnNvbkFkZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGVyc29uUmVtb3ZlXCJdID0gMjQyXSA9IFwicGVyc29uUmVtb3ZlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwaG9uZVwiXSA9IDI0M10gPSBcInBob25lXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwaG9uZUFkZFwiXSA9IDI0NF0gPSBcInBob25lQWRkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwaG9uZVRyYW5zZmVyXCJdID0gMjQ1XSA9IFwicGhvbmVUcmFuc2ZlclwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGljdHVyZVwiXSA9IDI0Nl0gPSBcInBpY3R1cmVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBpY3R1cmVBZGRcIl0gPSAyNDddID0gXCJwaWN0dXJlQWRkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwaWN0dXJlRWRpdFwiXSA9IDI0OF0gPSBcInBpY3R1cmVFZGl0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwaWN0dXJlUmVtb3ZlXCJdID0gMjQ5XSA9IFwicGljdHVyZVJlbW92ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGlsbFwiXSA9IDI1MF0gPSBcInBpbGxcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBpbkRvd25cIl0gPSAyNTFdID0gXCJwaW5Eb3duXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwaW5MZWZ0XCJdID0gMjUyXSA9IFwicGluTGVmdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGxhY2Vob2xkZXJcIl0gPSAyNTNdID0gXCJwbGFjZWhvbGRlclwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGxhbmVcIl0gPSAyNTRdID0gXCJwbGFuZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicGxheVwiXSA9IDI1NV0gPSBcInBsYXlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBsdXNcIl0gPSAyNTZdID0gXCJwbHVzXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwbHVzMlwiXSA9IDI1N10gPSBcInBsdXMyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJwb2ludEl0ZW1cIl0gPSAyNThdID0gXCJwb2ludEl0ZW1cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInBvcG91dFwiXSA9IDI1OV0gPSBcInBvcG91dFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicG9zdFwiXSA9IDI2MF0gPSBcInBvc3RcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInByaW50XCJdID0gMjYxXSA9IFwicHJpbnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInByb3RlY3Rpb25DZW50ZXJcIl0gPSAyNjJdID0gXCJwcm90ZWN0aW9uQ2VudGVyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJxdWVzdGlvblwiXSA9IDI2M10gPSBcInF1ZXN0aW9uXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJxdWVzdGlvblJldmVyc2VcIl0gPSAyNjRdID0gXCJxdWVzdGlvblJldmVyc2VcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInF1b3RlXCJdID0gMjY1XSA9IFwicXVvdGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInJhZGlvQnV0dG9uXCJdID0gMjY2XSA9IFwicmFkaW9CdXR0b25cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInJlYWN0aXZhdGVcIl0gPSAyNjddID0gXCJyZWFjdGl2YXRlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJyZWNlaXB0Q2hlY2tcIl0gPSAyNjhdID0gXCJyZWNlaXB0Q2hlY2tcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInJlY2VpcHRGb3J3YXJkXCJdID0gMjY5XSA9IFwicmVjZWlwdEZvcndhcmRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInJlY2VpcHRSZXBseVwiXSA9IDI3MF0gPSBcInJlY2VpcHRSZXBseVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicmVmcmVzaFwiXSA9IDI3MV0gPSBcInJlZnJlc2hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInJlbG9hZFwiXSA9IDI3Ml0gPSBcInJlbG9hZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicmVwbHlcIl0gPSAyNzNdID0gXCJyZXBseVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicmVwbHlBbGxcIl0gPSAyNzRdID0gXCJyZXBseUFsbFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicmVwbHlBbGxBbHRcIl0gPSAyNzVdID0gXCJyZXBseUFsbEFsdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicmVwbHlBbHRcIl0gPSAyNzZdID0gXCJyZXBseUFsdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wicmliYm9uXCJdID0gMjc3XSA9IFwicmliYm9uXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJyb29tXCJdID0gMjc4XSA9IFwicm9vbVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic2F2ZVwiXSA9IDI3OV0gPSBcInNhdmVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInNjaGVkdWxpbmdcIl0gPSAyODBdID0gXCJzY2hlZHVsaW5nXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzZWFyY2hcIl0gPSAyODFdID0gXCJzZWFyY2hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInNlY3Rpb25cIl0gPSAyODJdID0gXCJzZWN0aW9uXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzZWN0aW9uc1wiXSA9IDI4M10gPSBcInNlY3Rpb25zXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzZXR0aW5nc1wiXSA9IDI4NF0gPSBcInNldHRpbmdzXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzaGFyZVwiXSA9IDI4NV0gPSBcInNoYXJlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzaGllbGRcIl0gPSAyODZdID0gXCJzaGllbGRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInNpdGVzXCJdID0gMjg3XSA9IFwic2l0ZXNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInNtaWxleVwiXSA9IDI4OF0gPSBcInNtaWxleVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic29jY2VyXCJdID0gMjg5XSA9IFwic29jY2VyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzb2NpYWxMaXN0ZW5pbmdcIl0gPSAyOTBdID0gXCJzb2NpYWxMaXN0ZW5pbmdcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInNvcnRcIl0gPSAyOTFdID0gXCJzb3J0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzb3J0TGluZXNcIl0gPSAyOTJdID0gXCJzb3J0TGluZXNcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInNwbGl0XCJdID0gMjkzXSA9IFwic3BsaXRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInN0YXJcIl0gPSAyOTRdID0gXCJzdGFyXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzdGFyRW1wdHlcIl0gPSAyOTVdID0gXCJzdGFyRW1wdHlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInN0b3B3YXRjaFwiXSA9IDI5Nl0gPSBcInN0b3B3YXRjaFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic3RvcnlcIl0gPSAyOTddID0gXCJzdG9yeVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic3R5bGVSZW1vdmVcIl0gPSAyOThdID0gXCJzdHlsZVJlbW92ZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic3Vic2NyaWJlXCJdID0gMjk5XSA9IFwic3Vic2NyaWJlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJzdW5cIl0gPSAzMDBdID0gXCJzdW5cIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInN1bkFkZFwiXSA9IDMwMV0gPSBcInN1bkFkZFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic3VuUXVlc3Rpb25cIl0gPSAzMDJdID0gXCJzdW5RdWVzdGlvblwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1wic3VwcG9ydFwiXSA9IDMwM10gPSBcInN1cHBvcnRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRhYmxlXCJdID0gMzA0XSA9IFwidGFibGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRhYmxldFwiXSA9IDMwNV0gPSBcInRhYmxldFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widGFnXCJdID0gMzA2XSA9IFwidGFnXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ0YXNrUmVjdXJyaW5nXCJdID0gMzA3XSA9IFwidGFza1JlY3VycmluZ1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widGFza3NcIl0gPSAzMDhdID0gXCJ0YXNrc1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widGVhbXdvcmtcIl0gPSAzMDldID0gXCJ0ZWFtd29ya1wiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widGV4dFwiXSA9IDMxMF0gPSBcInRleHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRleHRCb3hcIl0gPSAzMTFdID0gXCJ0ZXh0Qm94XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ0aWxlXCJdID0gMzEyXSA9IFwidGlsZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widGltZWxpbmVcIl0gPSAzMTNdID0gXCJ0aW1lbGluZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widG9kYXlcIl0gPSAzMTRdID0gXCJ0b2RheVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widG9nZ2xlXCJdID0gMzE1XSA9IFwidG9nZ2xlXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ0b2dnbGVNaWRkbGVcIl0gPSAzMTZdID0gXCJ0b2dnbGVNaWRkbGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRvdWNoXCJdID0gMzE3XSA9IFwidG91Y2hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRyYXNoXCJdID0gMzE4XSA9IFwidHJhc2hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRyaWFuZ2xlRG93blwiXSA9IDMxOV0gPSBcInRyaWFuZ2xlRG93blwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widHJpYW5nbGVFbXB0eURvd25cIl0gPSAzMjBdID0gXCJ0cmlhbmdsZUVtcHR5RG93blwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widHJpYW5nbGVFbXB0eUxlZnRcIl0gPSAzMjFdID0gXCJ0cmlhbmdsZUVtcHR5TGVmdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widHJpYW5nbGVFbXB0eVJpZ2h0XCJdID0gMzIyXSA9IFwidHJpYW5nbGVFbXB0eVJpZ2h0XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ0cmlhbmdsZUVtcHR5VXBcIl0gPSAzMjNdID0gXCJ0cmlhbmdsZUVtcHR5VXBcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRyaWFuZ2xlTGVmdFwiXSA9IDMyNF0gPSBcInRyaWFuZ2xlTGVmdFwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widHJpYW5nbGVSaWdodFwiXSA9IDMyNV0gPSBcInRyaWFuZ2xlUmlnaHRcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInRyaWFuZ2xlVXBcIl0gPSAzMjZdID0gXCJ0cmlhbmdsZVVwXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ0cm9waHlcIl0gPSAzMjddID0gXCJ0cm9waHlcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInVuZGVybGluZVwiXSA9IDMyOF0gPSBcInVuZGVybGluZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widW5zdWJzY3JpYmVcIl0gPSAzMjldID0gXCJ1bnN1YnNjcmliZVwiO1xuICAgIEljb25FbnVtW0ljb25FbnVtW1widXBsb2FkXCJdID0gMzMwXSA9IFwidXBsb2FkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ2aWRlb1wiXSA9IDMzMV0gPSBcInZpZGVvXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ2b2ljZW1haWxcIl0gPSAzMzJdID0gXCJ2b2ljZW1haWxcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInZvaWNlbWFpbEZvcndhcmRcIl0gPSAzMzNdID0gXCJ2b2ljZW1haWxGb3J3YXJkXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ2b2ljZW1haWxSZXBseVwiXSA9IDMzNF0gPSBcInZvaWNlbWFpbFJlcGx5XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ3YWZmbGVcIl0gPSAzMzVdID0gXCJ3YWZmbGVcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcIndvcmtcIl0gPSAzMzZdID0gXCJ3b3JrXCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ3cmVuY2hcIl0gPSAzMzddID0gXCJ3cmVuY2hcIjtcbiAgICBJY29uRW51bVtJY29uRW51bVtcInhcIl0gPSAzMzhdID0gXCJ4XCI7XG4gICAgSWNvbkVudW1bSWNvbkVudW1bXCJ4Q2lyY2xlXCJdID0gMzM5XSA9IFwieENpcmNsZVwiO1xufSkoZXhwb3J0cy5JY29uRW51bSB8fCAoZXhwb3J0cy5JY29uRW51bSA9IHt9KSk7XG52YXIgSWNvbkVudW0gPSBleHBvcnRzLkljb25FbnVtO1xuO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL2ljb24vaWNvbkVudW0udHNcbiAqKiBtb2R1bGUgaWQgPSAxNVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xudmFyIG5nID0gcmVxdWlyZSgnYW5ndWxhcicpO1xudmFyIExhYmVsRGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBMYWJlbERpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gZmFsc2U7XG4gICAgICAgIHRoaXMuc2NvcGUgPSBmYWxzZTtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8bGFiZWwgY2xhc3M9XCJtcy1MYWJlbFwiPjxuZy10cmFuc2NsdWRlLz48L2xhYmVsPic7XG4gICAgfVxuICAgIExhYmVsRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgTGFiZWxEaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIExhYmVsRGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlLCBpbnN0YW5jZUVsZW1lbnQsIGF0dHJpYnV0ZXMpIHtcbiAgICAgICAgaWYgKG5nLmlzRGVmaW5lZChhdHRyaWJ1dGVzLmRpc2FibGVkKSkge1xuICAgICAgICAgICAgaW5zdGFuY2VFbGVtZW50LmZpbmQoJ2xhYmVsJykuZXEoMCkuYWRkQ2xhc3MoJ2lzLWRpc2FibGVkJyk7XG4gICAgICAgIH1cbiAgICAgICAgaWYgKG5nLmlzRGVmaW5lZChhdHRyaWJ1dGVzLnJlcXVpcmVkKSkge1xuICAgICAgICAgICAgaW5zdGFuY2VFbGVtZW50LmZpbmQoJ2xhYmVsJykuZXEoMCkuYWRkQ2xhc3MoJ2lzLXJlcXVpcmVkJyk7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIHJldHVybiBMYWJlbERpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLkxhYmVsRGlyZWN0aXZlID0gTGFiZWxEaXJlY3RpdmU7XG5leHBvcnRzLm1vZHVsZSA9IG5nLm1vZHVsZSgnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5sYWJlbCcsIFsnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cyddKVxuICAgIC5kaXJlY3RpdmUoJ3VpZkxhYmVsJywgTGFiZWxEaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9sYWJlbC9sYWJlbERpcmVjdGl2ZS50c1xuICoqIG1vZHVsZSBpZCA9IDE2XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgTGlua0RpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gTGlua0RpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8YSBuZy1ocmVmPVwie3sgbmdIcmVmIH19XCIgY2xhc3M9XCJtcy1MaW5rXCIgbmctdHJhbnNjbHVkZT48L2E+JztcbiAgICAgICAgdGhpcy5zY29wZSA9IHtcbiAgICAgICAgICAgIG5nSHJlZjogJ0AnXG4gICAgICAgIH07XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgfVxuICAgIExpbmtEaXJlY3RpdmUuZmFjdG9yeSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgdmFyIGRpcmVjdGl2ZSA9IGZ1bmN0aW9uICgpIHsgcmV0dXJuIG5ldyBMaW5rRGlyZWN0aXZlKCk7IH07XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICByZXR1cm4gTGlua0RpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLkxpbmtEaXJlY3RpdmUgPSBMaW5rRGlyZWN0aXZlO1xuZXhwb3J0cy5tb2R1bGUgPSBuZy5tb2R1bGUoJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMubGluaycsIFtcbiAgICAnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cydcbl0pXG4gICAgLmRpcmVjdGl2ZSgndWlmTGluaycsIExpbmtEaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9saW5rL2xpbmtEaXJlY3RpdmUudHNcbiAqKiBtb2R1bGUgaWQgPSAxN1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xudmFyIG5nID0gcmVxdWlyZSgnYW5ndWxhcicpO1xudmFyIG92ZXJsYXlNb2RlRW51bV90c18xID0gcmVxdWlyZSgnLi9vdmVybGF5TW9kZUVudW0udHMnKTtcbnZhciBPdmVybGF5Q29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gT3ZlcmxheUNvbnRyb2xsZXIobG9nKSB7XG4gICAgICAgIHRoaXMubG9nID0gbG9nO1xuICAgIH1cbiAgICBPdmVybGF5Q29udHJvbGxlci4kaW5qZWN0ID0gWyckbG9nJ107XG4gICAgcmV0dXJuIE92ZXJsYXlDb250cm9sbGVyO1xufSkoKTtcbnZhciBPdmVybGF5RGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBPdmVybGF5RGlyZWN0aXZlKGxvZykge1xuICAgICAgICB0aGlzLmxvZyA9IGxvZztcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IGNsYXNzPVwibXMtT3ZlcmxheVwiIG5nLWNsYXNzPVwie1xcJ21zLU92ZXJsYXktLWRhcmtcXCc6IHVpZk1vZGUgPT0gXFwnZGFya1xcJ31cIiBuZy10cmFuc2NsdWRlPjwvZGl2Pic7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7XG4gICAgICAgICAgICB1aWZNb2RlOiAnQCdcbiAgICAgICAgfTtcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgT3ZlcmxheURpcmVjdGl2ZS5sb2cgPSBsb2c7XG4gICAgfVxuICAgIE92ZXJsYXlEaXJlY3RpdmUuZmFjdG9yeSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgdmFyIGRpcmVjdGl2ZSA9IGZ1bmN0aW9uIChsb2cpIHsgcmV0dXJuIG5ldyBPdmVybGF5RGlyZWN0aXZlKGxvZyk7IH07XG4gICAgICAgIGRpcmVjdGl2ZS4kaW5qZWN0ID0gWyckbG9nJ107XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICBPdmVybGF5RGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlKSB7XG4gICAgICAgIHNjb3BlLiR3YXRjaCgndWlmTW9kZScsIGZ1bmN0aW9uIChuZXdWYWx1ZSwgb2xkVmFsdWUpIHtcbiAgICAgICAgICAgIGlmIChvdmVybGF5TW9kZUVudW1fdHNfMS5PdmVybGF5TW9kZVtuZXdWYWx1ZV0gPT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgICAgIE92ZXJsYXlEaXJlY3RpdmUubG9nLmVycm9yKCdFcnJvciBbbmdPZmZpY2VVaUZhYnJpY10gb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy5vdmVybGF5IC0gVW5zdXBwb3J0ZWQgb3ZlcmxheSBtb2RlOiAnICtcbiAgICAgICAgICAgICAgICAgICAgJ1RoZSBvdmVybGF5IG1vZGUgKFxcJycgKyBzY29wZS51aWZNb2RlICsgJ1xcJykgaXMgbm90IHN1cHBvcnRlZCBieSB0aGUgT2ZmaWNlIFVJIEZhYnJpYy4gJyArXG4gICAgICAgICAgICAgICAgICAgICdTdXBwb3J0ZWQgb3B0aW9ucyBhcmUgbGlzdGVkIGhlcmU6ICcgK1xuICAgICAgICAgICAgICAgICAgICAnaHR0cHM6Ly9naXRodWIuY29tL25nT2ZmaWNlVUlGYWJyaWMvbmctb2ZmaWNldWlmYWJyaWMvYmxvYi9tYXN0ZXIvc3JjL2NvbXBvbmVudHMvb3ZlcmxheS9vdmVybGF5TW9kZUVudW0udHMnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfSk7XG4gICAgfTtcbiAgICA7XG4gICAgcmV0dXJuIE92ZXJsYXlEaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5PdmVybGF5RGlyZWN0aXZlID0gT3ZlcmxheURpcmVjdGl2ZTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLm92ZXJsYXknLCBbXG4gICAgJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMnXG5dKVxuICAgIC5kaXJlY3RpdmUoJ3VpZk92ZXJsYXknLCBPdmVybGF5RGlyZWN0aXZlLmZhY3RvcnkoKSk7XG5cblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqIC4vc3JjL2NvbXBvbmVudHMvb3ZlcmxheS9vdmVybGF5RGlyZWN0aXZlLnRzXG4gKiogbW9kdWxlIGlkID0gMThcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyIsIid1c2Ugc3RyaWN0JztcbihmdW5jdGlvbiAoT3ZlcmxheU1vZGUpIHtcbiAgICBPdmVybGF5TW9kZVtPdmVybGF5TW9kZVtcImxpZ2h0XCJdID0gMF0gPSBcImxpZ2h0XCI7XG4gICAgT3ZlcmxheU1vZGVbT3ZlcmxheU1vZGVbXCJkYXJrXCJdID0gMV0gPSBcImRhcmtcIjtcbn0pKGV4cG9ydHMuT3ZlcmxheU1vZGUgfHwgKGV4cG9ydHMuT3ZlcmxheU1vZGUgPSB7fSkpO1xudmFyIE92ZXJsYXlNb2RlID0gZXhwb3J0cy5PdmVybGF5TW9kZTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9vdmVybGF5L292ZXJsYXlNb2RlRW51bS50c1xuICoqIG1vZHVsZSBpZCA9IDE5XG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgUHJvZ3Jlc3NJbmRpY2F0b3JEaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIFByb2dyZXNzSW5kaWNhdG9yRGlyZWN0aXZlKGxvZykge1xuICAgICAgICB0aGlzLmxvZyA9IGxvZztcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IGNsYXNzPVwibXMtUHJvZ3Jlc3NJbmRpY2F0b3JcIj4nICtcbiAgICAgICAgICAgICc8ZGl2IGNsYXNzPVwibXMtUHJvZ3Jlc3NJbmRpY2F0b3ItaXRlbU5hbWVcIj57e3VpZk5hbWV9fTwvZGl2PicgK1xuICAgICAgICAgICAgJzxkaXYgY2xhc3M9XCJtcy1Qcm9ncmVzc0luZGljYXRvci1pdGVtUHJvZ3Jlc3NcIj4nICtcbiAgICAgICAgICAgICc8ZGl2IGNsYXNzPVwibXMtUHJvZ3Jlc3NJbmRpY2F0b3ItcHJvZ3Jlc3NUcmFja1wiPjwvZGl2PicgK1xuICAgICAgICAgICAgJzxkaXYgY2xhc3M9XCJtcy1Qcm9ncmVzc0luZGljYXRvci1wcm9ncmVzc0JhclwiIG5nLXN0eWxlPVwie3dpZHRoOiB1aWZQZXJjZW50Q29tcGxldGUrXFwnJVxcJ31cIj48L2Rpdj4nICtcbiAgICAgICAgICAgICc8L2Rpdj4nICtcbiAgICAgICAgICAgICc8ZGl2IGNsYXNzPVwibXMtUHJvZ3Jlc3NJbmRpY2F0b3ItaXRlbURlc2NyaXB0aW9uXCI+e3t1aWZEZXNjcmlwdGlvbn19PC9kaXY+JyArXG4gICAgICAgICAgICAnPC9kaXY+JztcbiAgICAgICAgdGhpcy5zY29wZSA9IHtcbiAgICAgICAgICAgIHVpZkRlc2NyaXB0aW9uOiAnQCcsXG4gICAgICAgICAgICB1aWZOYW1lOiAnQCcsXG4gICAgICAgICAgICB1aWZQZXJjZW50Q29tcGxldGU6ICdAJ1xuICAgICAgICB9O1xuICAgICAgICBQcm9ncmVzc0luZGljYXRvckRpcmVjdGl2ZS5sb2cgPSBsb2c7XG4gICAgfVxuICAgIFByb2dyZXNzSW5kaWNhdG9yRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAobG9nKSB7IHJldHVybiBuZXcgUHJvZ3Jlc3NJbmRpY2F0b3JEaXJlY3RpdmUobG9nKTsgfTtcbiAgICAgICAgZGlyZWN0aXZlLiRpbmplY3QgPSBbJyRsb2cnXTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIFByb2dyZXNzSW5kaWNhdG9yRGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlKSB7XG4gICAgICAgIHNjb3BlLiR3YXRjaCgndWlmUGVyY2VudENvbXBsZXRlJywgZnVuY3Rpb24gKG5ld1ZhbHVlLCBvbGRWYWx1ZSkge1xuICAgICAgICAgICAgaWYgKG5ld1ZhbHVlID09IG51bGwgfHwgbmV3VmFsdWUgPT09ICcnKSB7XG4gICAgICAgICAgICAgICAgc2NvcGUudWlmUGVyY2VudENvbXBsZXRlID0gMDtcbiAgICAgICAgICAgICAgICByZXR1cm47XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICB2YXIgbmV3UGVyY2VudENvbXBsZXRlID0gcGFyc2VGbG9hdChuZXdWYWx1ZSk7XG4gICAgICAgICAgICBpZiAoaXNOYU4obmV3UGVyY2VudENvbXBsZXRlKSB8fCBuZXdQZXJjZW50Q29tcGxldGUgPCAwIHx8IG5ld1BlcmNlbnRDb21wbGV0ZSA+IDEwMCkge1xuICAgICAgICAgICAgICAgIFByb2dyZXNzSW5kaWNhdG9yRGlyZWN0aXZlLmxvZy5lcnJvcignRXJyb3IgW25nT2ZmaWNlVWlGYWJyaWNdIG9mZmljZXVpZmFicmljLmNvbXBvbmVudHMucHJvZ3Jlc3NpbmRpY2F0b3IgLSAnICtcbiAgICAgICAgICAgICAgICAgICAgJ1BlcmNlbnQgY29tcGxldGUgbXVzdCBiZSBhIHZhbGlkIG51bWJlciBiZXR3ZWVuIDAgYW5kIDEwMC4nKTtcbiAgICAgICAgICAgICAgICBzY29wZS51aWZQZXJjZW50Q29tcGxldGUgPSBNYXRoLm1heChNYXRoLm1pbihuZXdQZXJjZW50Q29tcGxldGUsIDEwMCksIDApO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICB9O1xuICAgIDtcbiAgICByZXR1cm4gUHJvZ3Jlc3NJbmRpY2F0b3JEaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5Qcm9ncmVzc0luZGljYXRvckRpcmVjdGl2ZSA9IFByb2dyZXNzSW5kaWNhdG9yRGlyZWN0aXZlO1xuZXhwb3J0cy5tb2R1bGUgPSBuZy5tb2R1bGUoJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMucHJvZ3Jlc3NpbmRpY2F0b3InLCBbXG4gICAgJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMnXG5dKVxuICAgIC5kaXJlY3RpdmUoJ3VpZlByb2dyZXNzSW5kaWNhdG9yJywgUHJvZ3Jlc3NJbmRpY2F0b3JEaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy9wcm9ncmVzc2luZGljYXRvci9wcm9ncmVzc0luZGljYXRvckRpcmVjdGl2ZS50c1xuICoqIG1vZHVsZSBpZCA9IDIwXG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG52YXIgbmcgPSByZXF1aXJlKCdhbmd1bGFyJyk7XG52YXIgU2VhcmNoQm94RGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBTZWFyY2hCb3hEaXJlY3RpdmUoKSB7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPGRpdiBjbGFzcz1cIm1zLVNlYXJjaEJveFwiIG5nLWNsYXNzPVwie1xcJ2lzLWFjdGl2ZVxcJzppc0FjdGl2ZX1cIj4nICtcbiAgICAgICAgICAgICc8aW5wdXQgY2xhc3M9XCJtcy1TZWFyY2hCb3gtZmllbGRcIiBuZy1mb2N1cz1cImlucHV0Rm9jdXMoKVwiIG5nLWJsdXI9XCJpbnB1dEJsdXIoKVwiJyArXG4gICAgICAgICAgICAnIG5nLW1vZGVsPVwidmFsdWVcIiBpZD1cInt7OjpcXCdzZWFyY2hCb3hfXFwnKyRpZH19XCIgLz4nICtcbiAgICAgICAgICAgICc8bGFiZWwgY2xhc3M9XCJtcy1TZWFyY2hCb3gtbGFiZWxcIiBmb3I9XCJ7ezo6XFwnc2VhcmNoQm94X1xcJyskaWR9fVwiIG5nLWhpZGU9XCJpc0xhYmVsSGlkZGVuXCI+JyArXG4gICAgICAgICAgICAnPGkgY2xhc3M9XCJtcy1TZWFyY2hCb3gtaWNvbiBtcy1JY29uIG1zLUljb24tLXNlYXJjaFwiID48L2k+IHt7cGxhY2Vob2xkZXJ9fTwvbGFiZWw+JyArXG4gICAgICAgICAgICAnPGJ1dHRvbiBjbGFzcz1cIm1zLVNlYXJjaEJveC1jbG9zZUJ1dHRvblwiIG5nLW1vdXNlZG93bj1cImJ0bk1vdXNlZG93bigpXCIgdHlwZT1cImJ1dHRvblwiPjxpIGNsYXNzPVwibXMtSWNvbiBtcy1JY29uLS14XCI+PC9pPjwvYnV0dG9uPicgK1xuICAgICAgICAgICAgJzwvZGl2Pic7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7XG4gICAgICAgICAgICBwbGFjZWhvbGRlcjogJz0/JyxcbiAgICAgICAgICAgIHZhbHVlOiAnPT8nXG4gICAgICAgIH07XG4gICAgfVxuICAgIFNlYXJjaEJveERpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IFNlYXJjaEJveERpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgU2VhcmNoQm94RGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlLCBlbGVtLCBhdHRycykge1xuICAgICAgICBzY29wZS5pc0ZvY3VzID0gZmFsc2U7XG4gICAgICAgIHNjb3BlLmlzQ2FuY2VsID0gZmFsc2U7XG4gICAgICAgIHNjb3BlLmlzTGFiZWxIaWRkZW4gPSBmYWxzZTtcbiAgICAgICAgc2NvcGUuaXNBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgc2NvcGUuaW5wdXRGb2N1cyA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHNjb3BlLmlzRm9jdXMgPSB0cnVlO1xuICAgICAgICAgICAgc2NvcGUuaXNMYWJlbEhpZGRlbiA9IHRydWU7XG4gICAgICAgICAgICBzY29wZS5pc0FjdGl2ZSA9IHRydWU7XG4gICAgICAgIH07XG4gICAgICAgIHNjb3BlLmlucHV0Qmx1ciA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIGlmIChzY29wZS5pc0NhbmNlbCkge1xuICAgICAgICAgICAgICAgIHNjb3BlLnZhbHVlID0gJyc7XG4gICAgICAgICAgICAgICAgc2NvcGUuaXNMYWJlbEhpZGRlbiA9IGZhbHNlO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgc2NvcGUuaXNBY3RpdmUgPSBmYWxzZTtcbiAgICAgICAgICAgIGlmICh0eXBlb2YgKHNjb3BlLnZhbHVlKSA9PT0gJ3VuZGVmaW5lZCcgfHwgc2NvcGUudmFsdWUgPT09ICcnKSB7XG4gICAgICAgICAgICAgICAgc2NvcGUuaXNMYWJlbEhpZGRlbiA9IGZhbHNlO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgc2NvcGUuaXNGb2N1cyA9IHNjb3BlLmlzQ2FuY2VsID0gZmFsc2U7XG4gICAgICAgIH07XG4gICAgICAgIHNjb3BlLmJ0bk1vdXNlZG93biA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHNjb3BlLmlzQ2FuY2VsID0gdHJ1ZTtcbiAgICAgICAgfTtcbiAgICAgICAgc2NvcGUuJHdhdGNoKCd2YWx1ZScsIGZ1bmN0aW9uICh2YWwpIHtcbiAgICAgICAgICAgIGlmICghc2NvcGUuaXNGb2N1cykge1xuICAgICAgICAgICAgICAgIGlmICh2YWwgJiYgdmFsICE9PSAnJykge1xuICAgICAgICAgICAgICAgICAgICBzY29wZS5pc0xhYmVsSGlkZGVuID0gdHJ1ZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgZWxzZSB7XG4gICAgICAgICAgICAgICAgICAgIHNjb3BlLmlzTGFiZWxIaWRkZW4gPSBmYWxzZTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgc2NvcGUudmFsdWUgPSB2YWw7XG4gICAgICAgICAgICB9XG4gICAgICAgIH0pO1xuICAgICAgICBzY29wZS4kd2F0Y2goJ3BsYWNlaG9sZGVyJywgZnVuY3Rpb24gKHNlYXJjaCkge1xuICAgICAgICAgICAgc2NvcGUucGxhY2Vob2xkZXIgPSBzZWFyY2g7XG4gICAgICAgIH0pO1xuICAgIH07XG4gICAgcmV0dXJuIFNlYXJjaEJveERpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLlNlYXJjaEJveERpcmVjdGl2ZSA9IFNlYXJjaEJveERpcmVjdGl2ZTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLnNlYXJjaGJveCcsIFsnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cyddKVxuICAgIC5kaXJlY3RpdmUoJ3VpZlNlYXJjaGJveCcsIFNlYXJjaEJveERpcmVjdGl2ZS5mYWN0b3J5KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL3NlYXJjaGJveC9zZWFyY2hib3hEaXJlY3RpdmUudHNcbiAqKiBtb2R1bGUgaWQgPSAyMVxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xudmFyIG5nID0gcmVxdWlyZSgnYW5ndWxhcicpO1xudmFyIHNwaW5uZXJTaXplRW51bV8xID0gcmVxdWlyZSgnLi9zcGlubmVyU2l6ZUVudW0nKTtcbnZhciBTcGlubmVyRGlyZWN0aXZlID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBTcGlubmVyRGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnJlc3RyaWN0ID0gJ0UnO1xuICAgICAgICB0aGlzLnRyYW5zY2x1ZGUgPSB0cnVlO1xuICAgICAgICB0aGlzLnJlcGxhY2UgPSB0cnVlO1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxkaXYgY2xhc3M9XCJtcy1TcGlubmVyXCI+PC9kaXY+JztcbiAgICAgICAgdGhpcy5jb250cm9sbGVyID0gU3Bpbm5lckNvbnRyb2xsZXI7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7XG4gICAgICAgICAgICAnbmdTaG93JzogJz0nLFxuICAgICAgICAgICAgJ3VpZlNpemUnOiAnQCdcbiAgICAgICAgfTtcbiAgICB9XG4gICAgU3Bpbm5lckRpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IFNwaW5uZXJEaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIFNwaW5uZXJEaXJlY3RpdmUucHJvdG90eXBlLmxpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGluc3RhbmNlRWxlbWVudCwgYXR0cnMsIGNvbnRyb2xsZXIsICR0cmFuc2NsdWRlKSB7XG4gICAgICAgIGlmIChuZy5pc0RlZmluZWQoYXR0cnMudWlmU2l6ZSkpIHtcbiAgICAgICAgICAgIGlmIChuZy5pc1VuZGVmaW5lZChzcGlubmVyU2l6ZUVudW1fMS5TcGlubmVyU2l6ZVthdHRycy51aWZTaXplXSkpIHtcbiAgICAgICAgICAgICAgICBjb250cm9sbGVyLiRsb2cuZXJyb3IoJ0Vycm9yIFtuZ09mZmljZVVpRmFicmljXSBvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLnNwaW5uZXIgLSBVbnN1cHBvcnRlZCBzaXplOiAnICtcbiAgICAgICAgICAgICAgICAgICAgJ1NwaW5uZXIgc2l6ZSAoXFwnJyArIGF0dHJzLnVpZlNpemUgKyAnXFwnKSBpcyBub3Qgc3VwcG9ydGVkIGJ5IHRoZSBPZmZpY2UgVUkgRmFicmljLicpO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKHNwaW5uZXJTaXplRW51bV8xLlNwaW5uZXJTaXplW2F0dHJzLnVpZlNpemVdID09PSBzcGlubmVyU2l6ZUVudW1fMS5TcGlubmVyU2l6ZS5sYXJnZSkge1xuICAgICAgICAgICAgICAgIGluc3RhbmNlRWxlbWVudC5hZGRDbGFzcygnbXMtU3Bpbm5lci0tbGFyZ2UnKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBpZiAoYXR0cnMubmdTaG93ICE9IG51bGwpIHtcbiAgICAgICAgICAgIHNjb3BlLiR3YXRjaCgnbmdTaG93JywgZnVuY3Rpb24gKG5ld1Zpc2libGUsIG9sZFZpc2libGUsIHNwaW5uZXJTY29wZSkge1xuICAgICAgICAgICAgICAgIGlmIChuZXdWaXNpYmxlKSB7XG4gICAgICAgICAgICAgICAgICAgIHNwaW5uZXJTY29wZS5zdGFydCgpO1xuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICAgICAgc3Bpbm5lclNjb3BlLnN0b3AoKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9KTtcbiAgICAgICAgfVxuICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgIHNjb3BlLnN0YXJ0KCk7XG4gICAgICAgIH1cbiAgICAgICAgJHRyYW5zY2x1ZGUoZnVuY3Rpb24gKGNsb25lKSB7XG4gICAgICAgICAgICBpZiAoY2xvbmUubGVuZ3RoID4gMCkge1xuICAgICAgICAgICAgICAgIHZhciB3cmFwcGVyID0gbmcuZWxlbWVudCgnPGRpdj48L2Rpdj4nKTtcbiAgICAgICAgICAgICAgICB3cmFwcGVyLmFkZENsYXNzKCdtcy1TcGlubmVyLWxhYmVsJykuYXBwZW5kKGNsb25lKTtcbiAgICAgICAgICAgICAgICBpbnN0YW5jZUVsZW1lbnQuYXBwZW5kKHdyYXBwZXIpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICAgICAgc2NvcGUuaW5pdCgpO1xuICAgIH07XG4gICAgcmV0dXJuIFNwaW5uZXJEaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5TcGlubmVyRGlyZWN0aXZlID0gU3Bpbm5lckRpcmVjdGl2ZTtcbnZhciBTcGlubmVyQ29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gU3Bpbm5lckNvbnRyb2xsZXIoJHNjb3BlLCAkZWxlbWVudCwgJGludGVydmFsLCAkbG9nKSB7XG4gICAgICAgIHZhciBfdGhpcyA9IHRoaXM7XG4gICAgICAgIHRoaXMuJHNjb3BlID0gJHNjb3BlO1xuICAgICAgICB0aGlzLiRlbGVtZW50ID0gJGVsZW1lbnQ7XG4gICAgICAgIHRoaXMuJGludGVydmFsID0gJGludGVydmFsO1xuICAgICAgICB0aGlzLiRsb2cgPSAkbG9nO1xuICAgICAgICB0aGlzLl9vZmZzZXRTaXplID0gMC4xNzk7XG4gICAgICAgIHRoaXMuX251bUNpcmNsZXMgPSA4O1xuICAgICAgICB0aGlzLl9hbmltYXRpb25TcGVlZCA9IDkwO1xuICAgICAgICB0aGlzLl9jaXJjbGVzID0gW107XG4gICAgICAgICRzY29wZS5pbml0ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgX3RoaXMuX3BhcmVudFNpemUgPSBzcGlubmVyU2l6ZUVudW1fMS5TcGlubmVyU2l6ZVtfdGhpcy4kc2NvcGUudWlmU2l6ZV0gPT09IHNwaW5uZXJTaXplRW51bV8xLlNwaW5uZXJTaXplLmxhcmdlID8gMjggOiAyMDtcbiAgICAgICAgICAgIF90aGlzLmNyZWF0ZUNpcmNsZXNBbmRBcnJhbmdlKCk7XG4gICAgICAgICAgICBfdGhpcy5zZXRJbml0aWFsT3BhY2l0eSgpO1xuICAgICAgICB9O1xuICAgICAgICAkc2NvcGUuc3RhcnQgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICBfdGhpcy5fYW5pbWF0aW9uSW50ZXJ2YWwgPSAkaW50ZXJ2YWwoZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgICAgIHZhciBpID0gX3RoaXMuX2NpcmNsZXMubGVuZ3RoO1xuICAgICAgICAgICAgICAgIHdoaWxlIChpLS0pIHtcbiAgICAgICAgICAgICAgICAgICAgX3RoaXMuZmFkZUNpcmNsZShfdGhpcy5fY2lyY2xlc1tpXSk7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSwgX3RoaXMuX2FuaW1hdGlvblNwZWVkKTtcbiAgICAgICAgfTtcbiAgICAgICAgJHNjb3BlLnN0b3AgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAkaW50ZXJ2YWwuY2FuY2VsKF90aGlzLl9hbmltYXRpb25JbnRlcnZhbCk7XG4gICAgICAgIH07XG4gICAgfVxuICAgIFNwaW5uZXJDb250cm9sbGVyLnByb3RvdHlwZS5jcmVhdGVDaXJjbGVzQW5kQXJyYW5nZSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgdmFyIGFuZ2xlID0gMDtcbiAgICAgICAgdmFyIG9mZnNldCA9IHRoaXMuX3BhcmVudFNpemUgKiB0aGlzLl9vZmZzZXRTaXplO1xuICAgICAgICB2YXIgc3RlcCA9ICgyICogTWF0aC5QSSkgLyB0aGlzLl9udW1DaXJjbGVzO1xuICAgICAgICB2YXIgaSA9IHRoaXMuX251bUNpcmNsZXM7XG4gICAgICAgIHZhciByYWRpdXMgPSAodGhpcy5fcGFyZW50U2l6ZSAtIG9mZnNldCkgKiAwLjU7XG4gICAgICAgIHdoaWxlIChpLS0pIHtcbiAgICAgICAgICAgIHZhciBjaXJjbGUgPSB0aGlzLmNyZWF0ZUNpcmNsZSgpO1xuICAgICAgICAgICAgdmFyIHggPSBNYXRoLnJvdW5kKHRoaXMuX3BhcmVudFNpemUgKiAwLjUgKyByYWRpdXMgKiBNYXRoLmNvcyhhbmdsZSkgLSBjaXJjbGVbMF0uY2xpZW50V2lkdGggKiAwLjUpIC0gb2Zmc2V0ICogMC41O1xuICAgICAgICAgICAgdmFyIHkgPSBNYXRoLnJvdW5kKHRoaXMuX3BhcmVudFNpemUgKiAwLjUgKyByYWRpdXMgKiBNYXRoLnNpbihhbmdsZSkgLSBjaXJjbGVbMF0uY2xpZW50SGVpZ2h0ICogMC41KSAtIG9mZnNldCAqIDAuNTtcbiAgICAgICAgICAgIHRoaXMuJGVsZW1lbnQuYXBwZW5kKGNpcmNsZSk7XG4gICAgICAgICAgICBjaXJjbGUuY3NzKCdsZWZ0JywgKHggKyAncHgnKSk7XG4gICAgICAgICAgICBjaXJjbGUuY3NzKCd0b3AnLCAoeSArICdweCcpKTtcbiAgICAgICAgICAgIGFuZ2xlICs9IHN0ZXA7XG4gICAgICAgICAgICB2YXIgY2lyY2xlT2JqZWN0ID0gbmV3IENpcmNsZU9iamVjdChjaXJjbGUsIGkpO1xuICAgICAgICAgICAgdGhpcy5fY2lyY2xlcy5wdXNoKGNpcmNsZU9iamVjdCk7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIFNwaW5uZXJDb250cm9sbGVyLnByb3RvdHlwZS5jcmVhdGVDaXJjbGUgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBjaXJjbGUgPSBuZy5lbGVtZW50KCc8ZGl2PjwvZGl2PicpO1xuICAgICAgICB2YXIgZG90U2l6ZSA9ICh0aGlzLl9wYXJlbnRTaXplICogdGhpcy5fb2Zmc2V0U2l6ZSkgKyAncHgnO1xuICAgICAgICBjaXJjbGUuYWRkQ2xhc3MoJ21zLVNwaW5uZXItY2lyY2xlJykuY3NzKCd3aWR0aCcsIGRvdFNpemUpLmNzcygnaGVpZ2h0JywgZG90U2l6ZSk7XG4gICAgICAgIHJldHVybiBjaXJjbGU7XG4gICAgfTtcbiAgICA7XG4gICAgU3Bpbm5lckNvbnRyb2xsZXIucHJvdG90eXBlLnNldEluaXRpYWxPcGFjaXR5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgX3RoaXMgPSB0aGlzO1xuICAgICAgICB2YXIgb3BjYWl0eVRvU2V0O1xuICAgICAgICB0aGlzLl9mYWRlSW5jcmVtZW50ID0gMSAvIHRoaXMuX251bUNpcmNsZXM7XG4gICAgICAgIHRoaXMuX2NpcmNsZXMuZm9yRWFjaChmdW5jdGlvbiAoY2lyY2xlLCBpbmRleCkge1xuICAgICAgICAgICAgb3BjYWl0eVRvU2V0ID0gKF90aGlzLl9mYWRlSW5jcmVtZW50ICogKGluZGV4ICsgMSkpO1xuICAgICAgICAgICAgY2lyY2xlLm9wYWNpdHkgPSBvcGNhaXR5VG9TZXQ7XG4gICAgICAgIH0pO1xuICAgIH07XG4gICAgU3Bpbm5lckNvbnRyb2xsZXIucHJvdG90eXBlLmZhZGVDaXJjbGUgPSBmdW5jdGlvbiAoY2lyY2xlKSB7XG4gICAgICAgIHZhciBuZXdPcGFjaXR5ID0gY2lyY2xlLm9wYWNpdHkgLSB0aGlzLl9mYWRlSW5jcmVtZW50O1xuICAgICAgICBpZiAobmV3T3BhY2l0eSA8PSAwKSB7XG4gICAgICAgICAgICBuZXdPcGFjaXR5ID0gMTtcbiAgICAgICAgfVxuICAgICAgICBjaXJjbGUub3BhY2l0eSA9IG5ld09wYWNpdHk7XG4gICAgfTtcbiAgICBTcGlubmVyQ29udHJvbGxlci4kaW5qZWN0ID0gWyckc2NvcGUnLCAnJGVsZW1lbnQnLCAnJGludGVydmFsJywgJyRsb2cnXTtcbiAgICByZXR1cm4gU3Bpbm5lckNvbnRyb2xsZXI7XG59KSgpO1xudmFyIENpcmNsZU9iamVjdCA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gQ2lyY2xlT2JqZWN0KGNpcmNsZUVsZW1lbnQsIGNpcmNsZUluZGV4KSB7XG4gICAgICAgIHRoaXMuY2lyY2xlRWxlbWVudCA9IGNpcmNsZUVsZW1lbnQ7XG4gICAgICAgIHRoaXMuY2lyY2xlSW5kZXggPSBjaXJjbGVJbmRleDtcbiAgICB9XG4gICAgT2JqZWN0LmRlZmluZVByb3BlcnR5KENpcmNsZU9iamVjdC5wcm90b3R5cGUsIFwib3BhY2l0eVwiLCB7XG4gICAgICAgIGdldDogZnVuY3Rpb24gKCkge1xuICAgICAgICAgICAgcmV0dXJuICsodGhpcy5jaXJjbGVFbGVtZW50LmNzcygnb3BhY2l0eScpKTtcbiAgICAgICAgfSxcbiAgICAgICAgc2V0OiBmdW5jdGlvbiAob3BhY2l0eSkge1xuICAgICAgICAgICAgdGhpcy5jaXJjbGVFbGVtZW50LmNzcygnb3BhY2l0eScsIG9wYWNpdHkpO1xuICAgICAgICB9LFxuICAgICAgICBlbnVtZXJhYmxlOiB0cnVlLFxuICAgICAgICBjb25maWd1cmFibGU6IHRydWVcbiAgICB9KTtcbiAgICByZXR1cm4gQ2lyY2xlT2JqZWN0O1xufSkoKTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLnNwaW5uZXInLCBbJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMnXSlcbiAgICAuZGlyZWN0aXZlKCd1aWZTcGlubmVyJywgU3Bpbm5lckRpcmVjdGl2ZS5mYWN0b3J5KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL3NwaW5uZXIvc3Bpbm5lckRpcmVjdGl2ZS50c1xuICoqIG1vZHVsZSBpZCA9IDIyXG4gKiogbW9kdWxlIGNodW5rcyA9IDBcbiAqKi8iLCIndXNlIHN0cmljdCc7XG4oZnVuY3Rpb24gKFNwaW5uZXJTaXplKSB7XG4gICAgU3Bpbm5lclNpemVbU3Bpbm5lclNpemVbJ3NtYWxsJ10gPSAwXSA9ICdzbWFsbCc7XG4gICAgU3Bpbm5lclNpemVbU3Bpbm5lclNpemVbJ2xhcmdlJ10gPSAxXSA9ICdsYXJnZSc7XG59KShleHBvcnRzLlNwaW5uZXJTaXplIHx8IChleHBvcnRzLlNwaW5uZXJTaXplID0ge30pKTtcbnZhciBTcGlubmVyU2l6ZSA9IGV4cG9ydHMuU3Bpbm5lclNpemU7XG5cblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqIC4vc3JjL2NvbXBvbmVudHMvc3Bpbm5lci9zcGlubmVyU2l6ZUVudW0udHNcbiAqKiBtb2R1bGUgaWQgPSAyM1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xudmFyIG5nID0gcmVxdWlyZSgnYW5ndWxhcicpO1xudmFyIHRhYmxlUm93U2VsZWN0TW9kZUVudW1fMSA9IHJlcXVpcmUoJy4vdGFibGVSb3dTZWxlY3RNb2RlRW51bScpO1xudmFyIFRhYmxlQ29udHJvbGxlciA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gVGFibGVDb250cm9sbGVyKCRzY29wZSwgJGxvZykge1xuICAgICAgICB0aGlzLiRzY29wZSA9ICRzY29wZTtcbiAgICAgICAgdGhpcy4kbG9nID0gJGxvZztcbiAgICAgICAgdGhpcy4kc2NvcGUub3JkZXJCeSA9IG51bGw7XG4gICAgICAgIHRoaXMuJHNjb3BlLm9yZGVyQXNjID0gdHJ1ZTtcbiAgICAgICAgdGhpcy4kc2NvcGUucm93cyA9IFtdO1xuICAgIH1cbiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkoVGFibGVDb250cm9sbGVyLnByb3RvdHlwZSwgXCJvcmRlckJ5XCIsIHtcbiAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUub3JkZXJCeTtcbiAgICAgICAgfSxcbiAgICAgICAgc2V0OiBmdW5jdGlvbiAocHJvcGVydHkpIHtcbiAgICAgICAgICAgIHRoaXMuJHNjb3BlLm9yZGVyQnkgPSBwcm9wZXJ0eTtcbiAgICAgICAgICAgIHRoaXMuJHNjb3BlLiRkaWdlc3QoKTtcbiAgICAgICAgfSxcbiAgICAgICAgZW51bWVyYWJsZTogdHJ1ZSxcbiAgICAgICAgY29uZmlndXJhYmxlOiB0cnVlXG4gICAgfSk7XG4gICAgT2JqZWN0LmRlZmluZVByb3BlcnR5KFRhYmxlQ29udHJvbGxlci5wcm90b3R5cGUsIFwib3JkZXJBc2NcIiwge1xuICAgICAgICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHJldHVybiB0aGlzLiRzY29wZS5vcmRlckFzYztcbiAgICAgICAgfSxcbiAgICAgICAgc2V0OiBmdW5jdGlvbiAob3JkZXJBc2MpIHtcbiAgICAgICAgICAgIHRoaXMuJHNjb3BlLm9yZGVyQXNjID0gb3JkZXJBc2M7XG4gICAgICAgICAgICB0aGlzLiRzY29wZS4kZGlnZXN0KCk7XG4gICAgICAgIH0sXG4gICAgICAgIGVudW1lcmFibGU6IHRydWUsXG4gICAgICAgIGNvbmZpZ3VyYWJsZTogdHJ1ZVxuICAgIH0pO1xuICAgIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShUYWJsZUNvbnRyb2xsZXIucHJvdG90eXBlLCBcInJvd1NlbGVjdE1vZGVcIiwge1xuICAgICAgICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHJldHVybiB0aGlzLiRzY29wZS5yb3dTZWxlY3RNb2RlO1xuICAgICAgICB9LFxuICAgICAgICBzZXQ6IGZ1bmN0aW9uIChyb3dTZWxlY3RNb2RlKSB7XG4gICAgICAgICAgICBpZiAodGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW1bcm93U2VsZWN0TW9kZV0gPT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgICAgIHRoaXMuJGxvZy5lcnJvcignRXJyb3IgW25nT2ZmaWNlVWlGYWJyaWNdIG9mZmljZXVpZmFicmljLmNvbXBvbmVudHMudGFibGUuICcgK1xuICAgICAgICAgICAgICAgICAgICAnXFwnJyArIHJvd1NlbGVjdE1vZGUgKyAnXFwnIGlzIG5vdCBhIHZhbGlkIG9wdGlvbiBmb3IgXFwndWlmLXJvdy1zZWxlY3QtbW9kZVxcJy4gJyArXG4gICAgICAgICAgICAgICAgICAgICdWYWxpZCBvcHRpb25zIGFyZSBub25lfHNpbmdsZXxtdWx0aXBsZS4nKTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIHRoaXMuJHNjb3BlLnJvd1NlbGVjdE1vZGUgPSByb3dTZWxlY3RNb2RlO1xuICAgICAgICAgICAgdGhpcy4kc2NvcGUuJGRpZ2VzdCgpO1xuICAgICAgICB9LFxuICAgICAgICBlbnVtZXJhYmxlOiB0cnVlLFxuICAgICAgICBjb25maWd1cmFibGU6IHRydWVcbiAgICB9KTtcbiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkoVGFibGVDb250cm9sbGVyLnByb3RvdHlwZSwgXCJyb3dzXCIsIHtcbiAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUucm93cztcbiAgICAgICAgfSxcbiAgICAgICAgc2V0OiBmdW5jdGlvbiAocm93cykge1xuICAgICAgICAgICAgdGhpcy4kc2NvcGUucm93cyA9IHJvd3M7XG4gICAgICAgIH0sXG4gICAgICAgIGVudW1lcmFibGU6IHRydWUsXG4gICAgICAgIGNvbmZpZ3VyYWJsZTogdHJ1ZVxuICAgIH0pO1xuICAgIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShUYWJsZUNvbnRyb2xsZXIucHJvdG90eXBlLCBcInNlbGVjdGVkSXRlbXNcIiwge1xuICAgICAgICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICAgIHZhciBzZWxlY3RlZEl0ZW1zID0gW107XG4gICAgICAgICAgICBmb3IgKHZhciBpID0gMDsgaSA8IHRoaXMucm93cy5sZW5ndGg7IGkrKykge1xuICAgICAgICAgICAgICAgIGlmICh0aGlzLnJvd3NbaV0uc2VsZWN0ZWQgPT09IHRydWUpIHtcbiAgICAgICAgICAgICAgICAgICAgc2VsZWN0ZWRJdGVtcy5wdXNoKHRoaXMucm93c1tpXS5pdGVtKTtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICByZXR1cm4gc2VsZWN0ZWRJdGVtcztcbiAgICAgICAgfSxcbiAgICAgICAgZW51bWVyYWJsZTogdHJ1ZSxcbiAgICAgICAgY29uZmlndXJhYmxlOiB0cnVlXG4gICAgfSk7XG4gICAgVGFibGVDb250cm9sbGVyLiRpbmplY3QgPSBbJyRzY29wZScsICckbG9nJ107XG4gICAgcmV0dXJuIFRhYmxlQ29udHJvbGxlcjtcbn0pKCk7XG52YXIgVGFibGVEaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIFRhYmxlRGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnJlc3RyaWN0ID0gJ0UnO1xuICAgICAgICB0aGlzLnRyYW5zY2x1ZGUgPSB0cnVlO1xuICAgICAgICB0aGlzLnJlcGxhY2UgPSB0cnVlO1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxkaXYgY2xhc3M9XCJtcy1UYWJsZVwiIG5nLXRyYW5zY2x1ZGU+PC9kaXY+JztcbiAgICAgICAgdGhpcy5jb250cm9sbGVyID0gVGFibGVDb250cm9sbGVyO1xuICAgICAgICB0aGlzLmNvbnRyb2xsZXJBcyA9ICd0YWJsZSc7XG4gICAgfVxuICAgIFRhYmxlRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgVGFibGVEaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIFRhYmxlRGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlLCBpbnN0YW5jZUVsZW1lbnQsIGF0dHJzLCBjb250cm9sbGVyKSB7XG4gICAgICAgIGlmIChhdHRycy51aWZSb3dTZWxlY3RNb2RlICE9PSB1bmRlZmluZWQgJiYgYXR0cnMudWlmUm93U2VsZWN0TW9kZSAhPT0gbnVsbCkge1xuICAgICAgICAgICAgaWYgKHRhYmxlUm93U2VsZWN0TW9kZUVudW1fMS5UYWJsZVJvd1NlbGVjdE1vZGVFbnVtW2F0dHJzLnVpZlJvd1NlbGVjdE1vZGVdID09PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgICAgICBjb250cm9sbGVyLiRsb2cuZXJyb3IoJ0Vycm9yIFtuZ09mZmljZVVpRmFicmljXSBvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLnRhYmxlLiAnICtcbiAgICAgICAgICAgICAgICAgICAgJ1xcJycgKyBhdHRycy51aWZSb3dTZWxlY3RNb2RlICsgJ1xcJyBpcyBub3QgYSB2YWxpZCBvcHRpb24gZm9yIFxcJ3VpZi1yb3ctc2VsZWN0LW1vZGVcXCcuICcgK1xuICAgICAgICAgICAgICAgICAgICAnVmFsaWQgb3B0aW9ucyBhcmUgbm9uZXxzaW5nbGV8bXVsdGlwbGUuJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICBzY29wZS5yb3dTZWxlY3RNb2RlID0gYXR0cnMudWlmUm93U2VsZWN0TW9kZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgICBpZiAoc2NvcGUucm93U2VsZWN0TW9kZSA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICAgICAgICBzY29wZS5yb3dTZWxlY3RNb2RlID0gdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW1bdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW0ubm9uZV07XG4gICAgICAgIH1cbiAgICB9O1xuICAgIHJldHVybiBUYWJsZURpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLlRhYmxlRGlyZWN0aXZlID0gVGFibGVEaXJlY3RpdmU7XG52YXIgVGFibGVSb3dDb250cm9sbGVyID0gKGZ1bmN0aW9uICgpIHtcbiAgICBmdW5jdGlvbiBUYWJsZVJvd0NvbnRyb2xsZXIoJHNjb3BlLCAkbG9nKSB7XG4gICAgICAgIHRoaXMuJHNjb3BlID0gJHNjb3BlO1xuICAgICAgICB0aGlzLiRsb2cgPSAkbG9nO1xuICAgIH1cbiAgICBPYmplY3QuZGVmaW5lUHJvcGVydHkoVGFibGVSb3dDb250cm9sbGVyLnByb3RvdHlwZSwgXCJpdGVtXCIsIHtcbiAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUuaXRlbTtcbiAgICAgICAgfSxcbiAgICAgICAgc2V0OiBmdW5jdGlvbiAoaXRlbSkge1xuICAgICAgICAgICAgdGhpcy4kc2NvcGUuaXRlbSA9IGl0ZW07XG4gICAgICAgICAgICB0aGlzLiRzY29wZS4kZGlnZXN0KCk7XG4gICAgICAgIH0sXG4gICAgICAgIGVudW1lcmFibGU6IHRydWUsXG4gICAgICAgIGNvbmZpZ3VyYWJsZTogdHJ1ZVxuICAgIH0pO1xuICAgIE9iamVjdC5kZWZpbmVQcm9wZXJ0eShUYWJsZVJvd0NvbnRyb2xsZXIucHJvdG90eXBlLCBcInNlbGVjdGVkXCIsIHtcbiAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICByZXR1cm4gdGhpcy4kc2NvcGUuc2VsZWN0ZWQ7XG4gICAgICAgIH0sXG4gICAgICAgIHNldDogZnVuY3Rpb24gKHNlbGVjdGVkKSB7XG4gICAgICAgICAgICB0aGlzLiRzY29wZS5zZWxlY3RlZCA9IHNlbGVjdGVkO1xuICAgICAgICAgICAgdGhpcy4kc2NvcGUuJGRpZ2VzdCgpO1xuICAgICAgICB9LFxuICAgICAgICBlbnVtZXJhYmxlOiB0cnVlLFxuICAgICAgICBjb25maWd1cmFibGU6IHRydWVcbiAgICB9KTtcbiAgICBUYWJsZVJvd0NvbnRyb2xsZXIuJGluamVjdCA9IFsnJHNjb3BlJywgJyRsb2cnXTtcbiAgICByZXR1cm4gVGFibGVSb3dDb250cm9sbGVyO1xufSkoKTtcbnZhciBUYWJsZVJvd0RpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gVGFibGVSb3dEaXJlY3RpdmUoKSB7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPGRpdiBjbGFzcz1cIm1zLVRhYmxlLXJvd1wiIG5nLXRyYW5zY2x1ZGU+PC9kaXY+JztcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gJ151aWZUYWJsZSc7XG4gICAgICAgIHRoaXMuc2NvcGUgPSB7XG4gICAgICAgICAgICBpdGVtOiAnPXVpZkl0ZW0nXG4gICAgICAgIH07XG4gICAgICAgIHRoaXMuY29udHJvbGxlciA9IFRhYmxlUm93Q29udHJvbGxlcjtcbiAgICB9XG4gICAgVGFibGVSb3dEaXJlY3RpdmUuZmFjdG9yeSA9IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgdmFyIGRpcmVjdGl2ZSA9IGZ1bmN0aW9uICgpIHsgcmV0dXJuIG5ldyBUYWJsZVJvd0RpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgVGFibGVSb3dEaXJlY3RpdmUucHJvdG90eXBlLmxpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGluc3RhbmNlRWxlbWVudCwgYXR0cnMsIHRhYmxlKSB7XG4gICAgICAgIGlmIChhdHRycy51aWZTZWxlY3RlZCAhPT0gdW5kZWZpbmVkICYmXG4gICAgICAgICAgICBhdHRycy51aWZTZWxlY3RlZCAhPT0gbnVsbCkge1xuICAgICAgICAgICAgdmFyIHNlbGVjdGVkU3RyaW5nID0gYXR0cnMudWlmU2VsZWN0ZWQudG9Mb3dlckNhc2UoKTtcbiAgICAgICAgICAgIGlmIChzZWxlY3RlZFN0cmluZyAhPT0gJ3RydWUnICYmIHNlbGVjdGVkU3RyaW5nICE9PSAnZmFsc2UnKSB7XG4gICAgICAgICAgICAgICAgdGFibGUuJGxvZy5lcnJvcignRXJyb3IgW25nT2ZmaWNlVWlGYWJyaWNdIG9mZmljZXVpZmFicmljLmNvbXBvbmVudHMudGFibGUuICcgK1xuICAgICAgICAgICAgICAgICAgICAnXFwnJyArIGF0dHJzLnVpZlNlbGVjdGVkICsgJ1xcJyBpcyBub3QgYSB2YWxpZCBib29sZWFuIHZhbHVlLiAnICtcbiAgICAgICAgICAgICAgICAgICAgJ1ZhbGlkIG9wdGlvbnMgYXJlIHRydWV8ZmFsc2UuJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICBpZiAoc2VsZWN0ZWRTdHJpbmcgPT09ICd0cnVlJykge1xuICAgICAgICAgICAgICAgICAgICBzY29wZS5zZWxlY3RlZCA9IHRydWU7XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfVxuICAgICAgICB9XG4gICAgICAgIGlmIChzY29wZS5pdGVtICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgICAgIHRhYmxlLnJvd3MucHVzaChzY29wZSk7XG4gICAgICAgIH1cbiAgICAgICAgc2NvcGUucm93Q2xpY2sgPSBmdW5jdGlvbiAoZXYpIHtcbiAgICAgICAgICAgIHNjb3BlLnNlbGVjdGVkID0gIXNjb3BlLnNlbGVjdGVkO1xuICAgICAgICAgICAgc2NvcGUuJGFwcGx5KCk7XG4gICAgICAgIH07XG4gICAgICAgIHNjb3BlLiR3YXRjaCgnc2VsZWN0ZWQnLCBmdW5jdGlvbiAobmV3VmFsdWUsIG9sZFZhbHVlLCB0YWJsZVJvd1Njb3BlKSB7XG4gICAgICAgICAgICBpZiAobmV3VmFsdWUgPT09IHRydWUpIHtcbiAgICAgICAgICAgICAgICBpZiAodGFibGUucm93U2VsZWN0TW9kZSA9PT0gdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW1bdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW0uc2luZ2xlXSkge1xuICAgICAgICAgICAgICAgICAgICBpZiAodGFibGUucm93cykge1xuICAgICAgICAgICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0YWJsZS5yb3dzLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgaWYgKHRhYmxlLnJvd3NbaV0gIT09IHRhYmxlUm93U2NvcGUpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdGFibGUucm93c1tpXS5zZWxlY3RlZCA9IGZhbHNlO1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICBpbnN0YW5jZUVsZW1lbnQuYWRkQ2xhc3MoJ2lzLXNlbGVjdGVkJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICBlbHNlIHtcbiAgICAgICAgICAgICAgICBpbnN0YW5jZUVsZW1lbnQucmVtb3ZlQ2xhc3MoJ2lzLXNlbGVjdGVkJyk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH0pO1xuICAgICAgICBpZiAodGFibGUucm93U2VsZWN0TW9kZSAhPT0gdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW1bdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW0ubm9uZV0gJiZcbiAgICAgICAgICAgIHNjb3BlLml0ZW0gIT09IHVuZGVmaW5lZCkge1xuICAgICAgICAgICAgaW5zdGFuY2VFbGVtZW50Lm9uKCdjbGljaycsIHNjb3BlLnJvd0NsaWNrKTtcbiAgICAgICAgfVxuICAgICAgICBpZiAodGFibGUucm93U2VsZWN0TW9kZSA9PT0gdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW1bdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW0ubm9uZV0pIHtcbiAgICAgICAgICAgIGluc3RhbmNlRWxlbWVudC5jc3MoJ2N1cnNvcicsICdkZWZhdWx0Jyk7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIHJldHVybiBUYWJsZVJvd0RpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLlRhYmxlUm93RGlyZWN0aXZlID0gVGFibGVSb3dEaXJlY3RpdmU7XG52YXIgVGFibGVSb3dTZWxlY3REaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIFRhYmxlUm93U2VsZWN0RGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnJlc3RyaWN0ID0gJ0UnO1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxzcGFuIGNsYXNzPVwibXMtVGFibGUtcm93Q2hlY2tcIj48L3NwYW4+JztcbiAgICAgICAgdGhpcy5yZXBsYWNlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gWydedWlmVGFibGUnLCAnXnVpZlRhYmxlUm93J107XG4gICAgfVxuICAgIFRhYmxlUm93U2VsZWN0RGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgVGFibGVSb3dTZWxlY3REaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIFRhYmxlUm93U2VsZWN0RGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlLCBpbnN0YW5jZUVsZW1lbnQsIGF0dHJzLCBjb250cm9sbGVycykge1xuICAgICAgICBzY29wZS5yb3dTZWxlY3RDbGljayA9IGZ1bmN0aW9uIChldikge1xuICAgICAgICAgICAgdmFyIHRhYmxlID0gY29udHJvbGxlcnNbMF07XG4gICAgICAgICAgICB2YXIgcm93ID0gY29udHJvbGxlcnNbMV07XG4gICAgICAgICAgICBpZiAodGFibGUucm93U2VsZWN0TW9kZSAhPT0gdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW1bdGFibGVSb3dTZWxlY3RNb2RlRW51bV8xLlRhYmxlUm93U2VsZWN0TW9kZUVudW0ubXVsdGlwbGVdKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKHJvdy5pdGVtID09PSB1bmRlZmluZWQgfHwgcm93Lml0ZW0gPT09IG51bGwpIHtcbiAgICAgICAgICAgICAgICB2YXIgc2hvdWxkU2VsZWN0QWxsID0gZmFsc2U7XG4gICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0YWJsZS5yb3dzLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICAgICAgICAgIGlmICh0YWJsZS5yb3dzW2ldLnNlbGVjdGVkICE9PSB0cnVlKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBzaG91bGRTZWxlY3RBbGwgPSB0cnVlO1xuICAgICAgICAgICAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgZm9yICh2YXIgaSA9IDA7IGkgPCB0YWJsZS5yb3dzLmxlbmd0aDsgaSsrKSB7XG4gICAgICAgICAgICAgICAgICAgIGlmICh0YWJsZS5yb3dzW2ldLnNlbGVjdGVkICE9PSBzaG91bGRTZWxlY3RBbGwpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgIHRhYmxlLnJvd3NbaV0uc2VsZWN0ZWQgPSBzaG91bGRTZWxlY3RBbGw7XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgc2NvcGUuJGFwcGx5KCk7XG4gICAgICAgICAgICB9XG4gICAgICAgIH07XG4gICAgICAgIGluc3RhbmNlRWxlbWVudC5vbignY2xpY2snLCBzY29wZS5yb3dTZWxlY3RDbGljayk7XG4gICAgfTtcbiAgICByZXR1cm4gVGFibGVSb3dTZWxlY3REaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5UYWJsZVJvd1NlbGVjdERpcmVjdGl2ZSA9IFRhYmxlUm93U2VsZWN0RGlyZWN0aXZlO1xudmFyIFRhYmxlQ2VsbERpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gVGFibGVDZWxsRGlyZWN0aXZlKCkge1xuICAgICAgICB0aGlzLnJlc3RyaWN0ID0gJ0UnO1xuICAgICAgICB0aGlzLnRyYW5zY2x1ZGUgPSB0cnVlO1xuICAgICAgICB0aGlzLnRlbXBsYXRlID0gJzxzcGFuIGNsYXNzPVwibXMtVGFibGUtY2VsbFwiIG5nLXRyYW5zY2x1ZGU+PC9zcGFuPic7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgfVxuICAgIFRhYmxlQ2VsbERpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IFRhYmxlQ2VsbERpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgcmV0dXJuIFRhYmxlQ2VsbERpcmVjdGl2ZTtcbn0pKCk7XG5leHBvcnRzLlRhYmxlQ2VsbERpcmVjdGl2ZSA9IFRhYmxlQ2VsbERpcmVjdGl2ZTtcbnZhciBUYWJsZUhlYWRlckRpcmVjdGl2ZSA9IChmdW5jdGlvbiAoKSB7XG4gICAgZnVuY3Rpb24gVGFibGVIZWFkZXJEaXJlY3RpdmUoKSB7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgICAgIHRoaXMudHJhbnNjbHVkZSA9IHRydWU7XG4gICAgICAgIHRoaXMucmVwbGFjZSA9IHRydWU7XG4gICAgICAgIHRoaXMudGVtcGxhdGUgPSAnPHNwYW4gY2xhc3M9XCJtcy1UYWJsZS1jZWxsXCIgbmctdHJhbnNjbHVkZT48L3NwYW4+JztcbiAgICAgICAgdGhpcy5yZXF1aXJlID0gJ151aWZUYWJsZSc7XG4gICAgfVxuICAgIFRhYmxlSGVhZGVyRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgVGFibGVIZWFkZXJEaXJlY3RpdmUoKTsgfTtcbiAgICAgICAgcmV0dXJuIGRpcmVjdGl2ZTtcbiAgICB9O1xuICAgIFRhYmxlSGVhZGVyRGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlLCBpbnN0YW5jZUVsZW1lbnQsIGF0dHJzLCB0YWJsZSkge1xuICAgICAgICBzY29wZS5oZWFkZXJDbGljayA9IGZ1bmN0aW9uIChldikge1xuICAgICAgICAgICAgaWYgKHRhYmxlLm9yZGVyQnkgPT09IGF0dHJzLnVpZk9yZGVyQnkpIHtcbiAgICAgICAgICAgICAgICB0YWJsZS5vcmRlckFzYyA9ICF0YWJsZS5vcmRlckFzYztcbiAgICAgICAgICAgIH1cbiAgICAgICAgICAgIGVsc2Uge1xuICAgICAgICAgICAgICAgIHRhYmxlLm9yZGVyQnkgPSBhdHRycy51aWZPcmRlckJ5O1xuICAgICAgICAgICAgICAgIHRhYmxlLm9yZGVyQXNjID0gdHJ1ZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfTtcbiAgICAgICAgc2NvcGUuJHdhdGNoKCd0YWJsZS5vcmRlckJ5JywgZnVuY3Rpb24gKG5ld09yZGVyQnksIG9sZE9yZGVyQnksIHRhYmxlSGVhZGVyU2NvcGUpIHtcbiAgICAgICAgICAgIGlmIChvbGRPcmRlckJ5ICE9PSBuZXdPcmRlckJ5ICYmXG4gICAgICAgICAgICAgICAgbmV3T3JkZXJCeSA9PT0gYXR0cnMudWlmT3JkZXJCeSkge1xuICAgICAgICAgICAgICAgIHZhciBjZWxscyA9IGluc3RhbmNlRWxlbWVudC5wYXJlbnQoKS5jaGlsZHJlbigpO1xuICAgICAgICAgICAgICAgIGZvciAodmFyIGkgPSAwOyBpIDwgY2VsbHMubGVuZ3RoOyBpKyspIHtcbiAgICAgICAgICAgICAgICAgICAgaWYgKGNlbGxzLmVxKGkpLmNoaWxkcmVuKCkubGVuZ3RoID09PSAyKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICBjZWxscy5lcShpKS5jaGlsZHJlbigpLmVxKDEpLnJlbW92ZSgpO1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIGluc3RhbmNlRWxlbWVudC5hcHBlbmQoJzxzcGFuIGNsYXNzPVwidWlmLXNvcnQtb3JkZXJcIj4mbmJzcDtcXFxuICAgICAgICAgICAgICAgIDxpIGNsYXNzPVwibXMtSWNvbiBtcy1JY29uLS1jYXJldERvd25cIiBhcmlhLWhpZGRlbj1cInRydWVcIj48L2k+PC9zcGFuPicpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICAgICAgc2NvcGUuJHdhdGNoKCd0YWJsZS5vcmRlckFzYycsIGZ1bmN0aW9uIChuZXdPcmRlckFzYywgb2xkT3JkZXJBc2MsIHRhYmxlSGVhZGVyU2NvcGUpIHtcbiAgICAgICAgICAgIGlmIChpbnN0YW5jZUVsZW1lbnQuY2hpbGRyZW4oKS5sZW5ndGggPT09IDIpIHtcbiAgICAgICAgICAgICAgICB2YXIgb2xkQ3NzQ2xhc3MgPSBvbGRPcmRlckFzYyA/ICdtcy1JY29uLS1jYXJldERvd24nIDogJ21zLUljb24tLWNhcmV0VXAnO1xuICAgICAgICAgICAgICAgIHZhciBuZXdDc3NDbGFzcyA9IG5ld09yZGVyQXNjID8gJ21zLUljb24tLWNhcmV0RG93bicgOiAnbXMtSWNvbi0tY2FyZXRVcCc7XG4gICAgICAgICAgICAgICAgaW5zdGFuY2VFbGVtZW50LmNoaWxkcmVuKCkuZXEoMSkuY2hpbGRyZW4oKS5lcSgwKS5yZW1vdmVDbGFzcyhvbGRDc3NDbGFzcykuYWRkQ2xhc3MobmV3Q3NzQ2xhc3MpO1xuICAgICAgICAgICAgfVxuICAgICAgICB9KTtcbiAgICAgICAgaWYgKCd1aWZPcmRlckJ5JyBpbiBhdHRycykge1xuICAgICAgICAgICAgaW5zdGFuY2VFbGVtZW50Lm9uKCdjbGljaycsIHNjb3BlLmhlYWRlckNsaWNrKTtcbiAgICAgICAgfVxuICAgIH07XG4gICAgcmV0dXJuIFRhYmxlSGVhZGVyRGlyZWN0aXZlO1xufSkoKTtcbmV4cG9ydHMuVGFibGVIZWFkZXJEaXJlY3RpdmUgPSBUYWJsZUhlYWRlckRpcmVjdGl2ZTtcbmV4cG9ydHMubW9kdWxlID0gbmcubW9kdWxlKCdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzLnRhYmxlJywgWydvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzJ10pXG4gICAgLmRpcmVjdGl2ZSgndWlmVGFibGUnLCBUYWJsZURpcmVjdGl2ZS5mYWN0b3J5KCkpXG4gICAgLmRpcmVjdGl2ZSgndWlmVGFibGVSb3cnLCBUYWJsZVJvd0RpcmVjdGl2ZS5mYWN0b3J5KCkpXG4gICAgLmRpcmVjdGl2ZSgndWlmVGFibGVSb3dTZWxlY3QnLCBUYWJsZVJvd1NlbGVjdERpcmVjdGl2ZS5mYWN0b3J5KCkpXG4gICAgLmRpcmVjdGl2ZSgndWlmVGFibGVDZWxsJywgVGFibGVDZWxsRGlyZWN0aXZlLmZhY3RvcnkoKSlcbiAgICAuZGlyZWN0aXZlKCd1aWZUYWJsZUhlYWRlcicsIFRhYmxlSGVhZGVyRGlyZWN0aXZlLmZhY3RvcnkoKSk7XG5cblxuXG4vKioqKioqKioqKioqKioqKipcbiAqKiBXRUJQQUNLIEZPT1RFUlxuICoqIC4vc3JjL2NvbXBvbmVudHMvdGFibGUvdGFibGVEaXJlY3RpdmUudHNcbiAqKiBtb2R1bGUgaWQgPSAyNFxuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIiwiJ3VzZSBzdHJpY3QnO1xuKGZ1bmN0aW9uIChUYWJsZVJvd1NlbGVjdE1vZGVFbnVtKSB7XG4gICAgVGFibGVSb3dTZWxlY3RNb2RlRW51bVtUYWJsZVJvd1NlbGVjdE1vZGVFbnVtW1wibm9uZVwiXSA9IDBdID0gXCJub25lXCI7XG4gICAgVGFibGVSb3dTZWxlY3RNb2RlRW51bVtUYWJsZVJvd1NlbGVjdE1vZGVFbnVtW1wic2luZ2xlXCJdID0gMV0gPSBcInNpbmdsZVwiO1xuICAgIFRhYmxlUm93U2VsZWN0TW9kZUVudW1bVGFibGVSb3dTZWxlY3RNb2RlRW51bVtcIm11bHRpcGxlXCJdID0gMl0gPSBcIm11bHRpcGxlXCI7XG59KShleHBvcnRzLlRhYmxlUm93U2VsZWN0TW9kZUVudW0gfHwgKGV4cG9ydHMuVGFibGVSb3dTZWxlY3RNb2RlRW51bSA9IHt9KSk7XG52YXIgVGFibGVSb3dTZWxlY3RNb2RlRW51bSA9IGV4cG9ydHMuVGFibGVSb3dTZWxlY3RNb2RlRW51bTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy90YWJsZS90YWJsZVJvd1NlbGVjdE1vZGVFbnVtLnRzXG4gKiogbW9kdWxlIGlkID0gMjVcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyIsIid1c2Ugc3RyaWN0JztcbnZhciBuZyA9IHJlcXVpcmUoJ2FuZ3VsYXInKTtcbnZhciBUZXh0RmllbGREaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIFRleHRGaWVsZERpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IG5nLWNsYXNzPVwie1xcJ2lzLWFjdGl2ZVxcJzogaXNBY3RpdmUsIFxcJ21zLVRleHRGaWVsZFxcJzogdHJ1ZSwgJyArXG4gICAgICAgICAgICAnXFwnbXMtVGV4dEZpZWxkLS11bmRlcmxpbmVkXFwnOiB1aWZVbmRlcmxpbmVkLCBcXCdtcy1UZXh0RmllbGQtLXBsYWNlaG9sZGVyXFwnOiBwbGFjZWhvbGRlcn1cIj4nICtcbiAgICAgICAgICAgICc8bGFiZWwgbmctc2hvdz1cImxhYmVsU2hvd25cIiBjbGFzcz1cIm1zLUxhYmVsXCI+e3t1aWZMYWJlbCB8fCBwbGFjZWhvbGRlcn19PC9sYWJlbD4nICtcbiAgICAgICAgICAgICc8aW5wdXQgbmctbW9kZWw9XCJuZ01vZGVsXCIgbmctYmx1cj1cImlucHV0Qmx1cigpXCIgbmctZm9jdXM9XCJpbnB1dEZvY3VzKClcIiBuZy1jbGljaz1cImlucHV0Q2xpY2soKVwiIGNsYXNzPVwibXMtVGV4dEZpZWxkLWZpZWxkXCIgLz4nICtcbiAgICAgICAgICAgICc8c3BhbiBjbGFzcz1cIm1zLVRleHRGaWVsZC1kZXNjcmlwdGlvblwiPnt7dWlmRGVzY3JpcHRpb259fTwvc3Bhbj4nICtcbiAgICAgICAgICAgICc8L2Rpdj4nO1xuICAgICAgICB0aGlzLnNjb3BlID0ge1xuICAgICAgICAgICAgbmdNb2RlbDogJz0nLFxuICAgICAgICAgICAgcGxhY2Vob2xkZXI6ICdAJyxcbiAgICAgICAgICAgIHVpZkRlc2NyaXB0aW9uOiAnQCcsXG4gICAgICAgICAgICB1aWZMYWJlbDogJ0AnXG4gICAgICAgIH07XG4gICAgICAgIHRoaXMucmVxdWlyZSA9ICc/bmdNb2RlbCc7XG4gICAgICAgIHRoaXMucmVzdHJpY3QgPSAnRSc7XG4gICAgfVxuICAgIFRleHRGaWVsZERpcmVjdGl2ZS5mYWN0b3J5ID0gZnVuY3Rpb24gKCkge1xuICAgICAgICB2YXIgZGlyZWN0aXZlID0gZnVuY3Rpb24gKCkgeyByZXR1cm4gbmV3IFRleHRGaWVsZERpcmVjdGl2ZSgpOyB9O1xuICAgICAgICByZXR1cm4gZGlyZWN0aXZlO1xuICAgIH07XG4gICAgVGV4dEZpZWxkRGlyZWN0aXZlLnByb3RvdHlwZS5saW5rID0gZnVuY3Rpb24gKHNjb3BlLCBpbnN0YW5jZUVsZW1lbnQsIGF0dHJzLCBuZ01vZGVsKSB7XG4gICAgICAgIHNjb3BlLmxhYmVsU2hvd24gPSB0cnVlO1xuICAgICAgICBzY29wZS51aWZVbmRlcmxpbmVkID0gJ3VpZlVuZGVybGluZWQnIGluIGF0dHJzO1xuICAgICAgICBzY29wZS5pbnB1dEZvY3VzID0gZnVuY3Rpb24gKGV2KSB7XG4gICAgICAgICAgICBpZiAoc2NvcGUudWlmVW5kZXJsaW5lZCkge1xuICAgICAgICAgICAgICAgIHNjb3BlLmlzQWN0aXZlID0gdHJ1ZTtcbiAgICAgICAgICAgIH1cbiAgICAgICAgfTtcbiAgICAgICAgc2NvcGUuaW5wdXRDbGljayA9IGZ1bmN0aW9uIChldikge1xuICAgICAgICAgICAgaWYgKHNjb3BlLnBsYWNlaG9sZGVyKSB7XG4gICAgICAgICAgICAgICAgc2NvcGUubGFiZWxTaG93biA9IGZhbHNlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9O1xuICAgICAgICBzY29wZS5pbnB1dEJsdXIgPSBmdW5jdGlvbiAoZXYpIHtcbiAgICAgICAgICAgIHZhciBpbnB1dCA9IGluc3RhbmNlRWxlbWVudC5maW5kKCdpbnB1dCcpO1xuICAgICAgICAgICAgaWYgKHNjb3BlLnBsYWNlaG9sZGVyICYmIGlucHV0LnZhbCgpLmxlbmd0aCA9PT0gMCkge1xuICAgICAgICAgICAgICAgIHNjb3BlLmxhYmVsU2hvd24gPSB0cnVlO1xuICAgICAgICAgICAgfVxuICAgICAgICAgICAgaWYgKHNjb3BlLnVpZlVuZGVybGluZWQpIHtcbiAgICAgICAgICAgICAgICBzY29wZS5pc0FjdGl2ZSA9IGZhbHNlO1xuICAgICAgICAgICAgfVxuICAgICAgICB9O1xuICAgICAgICBpZiAobmdNb2RlbCAhPSBudWxsKSB7XG4gICAgICAgICAgICBuZ01vZGVsLiRyZW5kZXIgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgICAgICAgc2NvcGUubGFiZWxTaG93biA9ICFuZ01vZGVsLiR2aWV3VmFsdWU7XG4gICAgICAgICAgICB9O1xuICAgICAgICB9XG4gICAgfTtcbiAgICByZXR1cm4gVGV4dEZpZWxkRGlyZWN0aXZlO1xufSkoKTtcbmV4cG9ydHMuVGV4dEZpZWxkRGlyZWN0aXZlID0gVGV4dEZpZWxkRGlyZWN0aXZlO1xuZXhwb3J0cy5tb2R1bGUgPSBuZy5tb2R1bGUoJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMudGV4dGZpZWxkJywgW1xuICAgICdvZmZpY2V1aWZhYnJpYy5jb21wb25lbnRzJ1xuXSlcbiAgICAuZGlyZWN0aXZlKCd1aWZUZXh0ZmllbGQnLCBUZXh0RmllbGREaXJlY3RpdmUuZmFjdG9yeSgpKTtcblxuXG5cbi8qKioqKioqKioqKioqKioqKlxuICoqIFdFQlBBQ0sgRk9PVEVSXG4gKiogLi9zcmMvY29tcG9uZW50cy90ZXh0ZmllbGQvdGV4dEZpZWxkRGlyZWN0aXZlLnRzXG4gKiogbW9kdWxlIGlkID0gMjZcbiAqKiBtb2R1bGUgY2h1bmtzID0gMFxuICoqLyIsIid1c2Ugc3RyaWN0JztcbnZhciBuZyA9IHJlcXVpcmUoJ2FuZ3VsYXInKTtcbnZhciBUb2dnbGVEaXJlY3RpdmUgPSAoZnVuY3Rpb24gKCkge1xuICAgIGZ1bmN0aW9uIFRvZ2dsZURpcmVjdGl2ZSgpIHtcbiAgICAgICAgdGhpcy50ZW1wbGF0ZSA9ICc8ZGl2IG5nLWNsYXNzPVwidG9nZ2xlQ2xhc3NcIj4nICtcbiAgICAgICAgICAgICc8c3BhbiBjbGFzcz1cIm1zLVRvZ2dsZS1kZXNjcmlwdGlvblwiPjxuZy10cmFuc2NsdWRlLz48L3NwYW4+JyArXG4gICAgICAgICAgICAnPGlucHV0IHR5cGU9XCJjaGVja2JveFwiIGlkPVwie3s6OiRpZH19XCIgY2xhc3M9XCJtcy1Ub2dnbGUtaW5wdXRcIiBuZy1tb2RlbD1cIm5nTW9kZWxcIiAvPicgK1xuICAgICAgICAgICAgJzxsYWJlbCBmb3I9XCJ7ezo6JGlkfX1cIiBjbGFzcz1cIm1zLVRvZ2dsZS1maWVsZFwiPicgK1xuICAgICAgICAgICAgJzxzcGFuIGNsYXNzPVwibXMtTGFiZWwgbXMtTGFiZWwtLW9mZlwiPnt7dWlmTGFiZWxPZmZ9fTwvc3Bhbj4nICtcbiAgICAgICAgICAgICc8c3BhbiBjbGFzcz1cIm1zLUxhYmVsIG1zLUxhYmVsLS1vblwiPnt7dWlmTGFiZWxPbn19PC9zcGFuPicgK1xuICAgICAgICAgICAgJzwvbGFiZWw+JyArXG4gICAgICAgICAgICAnPC9kaXY+JztcbiAgICAgICAgdGhpcy5yZXN0cmljdCA9ICdFJztcbiAgICAgICAgdGhpcy50cmFuc2NsdWRlID0gdHJ1ZTtcbiAgICAgICAgdGhpcy5zY29wZSA9IHtcbiAgICAgICAgICAgIG5nTW9kZWw6ICc9PycsXG4gICAgICAgICAgICB1aWZMYWJlbE9mZjogJ0AnLFxuICAgICAgICAgICAgdWlmTGFiZWxPbjogJ0AnLFxuICAgICAgICAgICAgdWlmVGV4dExvY2F0aW9uOiAnQCdcbiAgICAgICAgfTtcbiAgICB9XG4gICAgVG9nZ2xlRGlyZWN0aXZlLmZhY3RvcnkgPSBmdW5jdGlvbiAoKSB7XG4gICAgICAgIHZhciBkaXJlY3RpdmUgPSBmdW5jdGlvbiAoKSB7IHJldHVybiBuZXcgVG9nZ2xlRGlyZWN0aXZlKCk7IH07XG4gICAgICAgIHJldHVybiBkaXJlY3RpdmU7XG4gICAgfTtcbiAgICBUb2dnbGVEaXJlY3RpdmUucHJvdG90eXBlLmxpbmsgPSBmdW5jdGlvbiAoc2NvcGUsIGVsZW0sIGF0dHJzKSB7XG4gICAgICAgIHNjb3BlLnRvZ2dsZUNsYXNzID0gJ21zLVRvZ2dsZSc7XG4gICAgICAgIGlmIChzY29wZS51aWZUZXh0TG9jYXRpb24pIHtcbiAgICAgICAgICAgIHZhciBsb2MgPSBzY29wZS51aWZUZXh0TG9jYXRpb247XG4gICAgICAgICAgICBsb2MgPSBsb2MuY2hhckF0KDApLnRvVXBwZXJDYXNlKCkgKyBsb2Muc2xpY2UoMSk7XG4gICAgICAgICAgICBzY29wZS50b2dnbGVDbGFzcyArPSAnIG1zLVRvZ2dsZS0tdGV4dCcgKyBsb2M7XG4gICAgICAgIH1cbiAgICB9O1xuICAgIHJldHVybiBUb2dnbGVEaXJlY3RpdmU7XG59KSgpO1xuZXhwb3J0cy5Ub2dnbGVEaXJlY3RpdmUgPSBUb2dnbGVEaXJlY3RpdmU7XG5leHBvcnRzLm1vZHVsZSA9IG5nLm1vZHVsZSgnb2ZmaWNldWlmYWJyaWMuY29tcG9uZW50cy50b2dnbGUnLCBbXG4gICAgJ29mZmljZXVpZmFicmljLmNvbXBvbmVudHMnXG5dKVxuICAgIC5kaXJlY3RpdmUoJ3VpZlRvZ2dsZScsIFRvZ2dsZURpcmVjdGl2ZS5mYWN0b3J5KCkpO1xuXG5cblxuLyoqKioqKioqKioqKioqKioqXG4gKiogV0VCUEFDSyBGT09URVJcbiAqKiAuL3NyYy9jb21wb25lbnRzL3RvZ2dsZS90b2dnbGVEaXJlY3RpdmUudHNcbiAqKiBtb2R1bGUgaWQgPSAyN1xuICoqIG1vZHVsZSBjaHVua3MgPSAwXG4gKiovIl0sInNvdXJjZVJvb3QiOiIifQ== |
src/components/UserList/index.js | hyy1115/react-redux-webpack2 | import React from 'react'
import { List, message, Avatar, Spin, Input } from 'antd'
import InfiniteScroll from 'react-infinite-scroller'
import './index.less'
const Search = Input.Search
class UserList extends React.Component {
state = {
data: [],
loading: false,
hasMore: true
}
getData = (callback) => {}
componentDidMount () {
this.getData((res) => {
this.setState({
data: res.results
})
})
}
handleInfiniteOnLoad = () => {
let data = this.state.data
this.setState({
loading: true
})
if (data.length > 14) {
message.warning('Infinite List loaded all')
this.setState({
hasMore: false,
loading: false
})
return
}
this.getData((res) => {
data = data.concat(res.results)
this.setState({
data,
loading: false
})
})
}
render () {
return (
<div className="user-list">
<Search
placeholder="input search text"
onSearch={value => console.log(value)}
enterButton
/>
<div className="demo-infinite-container">
<InfiniteScroll
initialLoad={ false }
pageStart={ 0 }
loadMore={ this.handleInfiniteOnLoad }
hasMore={ !this.state.loading && this.state.hasMore }
useWindow={ false }
>
<List
dataSource={ this.state.data }
renderItem={ item => (
<List.Item key={ item.id }>
<List.Item.Meta
avatar={ <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png"/> }
title={ <a href="https://ant.design">{ item.name.last }</a> }
description={ item.email }
/>
<div>Content</div>
</List.Item>
) }
>
{ this.state.loading && this.state.hasMore && (
<div className="demo-loading-container">
<Spin/>
</div>
) }
</List>
</InfiniteScroll>
</div>
</div>
)
}
}
export default UserList |
js/extjs/ext-all.js | MatthiasLohr/phpDNSAdmin | /*
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* [email protected]
* http://www.sencha.com/license
*/
(function(){var h=Ext.util,k=Ext.each,g=true,i=false;h.Observable=function(){var l=this,m=l.events;if(l.listeners){l.on(l.listeners);delete l.listeners}l.events=m||{}};h.Observable.prototype={filterOptRe:/^(?:scope|delay|buffer|single)$/,fireEvent:function(){var l=Array.prototype.slice.call(arguments,0),n=l[0].toLowerCase(),o=this,m=g,r=o.events[n],t,p,s;if(o.eventsSuspended===g){if(p=o.eventQueue){p.push(l)}}else{if(typeof r=="object"){if(r.bubble){if(r.fire.apply(r,l.slice(1))===i){return i}s=o.getBubbleTarget&&o.getBubbleTarget();if(s&&s.enableBubble){t=s.events[n];if(!t||typeof t!="object"||!t.bubble){s.enableBubble(n)}return s.fireEvent.apply(s,l)}}else{l.shift();m=r.fire.apply(r,l)}}}return m},addListener:function(l,n,m,s){var p=this,r,t,q;if(typeof l=="object"){s=l;for(r in s){t=s[r];if(!p.filterOptRe.test(r)){p.addListener(r,t.fn||t,t.scope||s.scope,t.fn?t:s)}}}else{l=l.toLowerCase();q=p.events[l]||g;if(typeof q=="boolean"){p.events[l]=q=new h.Event(p,l)}q.addListener(n,m,typeof s=="object"?s:{})}},removeListener:function(l,n,m){var o=this.events[l.toLowerCase()];if(typeof o=="object"){o.removeListener(n,m)}},purgeListeners:function(){var n=this.events,l,m;for(m in n){l=n[m];if(typeof l=="object"){l.clearListeners()}}},addEvents:function(p){var n=this;n.events=n.events||{};if(typeof p=="string"){var l=arguments,m=l.length;while(m--){n.events[l[m]]=n.events[l[m]]||g}}else{Ext.applyIf(n.events,p)}},hasListener:function(l){var m=this.events[l.toLowerCase()];return typeof m=="object"&&m.listeners.length>0},suspendEvents:function(l){this.eventsSuspended=g;if(l&&!this.eventQueue){this.eventQueue=[]}},resumeEvents:function(){var l=this,m=l.eventQueue||[];l.eventsSuspended=i;delete l.eventQueue;k(m,function(n){l.fireEvent.apply(l,n)})}};var d=h.Observable.prototype;d.on=d.addListener;d.un=d.removeListener;h.Observable.releaseCapture=function(l){l.fireEvent=d.fireEvent};function e(m,n,l){return function(){if(n.target==arguments[0]){m.apply(l,Array.prototype.slice.call(arguments,0))}}}function b(p,q,m,n){m.task=new h.DelayedTask();return function(){m.task.delay(q.buffer,p,n,Array.prototype.slice.call(arguments,0))}}function c(n,o,m,l){return function(){o.removeListener(m,l);return n.apply(l,arguments)}}function a(p,q,m,n){return function(){var l=new h.DelayedTask(),o=Array.prototype.slice.call(arguments,0);if(!m.tasks){m.tasks=[]}m.tasks.push(l);l.delay(q.delay||10,function(){m.tasks.remove(l);p.apply(n,o)},n)}}h.Event=function(m,l){this.name=l;this.obj=m;this.listeners=[]};h.Event.prototype={addListener:function(p,o,n){var q=this,m;o=o||q.obj;if(!q.isListening(p,o)){m=q.createListener(p,o,n);if(q.firing){q.listeners=q.listeners.slice(0)}q.listeners.push(m)}},createListener:function(q,p,r){r=r||{};p=p||this.obj;var m={fn:q,scope:p,options:r},n=q;if(r.target){n=e(n,r,p)}if(r.delay){n=a(n,r,m,p)}if(r.single){n=c(n,this,q,p)}if(r.buffer){n=b(n,r,m,p)}m.fireFn=n;return m},findListener:function(p,o){var q=this.listeners,n=q.length,m;o=o||this.obj;while(n--){m=q[n];if(m){if(m.fn==p&&m.scope==o){return n}}}return -1},isListening:function(m,l){return this.findListener(m,l)!=-1},removeListener:function(r,q){var p,m,n,s=this,o=i;if((p=s.findListener(r,q))!=-1){if(s.firing){s.listeners=s.listeners.slice(0)}m=s.listeners[p];if(m.task){m.task.cancel();delete m.task}n=m.tasks&&m.tasks.length;if(n){while(n--){m.tasks[n].cancel()}delete m.tasks}s.listeners.splice(p,1);o=g}return o},clearListeners:function(){var o=this,m=o.listeners,n=m.length;while(n--){o.removeListener(m[n].fn,m[n].scope)}},fire:function(){var r=this,q=r.listeners,m=q.length,p=0,n;if(m>0){r.firing=g;var o=Array.prototype.slice.call(arguments,0);for(;p<m;p++){n=q[p];if(n&&n.fireFn.apply(n.scope||r.obj||window,o)===i){return(r.firing=i)}}}r.firing=i;return g}}})();Ext.DomHelper=function(){var x=null,l=/^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i,n=/^table|tbody|tr|td$/i,d=/tag|children|cn|html$/i,t=/td|tr|tbody/i,p=/([a-z0-9-]+)\s*:\s*([^;\s]+(?:\s*[^;\s]+)*);?/gi,v=/end/i,s,o="afterbegin",q="afterend",c="beforebegin",r="beforeend",a="<table>",i="</table>",b=a+"<tbody>",k="</tbody>"+i,m=b+"<tr>",w="</tr>"+k;function h(B,D,C,E,A,y){var z=s.insertHtml(E,Ext.getDom(B),u(D));return C?Ext.get(z,true):z}function u(D){var z="",y,C,B,E;if(typeof D=="string"){z=D}else{if(Ext.isArray(D)){for(var A=0;A<D.length;A++){if(D[A]){z+=u(D[A])}}}else{z+="<"+(D.tag=D.tag||"div");for(y in D){C=D[y];if(!d.test(y)){if(typeof C=="object"){z+=" "+y+'="';for(B in C){z+=B+":"+C[B]+";"}z+='"'}else{z+=" "+({cls:"class",htmlFor:"for"}[y]||y)+'="'+C+'"'}}}if(l.test(D.tag)){z+="/>"}else{z+=">";if((E=D.children||D.cn)){z+=u(E)}else{if(D.html){z+=D.html}}z+="</"+D.tag+">"}}}return z}function g(F,C,B,D){x.innerHTML=[C,B,D].join("");var y=-1,A=x,z;while(++y<F){A=A.firstChild}if(z=A.nextSibling){var E=document.createDocumentFragment();while(A){z=A.nextSibling;E.appendChild(A);A=z}A=E}return A}function e(y,z,B,A){var C,D;x=x||document.createElement("div");if(y=="td"&&(z==o||z==r)||!t.test(y)&&(z==c||z==q)){return}D=z==c?B:z==q?B.nextSibling:z==o?B.firstChild:null;if(z==c||z==q){B=B.parentNode}if(y=="td"||(y=="tr"&&(z==r||z==o))){C=g(4,m,A,w)}else{if((y=="tbody"&&(z==r||z==o))||(y=="tr"&&(z==c||z==q))){C=g(3,b,A,k)}else{C=g(2,a,A,i)}}B.insertBefore(C,D);return C}s={markup:function(y){return u(y)},applyStyles:function(y,z){if(z){var A;y=Ext.fly(y);if(typeof z=="function"){z=z.call()}if(typeof z=="string"){p.lastIndex=0;while((A=p.exec(z))){y.setStyle(A[1],A[2])}}else{if(typeof z=="object"){y.setStyle(z)}}}},insertHtml:function(D,y,E){var C={},A,G,F,H,B,z;D=D.toLowerCase();C[c]=["BeforeBegin","previousSibling"];C[q]=["AfterEnd","nextSibling"];if(y.insertAdjacentHTML){if(n.test(y.tagName)&&(z=e(y.tagName.toLowerCase(),D,y,E))){return z}C[o]=["AfterBegin","firstChild"];C[r]=["BeforeEnd","lastChild"];if((A=C[D])){y.insertAdjacentHTML(A[0],E);return y[A[1]]}}else{F=y.ownerDocument.createRange();G="setStart"+(v.test(D)?"After":"Before");if(C[D]){F[G](y);H=F.createContextualFragment(E);y.parentNode.insertBefore(H,D==c?y:y.nextSibling);return y[(D==c?"previous":"next")+"Sibling"]}else{B=(D==o?"first":"last")+"Child";if(y.firstChild){F[G](y[B]);H=F.createContextualFragment(E);if(D==o){y.insertBefore(H,y.firstChild)}else{y.appendChild(H)}}else{y.innerHTML=E}return y[B]}}throw'Illegal insertion point -> "'+D+'"'},insertBefore:function(y,A,z){return h(y,A,z,c)},insertAfter:function(y,A,z){return h(y,A,z,q,"nextSibling")},insertFirst:function(y,A,z){return h(y,A,z,o,"firstChild")},append:function(y,A,z){return h(y,A,z,r,"",true)},overwrite:function(y,A,z){y=Ext.getDom(y);y.innerHTML=u(A);return z?Ext.get(y.firstChild):y.firstChild},createHtml:u};return s}();Ext.Template=function(h){var k=this,c=arguments,e=[],d;if(Ext.isArray(h)){h=h.join("")}else{if(c.length>1){for(var g=0,b=c.length;g<b;g++){d=c[g];if(typeof d=="object"){Ext.apply(k,d)}else{e.push(d)}}h=e.join("")}}k.html=h;if(k.compiled){k.compile()}};Ext.Template.prototype={re:/\{([\w-]+)\}/g,applyTemplate:function(a){var b=this;return b.compiled?b.compiled(a):b.html.replace(b.re,function(c,d){return a[d]!==undefined?a[d]:""})},set:function(a,c){var b=this;b.html=a;b.compiled=null;return c?b.compile():b},compile:function(){var me=this,sep=Ext.isGecko?"+":",";function fn(m,name){name="values['"+name+"']";return"'"+sep+"("+name+" == undefined ? '' : "+name+")"+sep+"'"}eval("this.compiled = function(values){ return "+(Ext.isGecko?"'":"['")+me.html.replace(/\\/g,"\\\\").replace(/(\r\n|\n)/g,"\\n").replace(/'/g,"\\'").replace(this.re,fn)+(Ext.isGecko?"';};":"'].join('');};"));return me},insertFirst:function(b,a,c){return this.doInsert("afterBegin",b,a,c)},insertBefore:function(b,a,c){return this.doInsert("beforeBegin",b,a,c)},insertAfter:function(b,a,c){return this.doInsert("afterEnd",b,a,c)},append:function(b,a,c){return this.doInsert("beforeEnd",b,a,c)},doInsert:function(c,e,b,a){e=Ext.getDom(e);var d=Ext.DomHelper.insertHtml(c,e,this.applyTemplate(b));return a?Ext.get(d,true):d},overwrite:function(b,a,c){b=Ext.getDom(b);b.innerHTML=this.applyTemplate(a);return c?Ext.get(b.firstChild,true):b.firstChild}};Ext.Template.prototype.apply=Ext.Template.prototype.applyTemplate;Ext.Template.from=function(b,a){b=Ext.getDom(b);return new Ext.Template(b.value||b.innerHTML,a||"")};Ext.DomQuery=function(){var cache={},simpleCache={},valueCache={},nonSpace=/\S/,trimRe=/^\s+|\s+$/g,tplRe=/\{(\d+)\}/g,modeRe=/^(\s?[\/>+~]\s?|\s|$)/,tagTokenRe=/^(#)?([\w-\*]+)/,nthRe=/(\d*)n\+?(\d*)/,nthRe2=/\D/,isIE=window.ActiveXObject?true:false,key=30803;eval("var batch = 30803;");function child(parent,index){var i=0,n=parent.firstChild;while(n){if(n.nodeType==1){if(++i==index){return n}}n=n.nextSibling}return null}function next(n){while((n=n.nextSibling)&&n.nodeType!=1){}return n}function prev(n){while((n=n.previousSibling)&&n.nodeType!=1){}return n}function children(parent){var n=parent.firstChild,nodeIndex=-1,nextNode;while(n){nextNode=n.nextSibling;if(n.nodeType==3&&!nonSpace.test(n.nodeValue)){parent.removeChild(n)}else{n.nodeIndex=++nodeIndex}n=nextNode}return this}function byClassName(nodeSet,cls){if(!cls){return nodeSet}var result=[],ri=-1;for(var i=0,ci;ci=nodeSet[i];i++){if((" "+ci.className+" ").indexOf(cls)!=-1){result[++ri]=ci}}return result}function attrValue(n,attr){if(!n.tagName&&typeof n.length!="undefined"){n=n[0]}if(!n){return null}if(attr=="for"){return n.htmlFor}if(attr=="class"||attr=="className"){return n.className}return n.getAttribute(attr)||n[attr]}function getNodes(ns,mode,tagName){var result=[],ri=-1,cs;if(!ns){return result}tagName=tagName||"*";if(typeof ns.getElementsByTagName!="undefined"){ns=[ns]}if(!mode){for(var i=0,ni;ni=ns[i];i++){cs=ni.getElementsByTagName(tagName);for(var j=0,ci;ci=cs[j];j++){result[++ri]=ci}}}else{if(mode=="/"||mode==">"){var utag=tagName.toUpperCase();for(var i=0,ni,cn;ni=ns[i];i++){cn=ni.childNodes;for(var j=0,cj;cj=cn[j];j++){if(cj.nodeName==utag||cj.nodeName==tagName||tagName=="*"){result[++ri]=cj}}}}else{if(mode=="+"){var utag=tagName.toUpperCase();for(var i=0,n;n=ns[i];i++){while((n=n.nextSibling)&&n.nodeType!=1){}if(n&&(n.nodeName==utag||n.nodeName==tagName||tagName=="*")){result[++ri]=n}}}else{if(mode=="~"){var utag=tagName.toUpperCase();for(var i=0,n;n=ns[i];i++){while((n=n.nextSibling)){if(n.nodeName==utag||n.nodeName==tagName||tagName=="*"){result[++ri]=n}}}}}}}return result}function concat(a,b){if(b.slice){return a.concat(b)}for(var i=0,l=b.length;i<l;i++){a[a.length]=b[i]}return a}function byTag(cs,tagName){if(cs.tagName||cs==document){cs=[cs]}if(!tagName){return cs}var result=[],ri=-1;tagName=tagName.toLowerCase();for(var i=0,ci;ci=cs[i];i++){if(ci.nodeType==1&&ci.tagName.toLowerCase()==tagName){result[++ri]=ci}}return result}function byId(cs,id){if(cs.tagName||cs==document){cs=[cs]}if(!id){return cs}var result=[],ri=-1;for(var i=0,ci;ci=cs[i];i++){if(ci&&ci.id==id){result[++ri]=ci;return result}}return result}function byAttribute(cs,attr,value,op,custom){var result=[],ri=-1,useGetStyle=custom=="{",fn=Ext.DomQuery.operators[op],a,xml,hasXml;for(var i=0,ci;ci=cs[i];i++){if(ci.nodeType!=1){continue}if(!hasXml){xml=Ext.DomQuery.isXml(ci);hasXml=true}if(!xml){if(useGetStyle){a=Ext.DomQuery.getStyle(ci,attr)}else{if(attr=="class"||attr=="className"){a=ci.className}else{if(attr=="for"){a=ci.htmlFor}else{if(attr=="href"){a=ci.getAttribute("href",2)}else{a=ci.getAttribute(attr)}}}}}else{a=ci.getAttribute(attr)}if((fn&&fn(a,value))||(!fn&&a)){result[++ri]=ci}}return result}function byPseudo(cs,name,value){return Ext.DomQuery.pseudos[name](cs,value)}function nodupIEXml(cs){var d=++key,r;cs[0].setAttribute("_nodup",d);r=[cs[0]];for(var i=1,len=cs.length;i<len;i++){var c=cs[i];if(!c.getAttribute("_nodup")!=d){c.setAttribute("_nodup",d);r[r.length]=c}}for(var i=0,len=cs.length;i<len;i++){cs[i].removeAttribute("_nodup")}return r}function nodup(cs){if(!cs){return[]}var len=cs.length,c,i,r=cs,cj,ri=-1;if(!len||typeof cs.nodeType!="undefined"||len==1){return cs}if(isIE&&typeof cs[0].selectSingleNode!="undefined"){return nodupIEXml(cs)}var d=++key;cs[0]._nodup=d;for(i=1;c=cs[i];i++){if(c._nodup!=d){c._nodup=d}else{r=[];for(var j=0;j<i;j++){r[++ri]=cs[j]}for(j=i+1;cj=cs[j];j++){if(cj._nodup!=d){cj._nodup=d;r[++ri]=cj}}return r}}return r}function quickDiffIEXml(c1,c2){var d=++key,r=[];for(var i=0,len=c1.length;i<len;i++){c1[i].setAttribute("_qdiff",d)}for(var i=0,len=c2.length;i<len;i++){if(c2[i].getAttribute("_qdiff")!=d){r[r.length]=c2[i]}}for(var i=0,len=c1.length;i<len;i++){c1[i].removeAttribute("_qdiff")}return r}function quickDiff(c1,c2){var len1=c1.length,d=++key,r=[];if(!len1){return c2}if(isIE&&typeof c1[0].selectSingleNode!="undefined"){return quickDiffIEXml(c1,c2)}for(var i=0;i<len1;i++){c1[i]._qdiff=d}for(var i=0,len=c2.length;i<len;i++){if(c2[i]._qdiff!=d){r[r.length]=c2[i]}}return r}function quickId(ns,mode,root,id){if(ns==root){var d=root.ownerDocument||root;return d.getElementById(id)}ns=getNodes(ns,mode,"*");return byId(ns,id)}return{getStyle:function(el,name){return Ext.fly(el).getStyle(name)},compile:function(path,type){type=type||"select";var fn=["var f = function(root){\n var mode; ++batch; var n = root || document;\n"],mode,lastPath,matchers=Ext.DomQuery.matchers,matchersLn=matchers.length,modeMatch,lmode=path.match(modeRe);if(lmode&&lmode[1]){fn[fn.length]='mode="'+lmode[1].replace(trimRe,"")+'";';path=path.replace(lmode[1],"")}while(path.substr(0,1)=="/"){path=path.substr(1)}while(path&&lastPath!=path){lastPath=path;var tokenMatch=path.match(tagTokenRe);if(type=="select"){if(tokenMatch){if(tokenMatch[1]=="#"){fn[fn.length]='n = quickId(n, mode, root, "'+tokenMatch[2]+'");'}else{fn[fn.length]='n = getNodes(n, mode, "'+tokenMatch[2]+'");'}path=path.replace(tokenMatch[0],"")}else{if(path.substr(0,1)!="@"){fn[fn.length]='n = getNodes(n, mode, "*");'}}}else{if(tokenMatch){if(tokenMatch[1]=="#"){fn[fn.length]='n = byId(n, "'+tokenMatch[2]+'");'}else{fn[fn.length]='n = byTag(n, "'+tokenMatch[2]+'");'}path=path.replace(tokenMatch[0],"")}}while(!(modeMatch=path.match(modeRe))){var matched=false;for(var j=0;j<matchersLn;j++){var t=matchers[j];var m=path.match(t.re);if(m){fn[fn.length]=t.select.replace(tplRe,function(x,i){return m[i]});path=path.replace(m[0],"");matched=true;break}}if(!matched){throw'Error parsing selector, parsing failed at "'+path+'"'}}if(modeMatch[1]){fn[fn.length]='mode="'+modeMatch[1].replace(trimRe,"")+'";';path=path.replace(modeMatch[1],"")}}fn[fn.length]="return nodup(n);\n}";eval(fn.join(""));return f},jsSelect:function(path,root,type){root=root||document;if(typeof root=="string"){root=document.getElementById(root)}var paths=path.split(","),results=[];for(var i=0,len=paths.length;i<len;i++){var subPath=paths[i].replace(trimRe,"");if(!cache[subPath]){cache[subPath]=Ext.DomQuery.compile(subPath);if(!cache[subPath]){throw subPath+" is not a valid selector"}}var result=cache[subPath](root);if(result&&result!=document){results=results.concat(result)}}if(paths.length>1){return nodup(results)}return results},isXml:function(el){var docEl=(el?el.ownerDocument||el:0).documentElement;return docEl?docEl.nodeName!=="HTML":false},select:document.querySelectorAll?function(path,root,type){root=root||document;if(!Ext.DomQuery.isXml(root)){try{var cs=root.querySelectorAll(path);return Ext.toArray(cs)}catch(ex){}}return Ext.DomQuery.jsSelect.call(this,path,root,type)}:function(path,root,type){return Ext.DomQuery.jsSelect.call(this,path,root,type)},selectNode:function(path,root){return Ext.DomQuery.select(path,root)[0]},selectValue:function(path,root,defaultValue){path=path.replace(trimRe,"");if(!valueCache[path]){valueCache[path]=Ext.DomQuery.compile(path,"select")}var n=valueCache[path](root),v;n=n[0]?n[0]:n;if(typeof n.normalize=="function"){n.normalize()}v=(n&&n.firstChild?n.firstChild.nodeValue:null);return((v===null||v===undefined||v==="")?defaultValue:v)},selectNumber:function(path,root,defaultValue){var v=Ext.DomQuery.selectValue(path,root,defaultValue||0);return parseFloat(v)},is:function(el,ss){if(typeof el=="string"){el=document.getElementById(el)}var isArray=Ext.isArray(el),result=Ext.DomQuery.filter(isArray?el:[el],ss);return isArray?(result.length==el.length):(result.length>0)},filter:function(els,ss,nonMatches){ss=ss.replace(trimRe,"");if(!simpleCache[ss]){simpleCache[ss]=Ext.DomQuery.compile(ss,"simple")}var result=simpleCache[ss](els);return nonMatches?quickDiff(result,els):result},matchers:[{re:/^\.([\w-]+)/,select:'n = byClassName(n, " {1} ");'},{re:/^\:([\w-]+)(?:\(((?:[^\s>\/]*|.*?))\))?/,select:'n = byPseudo(n, "{1}", "{2}");'},{re:/^(?:([\[\{])(?:@)?([\w-]+)\s?(?:(=|.=)\s?['"]?(.*?)["']?)?[\]\}])/,select:'n = byAttribute(n, "{2}", "{4}", "{3}", "{1}");'},{re:/^#([\w-]+)/,select:'n = byId(n, "{1}");'},{re:/^@([\w-]+)/,select:'return {firstChild:{nodeValue:attrValue(n, "{1}")}};'}],operators:{"=":function(a,v){return a==v},"!=":function(a,v){return a!=v},"^=":function(a,v){return a&&a.substr(0,v.length)==v},"$=":function(a,v){return a&&a.substr(a.length-v.length)==v},"*=":function(a,v){return a&&a.indexOf(v)!==-1},"%=":function(a,v){return(a%v)==0},"|=":function(a,v){return a&&(a==v||a.substr(0,v.length+1)==v+"-")},"~=":function(a,v){return a&&(" "+a+" ").indexOf(" "+v+" ")!=-1}},pseudos:{"first-child":function(c){var r=[],ri=-1,n;for(var i=0,ci;ci=n=c[i];i++){while((n=n.previousSibling)&&n.nodeType!=1){}if(!n){r[++ri]=ci}}return r},"last-child":function(c){var r=[],ri=-1,n;for(var i=0,ci;ci=n=c[i];i++){while((n=n.nextSibling)&&n.nodeType!=1){}if(!n){r[++ri]=ci}}return r},"nth-child":function(c,a){var r=[],ri=-1,m=nthRe.exec(a=="even"&&"2n"||a=="odd"&&"2n+1"||!nthRe2.test(a)&&"n+"+a||a),f=(m[1]||1)-0,l=m[2]-0;for(var i=0,n;n=c[i];i++){var pn=n.parentNode;if(batch!=pn._batch){var j=0;for(var cn=pn.firstChild;cn;cn=cn.nextSibling){if(cn.nodeType==1){cn.nodeIndex=++j}}pn._batch=batch}if(f==1){if(l==0||n.nodeIndex==l){r[++ri]=n}}else{if((n.nodeIndex+l)%f==0){r[++ri]=n}}}return r},"only-child":function(c){var r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){if(!prev(ci)&&!next(ci)){r[++ri]=ci}}return r},empty:function(c){var r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){var cns=ci.childNodes,j=0,cn,empty=true;while(cn=cns[j]){++j;if(cn.nodeType==1||cn.nodeType==3){empty=false;break}}if(empty){r[++ri]=ci}}return r},contains:function(c,v){var r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){if((ci.textContent||ci.innerText||"").indexOf(v)!=-1){r[++ri]=ci}}return r},nodeValue:function(c,v){var r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){if(ci.firstChild&&ci.firstChild.nodeValue==v){r[++ri]=ci}}return r},checked:function(c){var r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){if(ci.checked==true){r[++ri]=ci}}return r},not:function(c,ss){return Ext.DomQuery.filter(c,ss,true)},any:function(c,selectors){var ss=selectors.split("|"),r=[],ri=-1,s;for(var i=0,ci;ci=c[i];i++){for(var j=0;s=ss[j];j++){if(Ext.DomQuery.is(ci,s)){r[++ri]=ci;break}}}return r},odd:function(c){return this["nth-child"](c,"odd")},even:function(c){return this["nth-child"](c,"even")},nth:function(c,a){return c[a-1]||[]},first:function(c){return c[0]||[]},last:function(c){return c[c.length-1]||[]},has:function(c,ss){var s=Ext.DomQuery.select,r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){if(s(ss,ci).length>0){r[++ri]=ci}}return r},next:function(c,ss){var is=Ext.DomQuery.is,r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){var n=next(ci);if(n&&is(n,ss)){r[++ri]=ci}}return r},prev:function(c,ss){var is=Ext.DomQuery.is,r=[],ri=-1;for(var i=0,ci;ci=c[i];i++){var n=prev(ci);if(n&&is(n,ss)){r[++ri]=ci}}return r}}}}();Ext.query=Ext.DomQuery.select;Ext.util.DelayedTask=function(d,c,a){var e=this,g,b=function(){clearInterval(g);g=null;d.apply(c,a||[])};e.delay=function(i,l,k,h){e.cancel();d=l||d;c=k||c;a=h||a;g=setInterval(b,i)};e.cancel=function(){if(g){clearInterval(g);g=null}}};(function(){var h=document;Ext.Element=function(m,n){var o=typeof m=="string"?h.getElementById(m):m,p;if(!o){return null}p=o.id;if(!n&&p&&Ext.elCache[p]){return Ext.elCache[p].el}this.dom=o;this.id=p||Ext.id(o)};var d=Ext.DomHelper,e=Ext.Element,a=Ext.elCache;e.prototype={set:function(r,n){var p=this.dom,m,q,n=(n!==false)&&!!p.setAttribute;for(m in r){if(r.hasOwnProperty(m)){q=r[m];if(m=="style"){d.applyStyles(p,q)}else{if(m=="cls"){p.className=q}else{if(n){p.setAttribute(m,q)}else{p[m]=q}}}}}return this},defaultUnit:"px",is:function(m){return Ext.DomQuery.is(this.dom,m)},focus:function(p,o){var m=this,o=o||m.dom;try{if(Number(p)){m.focus.defer(p,null,[null,o])}else{o.focus()}}catch(n){}return m},blur:function(){try{this.dom.blur()}catch(m){}return this},getValue:function(m){var n=this.dom.value;return m?parseInt(n,10):n},addListener:function(m,p,o,n){Ext.EventManager.on(this.dom,m,p,o||this,n);return this},removeListener:function(m,o,n){Ext.EventManager.removeListener(this.dom,m,o,n||this);return this},removeAllListeners:function(){Ext.EventManager.removeAll(this.dom);return this},purgeAllListeners:function(){Ext.EventManager.purgeElement(this,true);return this},addUnits:function(m){if(m===""||m=="auto"||m===undefined){m=m||""}else{if(!isNaN(m)||!i.test(m)){m=m+(this.defaultUnit||"px")}}return m},load:function(n,o,m){Ext.Ajax.request(Ext.apply({params:o,url:n.url||n,callback:m,el:this.dom,indicatorText:n.indicatorText||""},Ext.isObject(n)?n:{}));return this},isBorderBox:function(){return Ext.isBorderBox||Ext.isForcedBorderBox||g[(this.dom.tagName||"").toLowerCase()]},remove:function(){var m=this,n=m.dom;if(n){delete m.dom;Ext.removeNode(n)}},hover:function(n,m,p,o){var q=this;q.on("mouseenter",n,p||q.dom,o);q.on("mouseleave",m,p||q.dom,o);return q},contains:function(m){return !m?false:Ext.lib.Dom.isAncestor(this.dom,m.dom?m.dom:m)},getAttributeNS:function(n,m){return this.getAttribute(m,n)},getAttribute:Ext.isIE?function(m,o){var p=this.dom,n=typeof p[o+":"+m];if(["undefined","unknown"].indexOf(n)==-1){return p[o+":"+m]}return p[m]}:function(m,n){var o=this.dom;return o.getAttributeNS(n,m)||o.getAttribute(n+":"+m)||o.getAttribute(m)||o[m]},update:function(m){if(this.dom){this.dom.innerHTML=m}return this}};var l=e.prototype;e.addMethods=function(m){Ext.apply(l,m)};l.on=l.addListener;l.un=l.removeListener;l.autoBoxAdjust=true;var i=/\d+(px|em|%|en|ex|pt|in|cm|mm|pc)$/i,c;e.get=function(n){var m,q,p;if(!n){return null}if(typeof n=="string"){if(!(q=h.getElementById(n))){return null}if(a[n]&&a[n].el){m=a[n].el;m.dom=q}else{m=e.addToCache(new e(q))}return m}else{if(n.tagName){if(!(p=n.id)){p=Ext.id(n)}if(a[p]&&a[p].el){m=a[p].el;m.dom=n}else{m=e.addToCache(new e(n))}return m}else{if(n instanceof e){if(n!=c){if(Ext.isIE&&(n.id==undefined||n.id=="")){n.dom=n.dom}else{n.dom=h.getElementById(n.id)||n.dom}}return n}else{if(n.isComposite){return n}else{if(Ext.isArray(n)){return e.select(n)}else{if(n==h){if(!c){var o=function(){};o.prototype=e.prototype;c=new o();c.dom=h}return c}}}}}}return null};e.addToCache=function(m,n){n=n||m.id;a[n]={el:m,data:{},events:{}};return m};e.data=function(n,m,o){n=e.get(n);if(!n){return null}var p=a[n.id].data;if(arguments.length==2){return p[m]}else{return(p[m]=o)}};function k(){if(!Ext.enableGarbageCollector){clearInterval(e.collectorThreadId)}else{var m,p,r,q;for(m in a){q=a[m];if(q.skipGC){continue}p=q.el;r=p.dom;if(!r||!r.parentNode||(!r.offsetParent&&!h.getElementById(m))){if(Ext.enableListenerCollection){Ext.EventManager.removeAll(r)}delete a[m]}}if(Ext.isIE){var n={};for(m in a){n[m]=a[m]}a=Ext.elCache=n}}}e.collectorThreadId=setInterval(k,30000);var b=function(){};b.prototype=e.prototype;e.Flyweight=function(m){this.dom=m};e.Flyweight.prototype=new b();e.Flyweight.prototype.isFlyweight=true;e._flyweights={};e.fly=function(o,m){var n=null;m=m||"_global";if(o=Ext.getDom(o)){(e._flyweights[m]=e._flyweights[m]||new e.Flyweight()).dom=o;n=e._flyweights[m]}return n};Ext.get=e.get;Ext.fly=e.fly;var g=Ext.isStrict?{select:1}:{input:1,select:1,textarea:1};if(Ext.isIE||Ext.isGecko){g.button=1}})();Ext.Element.addMethods(function(){var d="parentNode",b="nextSibling",c="previousSibling",e=Ext.DomQuery,a=Ext.get;return{findParent:function(n,m,h){var k=this.dom,g=document.body,l=0,i;if(Ext.isGecko&&Object.prototype.toString.call(k)=="[object XULElement]"){return null}m=m||50;if(isNaN(m)){i=Ext.getDom(m);m=Number.MAX_VALUE}while(k&&k.nodeType==1&&l<m&&k!=g&&k!=i){if(e.is(k,n)){return h?a(k):k}l++;k=k.parentNode}return null},findParentNode:function(k,i,g){var h=Ext.fly(this.dom.parentNode,"_internal");return h?h.findParent(k,i,g):null},up:function(h,g){return this.findParentNode(h,g,true)},select:function(g){return Ext.Element.select(g,this.dom)},query:function(g){return e.select(g,this.dom)},child:function(g,h){var i=e.selectNode(g,this.dom);return h?i:a(i)},down:function(g,h){var i=e.selectNode(" > "+g,this.dom);return h?i:a(i)},parent:function(g,h){return this.matchNode(d,d,g,h)},next:function(g,h){return this.matchNode(b,b,g,h)},prev:function(g,h){return this.matchNode(c,c,g,h)},first:function(g,h){return this.matchNode(b,"firstChild",g,h)},last:function(g,h){return this.matchNode(c,"lastChild",g,h)},matchNode:function(h,l,g,i){var k=this.dom[l];while(k){if(k.nodeType==1&&(!g||e.is(k,g))){return !i?a(k):k}k=k[h]}return null}}}());Ext.Element.addMethods(function(){var c=Ext.getDom,a=Ext.get,b=Ext.DomHelper;return{appendChild:function(d){return a(d).appendTo(this)},appendTo:function(d){c(d).appendChild(this.dom);return this},insertBefore:function(d){(d=c(d)).parentNode.insertBefore(this.dom,d);return this},insertAfter:function(d){(d=c(d)).parentNode.insertBefore(this.dom,d.nextSibling);return this},insertFirst:function(e,d){e=e||{};if(e.nodeType||e.dom||typeof e=="string"){e=c(e);this.dom.insertBefore(e,this.dom.firstChild);return !d?a(e):e}else{return this.createChild(e,this.dom.firstChild,d)}},replace:function(d){d=a(d);this.insertBefore(d);d.remove();return this},replaceWith:function(d){var e=this;if(d.nodeType||d.dom||typeof d=="string"){d=c(d);e.dom.parentNode.insertBefore(d,e.dom)}else{d=b.insertBefore(e.dom,d)}delete Ext.elCache[e.id];Ext.removeNode(e.dom);e.id=Ext.id(e.dom=d);Ext.Element.addToCache(e.isFlyweight?new Ext.Element(e.dom):e);return e},createChild:function(e,d,g){e=e||{tag:"div"};return d?b.insertBefore(d,e,g!==true):b[!this.dom.firstChild?"overwrite":"append"](this.dom,e,g!==true)},wrap:function(d,e){var g=b.insertBefore(this.dom,d||{tag:"div"},!e);g.dom?g.dom.appendChild(this.dom):g.appendChild(this.dom);return g},insertHtml:function(e,g,d){var h=b.insertHtml(e,this.dom,g);return d?Ext.get(h):h}}}());Ext.Element.addMethods(function(){var B=Ext.supports,h={},y=/(-[a-z])/gi,t=document.defaultView,E=/alpha\(opacity=(.*)\)/i,m=/^\s+|\s+$/g,C=Ext.Element,v=/\s+/,b=/\w/g,d="padding",c="margin",z="border",u="-left",r="-right",x="-top",p="-bottom",k="-width",s=Math,A="hidden",e="isClipped",l="overflow",o="overflow-x",n="overflow-y",D="originalClip",i={l:z+u+k,r:z+r+k,t:z+x+k,b:z+p+k},g={l:d+u,r:d+r,t:d+x,b:d+p},a={l:c+u,r:c+r,t:c+x,b:c+p},F=Ext.Element.data;function q(G,H){return H.charAt(1).toUpperCase()}function w(G){return h[G]||(h[G]=G=="float"?(B.cssFloat?"cssFloat":"styleFloat"):G.replace(y,q))}return{adjustWidth:function(G){var H=this;var I=(typeof G=="number");if(I&&H.autoBoxAdjust&&!H.isBorderBox()){G-=(H.getBorderWidth("lr")+H.getPadding("lr"))}return(I&&G<0)?0:G},adjustHeight:function(G){var H=this;var I=(typeof G=="number");if(I&&H.autoBoxAdjust&&!H.isBorderBox()){G-=(H.getBorderWidth("tb")+H.getPadding("tb"))}return(I&&G<0)?0:G},addClass:function(K){var L=this,J,G,I,H=[];if(!Ext.isArray(K)){if(typeof K=="string"&&!this.hasClass(K)){L.dom.className+=" "+K}}else{for(J=0,G=K.length;J<G;J++){I=K[J];if(typeof I=="string"&&(" "+L.dom.className+" ").indexOf(" "+I+" ")==-1){H.push(I)}}if(H.length){L.dom.className+=" "+H.join(" ")}}return L},removeClass:function(L){var M=this,K,H,G,J,I;if(!Ext.isArray(L)){L=[L]}if(M.dom&&M.dom.className){I=M.dom.className.replace(m,"").split(v);for(K=0,G=L.length;K<G;K++){J=L[K];if(typeof J=="string"){J=J.replace(m,"");H=I.indexOf(J);if(H!=-1){I.splice(H,1)}}}M.dom.className=I.join(" ")}return M},radioClass:function(J){var K=this.dom.parentNode.childNodes,H,I,G;J=Ext.isArray(J)?J:[J];for(I=0,G=K.length;I<G;I++){H=K[I];if(H&&H.nodeType==1){Ext.fly(H,"_internal").removeClass(J)}}return this.addClass(J)},toggleClass:function(G){return this.hasClass(G)?this.removeClass(G):this.addClass(G)},hasClass:function(G){return G&&(" "+this.dom.className+" ").indexOf(" "+G+" ")!=-1},replaceClass:function(H,G){return this.removeClass(H).addClass(G)},isStyle:function(G,H){return this.getStyle(G)==H},getStyle:function(){return t&&t.getComputedStyle?function(L){var J=this.dom,G,I,H,K;if(J==document){return null}L=w(L);H=(G=J.style[L])?G:(I=t.getComputedStyle(J,""))?I[L]:null;if(L=="marginRight"&&H!="0px"&&!B.correctRightMargin){K=J.style.display;J.style.display="inline-block";H=t.getComputedStyle(J,"").marginRight;J.style.display=K}if(L=="backgroundColor"&&H=="rgba(0, 0, 0, 0)"&&!B.correctTransparentColor){H="transparent"}return H}:function(K){var I=this.dom,G,H;if(I==document){return null}if(K=="opacity"){if(I.style.filter.match){if(G=I.style.filter.match(E)){var J=parseFloat(G[1]);if(!isNaN(J)){return J?J/100:0}}}return 1}K=w(K);return I.style[K]||((H=I.currentStyle)?H[K]:null)}}(),getColor:function(G,H,L){var J=this.getStyle(G),I=(typeof L!="undefined")?L:"#",K;if(!J||(/transparent|inherit/.test(J))){return H}if(/^r/.test(J)){Ext.each(J.slice(4,J.length-1).split(","),function(M){K=parseInt(M,10);I+=(K<16?"0":"")+K.toString(16)})}else{J=J.replace("#","");I+=J.length==3?J.replace(/^(\w)(\w)(\w)$/,"$1$1$2$2$3$3"):J}return(I.length>5?I.toLowerCase():H)},setStyle:function(J,I){var G,H;if(typeof J!="object"){G={};G[J]=I;J=G}for(H in J){I=J[H];H=="opacity"?this.setOpacity(I):this.dom.style[w(H)]=I}return this},setOpacity:function(H,G){var K=this,I=K.dom.style;if(!G||!K.anim){if(Ext.isIE){var J=H<1?"alpha(opacity="+H*100+")":"",L=I.filter.replace(E,"").replace(m,"");I.zoom=1;I.filter=L+(L.length>0?" ":"")+J}else{I.opacity=H}}else{K.anim({opacity:{to:H}},K.preanim(arguments,1),null,0.35,"easeIn")}return K},clearOpacity:function(){var G=this.dom.style;if(Ext.isIE){if(!Ext.isEmpty(G.filter)){G.filter=G.filter.replace(E,"").replace(m,"")}}else{G.opacity=G["-moz-opacity"]=G["-khtml-opacity"]=""}return this},getHeight:function(I){var H=this,K=H.dom,J=Ext.isIE&&H.isStyle("display","none"),G=s.max(K.offsetHeight,J?0:K.clientHeight)||0;G=!I?G:G-H.getBorderWidth("tb")-H.getPadding("tb");return G<0?0:G},getWidth:function(H){var I=this,K=I.dom,J=Ext.isIE&&I.isStyle("display","none"),G=s.max(K.offsetWidth,J?0:K.clientWidth)||0;G=!H?G:G-I.getBorderWidth("lr")-I.getPadding("lr");return G<0?0:G},setWidth:function(H,G){var I=this;H=I.adjustWidth(H);!G||!I.anim?I.dom.style.width=I.addUnits(H):I.anim({width:{to:H}},I.preanim(arguments,1));return I},setHeight:function(G,H){var I=this;G=I.adjustHeight(G);!H||!I.anim?I.dom.style.height=I.addUnits(G):I.anim({height:{to:G}},I.preanim(arguments,1));return I},getBorderWidth:function(G){return this.addStyles(G,i)},getPadding:function(G){return this.addStyles(G,g)},clip:function(){var G=this,H=G.dom;if(!F(H,e)){F(H,e,true);F(H,D,{o:G.getStyle(l),x:G.getStyle(o),y:G.getStyle(n)});G.setStyle(l,A);G.setStyle(o,A);G.setStyle(n,A)}return G},unclip:function(){var G=this,I=G.dom;if(F(I,e)){F(I,e,false);var H=F(I,D);if(H.o){G.setStyle(l,H.o)}if(H.x){G.setStyle(o,H.x)}if(H.y){G.setStyle(n,H.y)}}return G},addStyles:function(N,M){var K=0,L=N.match(b),J,I,H,G=L.length;for(H=0;H<G;H++){J=L[H];I=J&&parseInt(this.getStyle(M[J]),10);if(I){K+=s.abs(I)}}return K},margins:a}}());(function(){var a=Ext.lib.Dom,b="left",g="right",d="top",i="bottom",h="position",c="static",e="relative",k="auto",l="z-index";Ext.Element.addMethods({getX:function(){return a.getX(this.dom)},getY:function(){return a.getY(this.dom)},getXY:function(){return a.getXY(this.dom)},getOffsetsTo:function(m){var p=this.getXY(),n=Ext.fly(m,"_internal").getXY();return[p[0]-n[0],p[1]-n[1]]},setX:function(m,n){return this.setXY([m,this.getY()],this.animTest(arguments,n,1))},setY:function(n,m){return this.setXY([this.getX(),n],this.animTest(arguments,m,1))},setLeft:function(m){this.setStyle(b,this.addUnits(m));return this},setTop:function(m){this.setStyle(d,this.addUnits(m));return this},setRight:function(m){this.setStyle(g,this.addUnits(m));return this},setBottom:function(m){this.setStyle(i,this.addUnits(m));return this},setXY:function(o,m){var n=this;if(!m||!n.anim){a.setXY(n.dom,o)}else{n.anim({points:{to:o}},n.preanim(arguments,1),"motion")}return n},setLocation:function(m,o,n){return this.setXY([m,o],this.animTest(arguments,n,2))},moveTo:function(m,o,n){return this.setXY([m,o],this.animTest(arguments,n,2))},getLeft:function(m){return !m?this.getX():parseInt(this.getStyle(b),10)||0},getRight:function(m){var n=this;return !m?n.getX()+n.getWidth():(n.getLeft(true)+n.getWidth())||0},getTop:function(m){return !m?this.getY():parseInt(this.getStyle(d),10)||0},getBottom:function(m){var n=this;return !m?n.getY()+n.getHeight():(n.getTop(true)+n.getHeight())||0},position:function(q,p,m,o){var n=this;if(!q&&n.isStyle(h,c)){n.setStyle(h,e)}else{if(q){n.setStyle(h,q)}}if(p){n.setStyle(l,p)}if(m||o){n.setXY([m||false,o||false])}},clearPositioning:function(m){m=m||"";this.setStyle({left:m,right:m,top:m,bottom:m,"z-index":"",position:c});return this},getPositioning:function(){var m=this.getStyle(b);var n=this.getStyle(d);return{position:this.getStyle(h),left:m,right:m?"":this.getStyle(g),top:n,bottom:n?"":this.getStyle(i),"z-index":this.getStyle(l)}},setPositioning:function(m){var o=this,n=o.dom.style;o.setStyle(m);if(m.right==k){n.right=""}if(m.bottom==k){n.bottom=""}return o},translatePoints:function(m,u){u=isNaN(m[1])?u:m[1];m=isNaN(m[0])?m:m[0];var q=this,r=q.isStyle(h,e),s=q.getXY(),n=parseInt(q.getStyle(b),10),p=parseInt(q.getStyle(d),10);n=!isNaN(n)?n:(r?0:q.dom.offsetLeft);p=!isNaN(p)?p:(r?0:q.dom.offsetTop);return{left:(m-s[0]+n),top:(u-s[1]+p)}},animTest:function(n,m,o){return !!m&&this.preanim?this.preanim(n,o):false}})})();Ext.Element.addMethods({isScrollable:function(){var a=this.dom;return a.scrollHeight>a.clientHeight||a.scrollWidth>a.clientWidth},scrollTo:function(a,b){this.dom["scroll"+(/top/i.test(a)?"Top":"Left")]=b;return this},getScroll:function(){var i=this.dom,h=document,a=h.body,c=h.documentElement,b,g,e;if(i==h||i==a){if(Ext.isIE&&Ext.isStrict){b=c.scrollLeft;g=c.scrollTop}else{b=window.pageXOffset;g=window.pageYOffset}e={left:b||(a?a.scrollLeft:0),top:g||(a?a.scrollTop:0)}}else{e={left:i.scrollLeft,top:i.scrollTop}}return e}});Ext.Element.VISIBILITY=1;Ext.Element.DISPLAY=2;Ext.Element.OFFSETS=3;Ext.Element.ASCLASS=4;Ext.Element.visibilityCls="x-hide-nosize";Ext.Element.addMethods(function(){var e=Ext.Element,q="opacity",k="visibility",g="display",d="hidden",o="offsets",l="asclass",n="none",a="nosize",b="originalDisplay",c="visibilityMode",h="isVisible",i=e.data,m=function(s){var r=i(s,b);if(r===undefined){i(s,b,r="")}return r},p=function(s){var r=i(s,c);if(r===undefined){i(s,c,r=1)}return r};return{originalDisplay:"",visibilityMode:1,setVisibilityMode:function(r){i(this.dom,c,r);return this},animate:function(s,u,t,v,r){this.anim(s,{duration:u,callback:t,easing:v},r);return this},anim:function(u,v,s,x,t,r){s=s||"run";v=v||{};var w=this,y=Ext.lib.Anim[s](w.dom,u,(v.duration||x)||0.35,(v.easing||t)||"easeOut",function(){if(r){r.call(w)}if(v.callback){v.callback.call(v.scope||w,w,v)}},w);v.anim=y;return y},preanim:function(r,s){return !r[s]?false:(typeof r[s]=="object"?r[s]:{duration:r[s+1],callback:r[s+2],easing:r[s+3]})},isVisible:function(){var r=this,t=r.dom,s=i(t,h);if(typeof s=="boolean"){return s}s=!r.isStyle(k,d)&&!r.isStyle(g,n)&&!((p(t)==e.ASCLASS)&&r.hasClass(r.visibilityCls||e.visibilityCls));i(t,h,s);return s},setVisible:function(u,r){var x=this,s,z,y,w,v=x.dom,t=p(v);if(typeof r=="string"){switch(r){case g:t=e.DISPLAY;break;case k:t=e.VISIBILITY;break;case o:t=e.OFFSETS;break;case a:case l:t=e.ASCLASS;break}x.setVisibilityMode(t);r=false}if(!r||!x.anim){if(t==e.ASCLASS){x[u?"removeClass":"addClass"](x.visibilityCls||e.visibilityCls)}else{if(t==e.DISPLAY){return x.setDisplayed(u)}else{if(t==e.OFFSETS){if(!u){x.hideModeStyles={position:x.getStyle("position"),top:x.getStyle("top"),left:x.getStyle("left")};x.applyStyles({position:"absolute",top:"-10000px",left:"-10000px"})}else{x.applyStyles(x.hideModeStyles||{position:"",top:"",left:""});delete x.hideModeStyles}}else{x.fixDisplay();v.style.visibility=u?"visible":d}}}}else{if(u){x.setOpacity(0.01);x.setVisible(true)}x.anim({opacity:{to:(u?1:0)}},x.preanim(arguments,1),null,0.35,"easeIn",function(){u||x.setVisible(false).setOpacity(1)})}i(v,h,u);return x},hasMetrics:function(){var r=this.dom;return this.isVisible()||(p(r)==e.VISIBILITY)},toggle:function(r){var s=this;s.setVisible(!s.isVisible(),s.preanim(arguments,0));return s},setDisplayed:function(r){if(typeof r=="boolean"){r=r?m(this.dom):n}this.setStyle(g,r);return this},fixDisplay:function(){var r=this;if(r.isStyle(g,n)){r.setStyle(k,d);r.setStyle(g,m(this.dom));if(r.isStyle(g,n)){r.setStyle(g,"block")}}},hide:function(r){if(typeof r=="string"){this.setVisible(false,r);return this}this.setVisible(false,this.preanim(arguments,0));return this},show:function(r){if(typeof r=="string"){this.setVisible(true,r);return this}this.setVisible(true,this.preanim(arguments,0));return this}}}());(function(){var z=null,B=undefined,l=true,u=false,k="setX",h="setY",a="setXY",o="left",m="bottom",t="top",n="right",r="height",g="width",i="points",x="hidden",A="absolute",v="visible",e="motion",p="position",s="easeOut",d=new Ext.Element.Flyweight(),w={},y=function(C){return C||{}},q=function(C){d.dom=C;d.id=Ext.id(C);return d},c=function(C){if(!w[C]){w[C]=[]}return w[C]},b=function(D,C){w[D]=C};Ext.enableFx=l;Ext.Fx={switchStatements:function(D,E,C){return E.apply(this,C[D])},slideIn:function(I,F){F=y(F);var K=this,H=K.dom,N=H.style,P,C,M,E,D,N,J,O,L,G;I=I||"t";K.queueFx(F,function(){P=q(H).getXY();q(H).fixDisplay();C=q(H).getFxRestore();M={x:P[0],y:P[1],0:P[0],1:P[1],width:H.offsetWidth,height:H.offsetHeight};M.right=M.x+M.width;M.bottom=M.y+M.height;q(H).setWidth(M.width).setHeight(M.height);E=q(H).fxWrap(C.pos,F,x);N.visibility=v;N.position=A;function Q(){q(H).fxUnwrap(E,C.pos,F);N.width=C.width;N.height=C.height;q(H).afterFx(F)}O={to:[M.x,M.y]};L={to:M.width};G={to:M.height};function R(V,S,W,T,Y,aa,ad,ac,ab,X,U){var Z={};q(V).setWidth(W).setHeight(T);if(q(V)[Y]){q(V)[Y](aa)}S[ad]=S[ac]="0";if(ab){Z.width=ab}if(X){Z.height=X}if(U){Z.points=U}return Z}J=q(H).switchStatements(I.toLowerCase(),R,{t:[E,N,M.width,0,z,z,o,m,z,G,z],l:[E,N,0,M.height,z,z,n,t,L,z,z],r:[E,N,M.width,M.height,k,M.right,o,t,z,z,O],b:[E,N,M.width,M.height,h,M.bottom,o,t,z,G,O],tl:[E,N,0,0,z,z,n,m,L,G,O],bl:[E,N,0,0,h,M.y+M.height,n,t,L,G,O],br:[E,N,0,0,a,[M.right,M.bottom],o,t,L,G,O],tr:[E,N,0,0,k,M.x+M.width,o,m,L,G,O]});N.visibility=v;q(E).show();arguments.callee.anim=q(E).fxanim(J,F,e,0.5,s,Q)});return K},slideOut:function(G,E){E=y(E);var I=this,F=I.dom,L=F.style,M=I.getXY(),D,C,J,K,H={to:0};G=G||"t";I.queueFx(E,function(){C=q(F).getFxRestore();J={x:M[0],y:M[1],0:M[0],1:M[1],width:F.offsetWidth,height:F.offsetHeight};J.right=J.x+J.width;J.bottom=J.y+J.height;q(F).setWidth(J.width).setHeight(J.height);D=q(F).fxWrap(C.pos,E,v);L.visibility=v;L.position=A;q(D).setWidth(J.width).setHeight(J.height);function N(){E.useDisplay?q(F).setDisplayed(u):q(F).hide();q(F).fxUnwrap(D,C.pos,E);L.width=C.width;L.height=C.height;q(F).afterFx(E)}function O(P,X,V,Y,T,W,S,U,R){var Q={};P[X]=P[V]="0";Q[Y]=T;if(W){Q[W]=S}if(U){Q[U]=R}return Q}K=q(F).switchStatements(G.toLowerCase(),O,{t:[L,o,m,r,H],l:[L,n,t,g,H],r:[L,o,t,g,H,i,{to:[J.right,J.y]}],b:[L,o,t,r,H,i,{to:[J.x,J.bottom]}],tl:[L,n,m,g,H,r,H],bl:[L,n,t,g,H,r,H,i,{to:[J.x,J.bottom]}],br:[L,o,t,g,H,r,H,i,{to:[J.x+J.width,J.bottom]}],tr:[L,o,m,g,H,r,H,i,{to:[J.right,J.y]}]});arguments.callee.anim=q(D).fxanim(K,E,e,0.5,s,N)});return I},puff:function(I){I=y(I);var G=this,H=G.dom,D=H.style,E,C,F;G.queueFx(I,function(){E=q(H).getWidth();C=q(H).getHeight();q(H).clearOpacity();q(H).show();F=q(H).getFxRestore();function J(){I.useDisplay?q(H).setDisplayed(u):q(H).hide();q(H).clearOpacity();q(H).setPositioning(F.pos);D.width=F.width;D.height=F.height;D.fontSize="";q(H).afterFx(I)}arguments.callee.anim=q(H).fxanim({width:{to:q(H).adjustWidth(E*2)},height:{to:q(H).adjustHeight(C*2)},points:{by:[-E*0.5,-C*0.5]},opacity:{to:0},fontSize:{to:200,unit:"%"}},I,e,0.5,s,J)});return G},switchOff:function(G){G=y(G);var E=this,F=E.dom,C=F.style,D;E.queueFx(G,function(){q(F).clearOpacity();q(F).clip();D=q(F).getFxRestore();function H(){G.useDisplay?q(F).setDisplayed(u):q(F).hide();q(F).clearOpacity();q(F).setPositioning(D.pos);C.width=D.width;C.height=D.height;q(F).afterFx(G)}q(F).fxanim({opacity:{to:0.3}},z,z,0.1,z,function(){q(F).clearOpacity();(function(){q(F).fxanim({height:{to:1},points:{by:[0,q(F).getHeight()*0.5]}},G,e,0.3,"easeIn",H)}).defer(100)})});return E},highlight:function(E,I){I=y(I);var G=this,H=G.dom,C=I.attr||"backgroundColor",D={},F;G.queueFx(I,function(){q(H).clearOpacity();q(H).show();function J(){H.style[C]=F;q(H).afterFx(I)}F=H.style[C];D[C]={from:E||"ffff9c",to:I.endColor||q(H).getColor(C)||"ffffff"};arguments.callee.anim=q(H).fxanim(D,I,"color",1,"easeIn",J)});return G},frame:function(C,F,I){I=y(I);var E=this,H=E.dom,D,G;E.queueFx(I,function(){C=C||"#C3DAF9";if(C.length==6){C="#"+C}F=F||1;q(H).show();var M=q(H).getXY(),K={x:M[0],y:M[1],0:M[0],1:M[1],width:H.offsetWidth,height:H.offsetHeight},J=function(){D=q(document.body||document.documentElement).createChild({style:{position:A,"z-index":35000,border:"0px solid "+C}});return D.queueFx({},L)};arguments.callee.anim={isAnimated:true,stop:function(){F=0;D.stopFx()}};function L(){var N=Ext.isBorderBox?2:1;G=D.anim({top:{from:K.y,to:K.y-20},left:{from:K.x,to:K.x-20},borderWidth:{from:0,to:10},opacity:{from:1,to:0},height:{from:K.height,to:K.height+20*N},width:{from:K.width,to:K.width+20*N}},{duration:I.duration||1,callback:function(){D.remove();--F>0?J():q(H).afterFx(I)}});arguments.callee.anim={isAnimated:true,stop:function(){G.stop()}}}J()});return E},pause:function(E){var D=this.dom,C;this.queueFx({},function(){C=setTimeout(function(){q(D).afterFx({})},E*1000);arguments.callee.anim={isAnimated:true,stop:function(){clearTimeout(C);q(D).afterFx({})}}});return this},fadeIn:function(E){E=y(E);var C=this,D=C.dom,F=E.endOpacity||1;C.queueFx(E,function(){q(D).setOpacity(0);q(D).fixDisplay();D.style.visibility=v;arguments.callee.anim=q(D).fxanim({opacity:{to:F}},E,z,0.5,s,function(){if(F==1){q(D).clearOpacity()}q(D).afterFx(E)})});return C},fadeOut:function(F){F=y(F);var D=this,E=D.dom,C=E.style,G=F.endOpacity||0;D.queueFx(F,function(){arguments.callee.anim=q(E).fxanim({opacity:{to:G}},F,z,0.5,s,function(){if(G==0){Ext.Element.data(E,"visibilityMode")==Ext.Element.DISPLAY||F.useDisplay?C.display="none":C.visibility=x;q(E).clearOpacity()}q(E).afterFx(F)})});return D},scale:function(C,D,E){this.shift(Ext.apply({},E,{width:C,height:D}));return this},shift:function(E){E=y(E);var D=this.dom,C={};this.queueFx(E,function(){for(var F in E){if(E[F]!=B){C[F]={to:E[F]}}}C.width?C.width.to=q(D).adjustWidth(E.width):C;C.height?C.height.to=q(D).adjustWidth(E.height):C;if(C.x||C.y||C.xy){C.points=C.xy||{to:[C.x?C.x.to:q(D).getX(),C.y?C.y.to:q(D).getY()]}}arguments.callee.anim=q(D).fxanim(C,E,e,0.35,s,function(){q(D).afterFx(E)})});return this},ghost:function(F,D){D=y(D);var H=this,E=H.dom,K=E.style,I={opacity:{to:0},points:{}},L=I.points,C,J,G;F=F||"b";H.queueFx(D,function(){C=q(E).getFxRestore();J=q(E).getWidth();G=q(E).getHeight();function M(){D.useDisplay?q(E).setDisplayed(u):q(E).hide();q(E).clearOpacity();q(E).setPositioning(C.pos);K.width=C.width;K.height=C.height;q(E).afterFx(D)}L.by=q(E).switchStatements(F.toLowerCase(),function(O,N){return[O,N]},{t:[0,-G],l:[-J,0],r:[J,0],b:[0,G],tl:[-J,-G],bl:[-J,G],br:[J,G],tr:[J,-G]});arguments.callee.anim=q(E).fxanim(I,D,e,0.5,s,M)});return H},syncFx:function(){var C=this;C.fxDefaults=Ext.apply(C.fxDefaults||{},{block:u,concurrent:l,stopFx:u});return C},sequenceFx:function(){var C=this;C.fxDefaults=Ext.apply(C.fxDefaults||{},{block:u,concurrent:u,stopFx:u});return C},nextFx:function(){var C=c(this.dom.id)[0];if(C){C.call(this)}},hasActiveFx:function(){return c(this.dom.id)[0]},stopFx:function(C){var D=this,F=D.dom.id;if(D.hasActiveFx()){var E=c(F)[0];if(E&&E.anim){if(E.anim.isAnimated){b(F,[E]);E.anim.stop(C!==undefined?C:l)}else{b(F,[])}}}return D},beforeFx:function(C){if(this.hasActiveFx()&&!C.concurrent){if(C.stopFx){this.stopFx();return l}return u}return l},hasFxBlock:function(){var C=c(this.dom.id);return C&&C[0]&&C[0].block},queueFx:function(F,C){var D=q(this.dom);if(!D.hasFxBlock()){Ext.applyIf(F,D.fxDefaults);if(!F.concurrent){var E=D.beforeFx(F);C.block=F.block;c(D.dom.id).push(C);if(E){D.nextFx()}}else{C.call(D)}}return D},fxWrap:function(I,G,E){var F=this.dom,D,C;if(!G.wrap||!(D=Ext.getDom(G.wrap))){if(G.fixPosition){C=q(F).getXY()}var H=document.createElement("div");H.style.visibility=E;D=F.parentNode.insertBefore(H,F);q(D).setPositioning(I);if(q(D).isStyle(p,"static")){q(D).position("relative")}q(F).clearPositioning("auto");q(D).clip();D.appendChild(F);if(C){q(D).setXY(C)}}return D},fxUnwrap:function(D,G,F){var E=this.dom;q(E).clearPositioning();q(E).setPositioning(G);if(!F.wrap){var C=q(D).dom.parentNode;C.insertBefore(E,D);q(D).remove()}},getFxRestore:function(){var C=this.dom.style;return{pos:this.getPositioning(),width:C.width,height:C.height}},afterFx:function(D){var C=this.dom,E=C.id;if(D.afterStyle){q(C).setStyle(D.afterStyle)}if(D.afterCls){q(C).addClass(D.afterCls)}if(D.remove==l){q(C).remove()}if(D.callback){D.callback.call(D.scope,q(C))}if(!D.concurrent){c(E).shift();q(C).nextFx()}},fxanim:function(F,G,D,H,E,C){D=D||"run";G=G||{};var I=Ext.lib.Anim[D](this.dom,F,(G.duration||H)||0.35,(G.easing||E)||s,C,this);G.anim=I;return I}};Ext.Fx.resize=Ext.Fx.scale;Ext.Element.addMethods(Ext.Fx)})();Ext.CompositeElementLite=function(b,a){this.elements=[];this.add(b,a);this.el=new Ext.Element.Flyweight()};Ext.CompositeElementLite.prototype={isComposite:true,getElement:function(a){var b=this.el;b.dom=a;b.id=a.id;return b},transformElement:function(a){return Ext.getDom(a)},getCount:function(){return this.elements.length},add:function(d,b){var e=this,g=e.elements;if(!d){return this}if(typeof d=="string"){d=Ext.Element.selectorFunction(d,b)}else{if(d.isComposite){d=d.elements}else{if(!Ext.isIterable(d)){d=[d]}}}for(var c=0,a=d.length;c<a;++c){g.push(e.transformElement(d[c]))}return e},invoke:function(g,b){var h=this,d=h.elements,a=d.length,k,c;for(c=0;c<a;c++){k=d[c];if(k){Ext.Element.prototype[g].apply(h.getElement(k),b)}}return h},item:function(b){var d=this,c=d.elements[b],a=null;if(c){a=d.getElement(c)}return a},addListener:function(b,k,h,g){var d=this.elements,a=d.length,c,l;for(c=0;c<a;c++){l=d[c];if(l){Ext.EventManager.on(l,b,k,h||l,g)}}return this},each:function(g,d){var h=this,c=h.elements,a=c.length,b,k;for(b=0;b<a;b++){k=c[b];if(k){k=this.getElement(k);if(g.call(d||k,k,h,b)===false){break}}}return h},fill:function(a){var b=this;b.elements=[];b.add(a);return b},filter:function(a){var b=[],d=this,c=Ext.isFunction(a)?a:function(e){return e.is(a)};d.each(function(h,e,g){if(c(h,g)!==false){b[b.length]=d.transformElement(h)}});d.elements=b;return d},indexOf:function(a){return this.elements.indexOf(this.transformElement(a))},replaceElement:function(e,c,a){var b=!isNaN(e)?e:this.indexOf(e),g;if(b>-1){c=Ext.getDom(c);if(a){g=this.elements[b];g.parentNode.insertBefore(c,g);Ext.removeNode(g)}this.elements.splice(b,1,c)}return this},clear:function(){this.elements=[]}};Ext.CompositeElementLite.prototype.on=Ext.CompositeElementLite.prototype.addListener;Ext.CompositeElementLite.importElementMethods=function(){var c,b=Ext.Element.prototype,a=Ext.CompositeElementLite.prototype;for(c in b){if(typeof b[c]=="function"){(function(d){a[d]=a[d]||function(){return this.invoke(d,arguments)}}).call(a,c)}}};Ext.CompositeElementLite.importElementMethods();if(Ext.DomQuery){Ext.Element.selectorFunction=Ext.DomQuery.select}Ext.Element.select=function(a,b){var c;if(typeof a=="string"){c=Ext.Element.selectorFunction(a,b)}else{if(a.length!==undefined){c=a}else{throw"Invalid selector"}}return new Ext.CompositeElementLite(c)};Ext.select=Ext.Element.select;(function(){var b="beforerequest",e="requestcomplete",d="requestexception",h=undefined,c="load",i="POST",a="GET",g=window;Ext.data.Connection=function(k){Ext.apply(this,k);this.addEvents(b,e,d);Ext.data.Connection.superclass.constructor.call(this)};Ext.extend(Ext.data.Connection,Ext.util.Observable,{timeout:30000,autoAbort:false,disableCaching:true,disableCachingParam:"_dc",request:function(q){var t=this;if(t.fireEvent(b,t,q)){if(q.el){if(!Ext.isEmpty(q.indicatorText)){t.indicatorText='<div class="loading-indicator">'+q.indicatorText+"</div>"}if(t.indicatorText){Ext.getDom(q.el).innerHTML=t.indicatorText}q.success=(Ext.isFunction(q.success)?q.success:function(){}).createInterceptor(function(o){Ext.getDom(q.el).innerHTML=o.responseText})}var m=q.params,l=q.url||t.url,k,r={success:t.handleResponse,failure:t.handleFailure,scope:t,argument:{options:q},timeout:Ext.num(q.timeout,t.timeout)},n,u;if(Ext.isFunction(m)){m=m.call(q.scope||g,q)}m=Ext.urlEncode(t.extraParams,Ext.isObject(m)?Ext.urlEncode(m):m);if(Ext.isFunction(l)){l=l.call(q.scope||g,q)}if((n=Ext.getDom(q.form))){l=l||n.action;if(q.isUpload||(/multipart\/form-data/i.test(n.getAttribute("enctype")))){return t.doFormUpload.call(t,q,m,l)}u=Ext.lib.Ajax.serializeForm(n);m=m?(m+"&"+u):u}k=q.method||t.method||((m||q.xmlData||q.jsonData)?i:a);if(k===a&&(t.disableCaching&&q.disableCaching!==false)||q.disableCaching===true){var s=q.disableCachingParam||t.disableCachingParam;l=Ext.urlAppend(l,s+"="+(new Date().getTime()))}q.headers=Ext.apply(q.headers||{},t.defaultHeaders||{});if(q.autoAbort===true||t.autoAbort){t.abort()}if((k==a||q.xmlData||q.jsonData)&&m){l=Ext.urlAppend(l,m);m=""}return(t.transId=Ext.lib.Ajax.request(k,l,r,m,q))}else{return q.callback?q.callback.apply(q.scope,[q,h,h]):null}},isLoading:function(k){return k?Ext.lib.Ajax.isCallInProgress(k):!!this.transId},abort:function(k){if(k||this.isLoading()){Ext.lib.Ajax.abort(k||this.transId)}},handleResponse:function(k){this.transId=false;var l=k.argument.options;k.argument=l?l.argument:null;this.fireEvent(e,this,k,l);if(l.success){l.success.call(l.scope,k,l)}if(l.callback){l.callback.call(l.scope,l,true,k)}},handleFailure:function(k,m){this.transId=false;var l=k.argument.options;k.argument=l?l.argument:null;this.fireEvent(d,this,k,l,m);if(l.failure){l.failure.call(l.scope,k,l)}if(l.callback){l.callback.call(l.scope,l,false,k)}},doFormUpload:function(r,k,l){var m=Ext.id(),w=document,s=w.createElement("iframe"),n=Ext.getDom(r.form),v=[],u,q="multipart/form-data",p={target:n.target,method:n.method,encoding:n.encoding,enctype:n.enctype,action:n.action};Ext.fly(s).set({id:m,name:m,cls:"x-hidden",src:Ext.SSL_SECURE_URL});w.body.appendChild(s);if(Ext.isIE){document.frames[m].name=m}Ext.fly(n).set({target:m,method:i,enctype:q,encoding:q,action:l||p.action});Ext.iterate(Ext.urlDecode(k,false),function(x,o){u=w.createElement("input");Ext.fly(u).set({type:"hidden",value:o,name:x});n.appendChild(u);v.push(u)});function t(){var y=this,x={responseText:"",responseXML:null,argument:r.argument},B,A;try{B=s.contentWindow.document||s.contentDocument||g.frames[m].document;if(B){if(B.body){if(/textarea/i.test((A=B.body.firstChild||{}).tagName)){x.responseText=A.value}else{x.responseText=B.body.innerHTML}}x.responseXML=B.XMLDocument||B}}catch(z){}Ext.EventManager.removeListener(s,c,t,y);y.fireEvent(e,y,x,r);function o(E,D,C){if(Ext.isFunction(E)){E.apply(D,C)}}o(r.success,r.scope,[x,r]);o(r.callback,r.scope,[r,true,x]);if(!y.debugUploads){setTimeout(function(){Ext.removeNode(s)},100)}}Ext.EventManager.on(s,c,t,this);n.submit();Ext.fly(n).set(p);Ext.each(v,function(o){Ext.removeNode(o)})}})})();Ext.Ajax=new Ext.data.Connection({autoAbort:false,serializeForm:function(a){return Ext.lib.Ajax.serializeForm(a)}});Ext.util.JSON=new (function(){var useHasOwn=!!{}.hasOwnProperty,isNative=function(){var useNative=null;return function(){if(useNative===null){useNative=Ext.USE_NATIVE_JSON&&window.JSON&&JSON.toString()=="[object JSON]"}return useNative}}(),pad=function(n){return n<10?"0"+n:n},doDecode=function(json){return eval("("+json+")")},doEncode=function(o){if(!Ext.isDefined(o)||o===null){return"null"}else{if(Ext.isArray(o)){return encodeArray(o)}else{if(Ext.isDate(o)){return Ext.util.JSON.encodeDate(o)}else{if(Ext.isString(o)){return encodeString(o)}else{if(typeof o=="number"){return isFinite(o)?String(o):"null"}else{if(Ext.isBoolean(o)){return String(o)}else{var a=["{"],b,i,v;for(i in o){if(!o.getElementsByTagName){if(!useHasOwn||o.hasOwnProperty(i)){v=o[i];switch(typeof v){case"undefined":case"function":case"unknown":break;default:if(b){a.push(",")}a.push(doEncode(i),":",v===null?"null":doEncode(v));b=true}}}}a.push("}");return a.join("")}}}}}}},m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},encodeString=function(s){if(/["\\\x00-\x1f]/.test(s)){return'"'+s.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c}c=b.charCodeAt();return"\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"'}return'"'+s+'"'},encodeArray=function(o){var a=["["],b,i,l=o.length,v;for(i=0;i<l;i+=1){v=o[i];switch(typeof v){case"undefined":case"function":case"unknown":break;default:if(b){a.push(",")}a.push(v===null?"null":Ext.util.JSON.encode(v));b=true}}a.push("]");return a.join("")};this.encodeDate=function(o){return'"'+o.getFullYear()+"-"+pad(o.getMonth()+1)+"-"+pad(o.getDate())+"T"+pad(o.getHours())+":"+pad(o.getMinutes())+":"+pad(o.getSeconds())+'"'};this.encode=function(){var ec;return function(o){if(!ec){ec=isNative()?JSON.stringify:doEncode}return ec(o)}}();this.decode=function(){var dc;return function(json){if(!dc){dc=isNative()?JSON.parse:doDecode}return dc(json)}}()})();Ext.encode=Ext.util.JSON.encode;Ext.decode=Ext.util.JSON.decode;Ext.EventManager=function(){var A,q,k=false,m=Ext.isGecko||Ext.isWebKit||Ext.isSafari,p=Ext.lib.Event,r=Ext.lib.Dom,c=document,B=window,s="DOMContentLoaded",u="complete",g=/^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,v=[];function o(F){var I=false,E=0,D=v.length,G=false,H;if(F){if(F.getElementById||F.navigator){for(;E<D;++E){H=v[E];if(H.el===F){I=H.id;break}}if(!I){I=Ext.id(F);v.push({id:I,el:F});G=true}}else{I=Ext.id(F)}if(!Ext.elCache[I]){Ext.Element.addToCache(new Ext.Element(F),I);if(G){Ext.elCache[I].skipGC=true}}}return I}function n(F,H,K,G,E,M){F=Ext.getDom(F);var D=o(F),L=Ext.elCache[D].events,I;I=p.on(F,H,E);L[H]=L[H]||[];L[H].push([K,E,M,I,G]);if(F.addEventListener&&H=="mousewheel"){var J=["DOMMouseScroll",E,false];F.addEventListener.apply(F,J);Ext.EventManager.addListener(B,"unload",function(){F.removeEventListener.apply(F,J)})}if(F==c&&H=="mousedown"){Ext.EventManager.stoppedMouseDownEvent.addListener(E)}}function d(){if(window!=top){return false}try{c.documentElement.doScroll("left")}catch(D){return false}b();return true}function C(D){if(Ext.isIE&&d()){return true}if(c.readyState==u){b();return true}k||(q=setTimeout(arguments.callee,2));return false}var l;function i(D){l||(l=Ext.query("style, link[rel=stylesheet]"));if(l.length==c.styleSheets.length){b();return true}k||(q=setTimeout(arguments.callee,2));return false}function z(D){c.removeEventListener(s,arguments.callee,false);i()}function b(D){if(!k){k=true;if(q){clearTimeout(q)}if(m){c.removeEventListener(s,b,false)}if(Ext.isIE&&C.bindIE){c.detachEvent("onreadystatechange",C)}p.un(B,"load",arguments.callee)}if(A&&!Ext.isReady){Ext.isReady=true;A.fire();A.listeners=[]}}function a(){A||(A=new Ext.util.Event());if(m){c.addEventListener(s,b,false)}if(Ext.isIE){if(!C()){C.bindIE=true;c.attachEvent("onreadystatechange",C)}}else{if(Ext.isOpera){(c.readyState==u&&i())||c.addEventListener(s,z,false)}else{if(Ext.isWebKit){C()}}}p.on(B,"load",b)}function y(D,E){return function(){var F=Ext.toArray(arguments);if(E.target==Ext.EventObject.setEvent(F[0]).target){D.apply(this,F)}}}function x(E,F,D){return function(G){D.delay(F.buffer,E,null,[new Ext.EventObjectImpl(G)])}}function t(H,G,D,F,E){return function(I){Ext.EventManager.removeListener(G,D,F,E);H(I)}}function e(E,F,D){return function(H){var G=new Ext.util.DelayedTask(E);if(!D.tasks){D.tasks=[]}D.tasks.push(G);G.delay(F.delay||10,E,null,[new Ext.EventObjectImpl(H)])}}function h(I,H,D,K,L){var E=(!D||typeof D=="boolean")?{}:D,F=Ext.getDom(I),G;K=K||E.fn;L=L||E.scope;if(!F){throw'Error listening for "'+H+'". Element "'+I+"\" doesn't exist."}function J(N){if(!Ext){return}N=Ext.EventObject.setEvent(N);var M;if(E.delegate){if(!(M=N.getTarget(E.delegate,F))){return}}else{M=N.target}if(E.stopEvent){N.stopEvent()}if(E.preventDefault){N.preventDefault()}if(E.stopPropagation){N.stopPropagation()}if(E.normalized===false){N=N.browserEvent}K.call(L||F,N,M,E)}if(E.target){J=y(J,E)}if(E.delay){J=e(J,E,K)}if(E.single){J=t(J,F,H,K,L)}if(E.buffer){G=new Ext.util.DelayedTask(J);J=x(J,E,G)}n(F,H,K,G,J,L);return J}var w={addListener:function(F,D,H,G,E){if(typeof D=="object"){var K=D,I,J;for(I in K){J=K[I];if(!g.test(I)){if(Ext.isFunction(J)){h(F,I,K,J,K.scope)}else{h(F,I,J)}}}}else{h(F,D,E,H,G)}},removeListener:function(F,J,N,O){F=Ext.getDom(F);var D=o(F),L=F&&(Ext.elCache[D].events)[J]||[],E,I,G,H,K,M;for(I=0,K=L.length;I<K;I++){if(Ext.isArray(M=L[I])&&M[0]==N&&(!O||M[2]==O)){if(M[4]){M[4].cancel()}H=N.tasks&&N.tasks.length;if(H){while(H--){N.tasks[H].cancel()}delete N.tasks}E=M[1];p.un(F,J,p.extAdapter?M[3]:E);if(E&&F.addEventListener&&J=="mousewheel"){F.removeEventListener("DOMMouseScroll",E,false)}if(E&&F==c&&J=="mousedown"){Ext.EventManager.stoppedMouseDownEvent.removeListener(E)}L.splice(I,1);if(L.length===0){delete Ext.elCache[D].events[J]}for(H in Ext.elCache[D].events){return false}Ext.elCache[D].events={};return false}}},removeAll:function(F){F=Ext.getDom(F);var E=o(F),K=Ext.elCache[E]||{},N=K.events||{},J,I,L,G,M,H,D;for(G in N){if(N.hasOwnProperty(G)){J=N[G];for(I=0,L=J.length;I<L;I++){M=J[I];if(M[4]){M[4].cancel()}if(M[0].tasks&&(H=M[0].tasks.length)){while(H--){M[0].tasks[H].cancel()}delete M.tasks}D=M[1];p.un(F,G,p.extAdapter?M[3]:D);if(F.addEventListener&&D&&G=="mousewheel"){F.removeEventListener("DOMMouseScroll",D,false)}if(D&&F==c&&G=="mousedown"){Ext.EventManager.stoppedMouseDownEvent.removeListener(D)}}}}if(Ext.elCache[E]){Ext.elCache[E].events={}}},getListeners:function(G,D){G=Ext.getDom(G);var I=o(G),E=Ext.elCache[I]||{},H=E.events||{},F=[];if(H&&H[D]){return H[D]}else{return null}},purgeElement:function(F,D,H){F=Ext.getDom(F);var E=o(F),K=Ext.elCache[E]||{},L=K.events||{},G,J,I;if(H){if(L&&L.hasOwnProperty(H)){J=L[H];for(G=0,I=J.length;G<I;G++){Ext.EventManager.removeListener(F,H,J[G][0])}}}else{Ext.EventManager.removeAll(F)}if(D&&F&&F.childNodes){for(G=0,I=F.childNodes.length;G<I;G++){Ext.EventManager.purgeElement(F.childNodes[G],D,H)}}},_unload:function(){var D;for(D in Ext.elCache){Ext.EventManager.removeAll(D)}delete Ext.elCache;delete Ext.Element._flyweights;var H,E,G,F=Ext.lib.Ajax;(typeof F.conn=="object")?E=F.conn:E={};for(G in E){H=E[G];if(H){F.abort({conn:H,tId:G})}}},onDocumentReady:function(F,E,D){if(Ext.isReady){A||(A=new Ext.util.Event());A.addListener(F,E,D);A.fire();A.listeners=[]}else{if(!A){a()}D=D||{};D.delay=D.delay||1;A.addListener(F,E,D)}},fireDocReady:b};w.on=w.addListener;w.un=w.removeListener;w.stoppedMouseDownEvent=new Ext.util.Event();return w}();Ext.onReady=Ext.EventManager.onDocumentReady;(function(){var a=function(){var c=document.body||document.getElementsByTagName("body")[0];if(!c){return false}var b=[" ",Ext.isIE?"ext-ie "+(Ext.isIE6?"ext-ie6":(Ext.isIE7?"ext-ie7":"ext-ie8")):Ext.isGecko?"ext-gecko "+(Ext.isGecko2?"ext-gecko2":"ext-gecko3"):Ext.isOpera?"ext-opera":Ext.isWebKit?"ext-webkit":""];if(Ext.isSafari){b.push("ext-safari "+(Ext.isSafari2?"ext-safari2":(Ext.isSafari3?"ext-safari3":"ext-safari4")))}else{if(Ext.isChrome){b.push("ext-chrome")}}if(Ext.isMac){b.push("ext-mac")}if(Ext.isLinux){b.push("ext-linux")}if(Ext.isStrict||Ext.isBorderBox){var d=c.parentNode;if(d){Ext.fly(d,"_internal").addClass(((Ext.isStrict&&Ext.isIE)||(!Ext.enableForcedBoxModel&&!Ext.isIE))?" ext-strict":" ext-border-box")}}if(Ext.enableForcedBoxModel&&!Ext.isIE){Ext.isForcedBorderBox=true;b.push("ext-forced-border-box")}Ext.fly(c,"_internal").addClass(b);return true};if(!a()){Ext.onReady(a)}})();(function(){var b=Ext.apply(Ext.supports,{correctRightMargin:true,correctTransparentColor:true,cssFloat:true});var a=function(){var g=document.createElement("div"),e=document,c,d;g.innerHTML='<div style="height:30px;width:50px;"><div style="height:20px;width:20px;"></div></div><div style="float:left;background-color:transparent;">';e.body.appendChild(g);d=g.lastChild;if((c=e.defaultView)){if(c.getComputedStyle(g.firstChild.firstChild,null).marginRight!="0px"){b.correctRightMargin=false}if(c.getComputedStyle(d,null).backgroundColor!="transparent"){b.correctTransparentColor=false}}b.cssFloat=!!d.style.cssFloat;e.body.removeChild(g)};if(Ext.isReady){a()}else{Ext.onReady(a)}})();Ext.EventObject=function(){var b=Ext.lib.Event,c=/(dbl)?click/,a={3:13,63234:37,63235:39,63232:38,63233:40,63276:33,63277:34,63272:46,63273:36,63275:35},d=Ext.isIE?{1:0,4:1,2:2}:{0:0,1:1,2:2};Ext.EventObjectImpl=function(g){if(g){this.setEvent(g.browserEvent||g)}};Ext.EventObjectImpl.prototype={setEvent:function(h){var g=this;if(h==g||(h&&h.browserEvent)){return h}g.browserEvent=h;if(h){g.button=h.button?d[h.button]:(h.which?h.which-1:-1);if(c.test(h.type)&&g.button==-1){g.button=0}g.type=h.type;g.shiftKey=h.shiftKey;g.ctrlKey=h.ctrlKey||h.metaKey||false;g.altKey=h.altKey;g.keyCode=h.keyCode;g.charCode=h.charCode;g.target=b.getTarget(h);g.xy=b.getXY(h)}else{g.button=-1;g.shiftKey=false;g.ctrlKey=false;g.altKey=false;g.keyCode=0;g.charCode=0;g.target=null;g.xy=[0,0]}return g},stopEvent:function(){var e=this;if(e.browserEvent){if(e.browserEvent.type=="mousedown"){Ext.EventManager.stoppedMouseDownEvent.fire(e)}b.stopEvent(e.browserEvent)}},preventDefault:function(){if(this.browserEvent){b.preventDefault(this.browserEvent)}},stopPropagation:function(){var e=this;if(e.browserEvent){if(e.browserEvent.type=="mousedown"){Ext.EventManager.stoppedMouseDownEvent.fire(e)}b.stopPropagation(e.browserEvent)}},getCharCode:function(){return this.charCode||this.keyCode},getKey:function(){return this.normalizeKey(this.keyCode||this.charCode)},normalizeKey:function(e){return Ext.isSafari?(a[e]||e):e},getPageX:function(){return this.xy[0]},getPageY:function(){return this.xy[1]},getXY:function(){return this.xy},getTarget:function(g,h,e){return g?Ext.fly(this.target).findParent(g,h,e):(e?Ext.get(this.target):this.target)},getRelatedTarget:function(){return this.browserEvent?b.getRelatedTarget(this.browserEvent):null},getWheelDelta:function(){var g=this.browserEvent;var h=0;if(g.wheelDelta){h=g.wheelDelta/120}else{if(g.detail){h=-g.detail/3}}return h},within:function(h,i,e){if(h){var g=this[i?"getRelatedTarget":"getTarget"]();return g&&((e?(g==Ext.getDom(h)):false)||Ext.fly(h).contains(g))}return false}};return new Ext.EventObjectImpl()}();Ext.Loader=Ext.apply({},{load:function(k,i,l,c){var l=l||this,g=document.getElementsByTagName("head")[0],b=document.createDocumentFragment(),a=k.length,h=0,e=this;var m=function(n){g.appendChild(e.buildScriptTag(k[n],d))};var d=function(){h++;if(a==h&&typeof i=="function"){i.call(l)}else{if(c===true){m(h)}}};if(c===true){m.call(this,0)}else{Ext.each(k,function(o,n){b.appendChild(this.buildScriptTag(o,d))},this);g.appendChild(b)}},buildScriptTag:function(b,c){var a=document.createElement("script");a.type="text/javascript";a.src=b;if(a.readyState){a.onreadystatechange=function(){if(a.readyState=="loaded"||a.readyState=="complete"){a.onreadystatechange=null;c()}}}else{a.onload=c}return a}});Ext.ns("Ext.grid","Ext.list","Ext.dd","Ext.tree","Ext.form","Ext.menu","Ext.state","Ext.layout","Ext.app","Ext.ux","Ext.chart","Ext.direct");Ext.apply(Ext,function(){var c=Ext,a=0,b=null;return{emptyFn:function(){},BLANK_IMAGE_URL:Ext.isIE6||Ext.isIE7||Ext.isAir?"http://www.extjs.com/s.gif":"data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==",extendX:function(d,e){return Ext.extend(d,e(d.prototype))},getDoc:function(){return Ext.get(document)},num:function(e,d){e=Number(Ext.isEmpty(e)||Ext.isArray(e)||typeof e=="boolean"||(typeof e=="string"&&e.trim().length==0)?NaN:e);return isNaN(e)?d:e},value:function(g,d,e){return Ext.isEmpty(g,e)?d:g},escapeRe:function(d){return d.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1")},sequence:function(h,d,g,e){h[d]=h[d].createSequence(g,e)},addBehaviors:function(i){if(!Ext.isReady){Ext.onReady(function(){Ext.addBehaviors(i)})}else{var e={},h,d,g;for(d in i){if((h=d.split("@"))[1]){g=h[0];if(!e[g]){e[g]=Ext.select(g)}e[g].on(h[1],i[d])}}e=null}},getScrollBarWidth:function(g){if(!Ext.isReady){return 0}if(g===true||b===null){var i=Ext.getBody().createChild('<div class="x-hide-offsets" style="width:100px;height:50px;overflow:hidden;"><div style="height:200px;"></div></div>'),h=i.child("div",true);var e=h.offsetWidth;i.setStyle("overflow",(Ext.isWebKit||Ext.isGecko)?"auto":"scroll");var d=h.offsetWidth;i.remove();b=e-d+2}return b},combine:function(){var g=arguments,e=g.length,k=[];for(var h=0;h<e;h++){var d=g[h];if(Ext.isArray(d)){k=k.concat(d)}else{if(d.length!==undefined&&!d.substr){k=k.concat(Array.prototype.slice.call(d,0))}else{k.push(d)}}}return k},copyTo:function(d,e,g){if(typeof g=="string"){g=g.split(/[,;\s]/)}Ext.each(g,function(h){if(e.hasOwnProperty(h)){d[h]=e[h]}},this);return d},destroy:function(){Ext.each(arguments,function(d){if(d){if(Ext.isArray(d)){this.destroy.apply(this,d)}else{if(typeof d.destroy=="function"){d.destroy()}else{if(d.dom){d.remove()}}}}},this)},destroyMembers:function(m,k,g,h){for(var l=1,e=arguments,d=e.length;l<d;l++){Ext.destroy(m[e[l]]);delete m[e[l]]}},clean:function(d){var e=[];Ext.each(d,function(g){if(!!g){e.push(g)}});return e},unique:function(d){var e=[],g={};Ext.each(d,function(h){if(!g[h]){e.push(h)}g[h]=true});return e},flatten:function(d){var g=[];function e(h){Ext.each(h,function(i){if(Ext.isArray(i)){e(i)}else{g.push(i)}});return g}return e(d)},min:function(d,e){var g=d[0];e=e||function(i,h){return i<h?-1:1};Ext.each(d,function(h){g=e(g,h)==-1?g:h});return g},max:function(d,e){var g=d[0];e=e||function(i,h){return i>h?1:-1};Ext.each(d,function(h){g=e(g,h)==1?g:h});return g},mean:function(d){return d.length>0?Ext.sum(d)/d.length:undefined},sum:function(d){var e=0;Ext.each(d,function(g){e+=g});return e},partition:function(d,e){var g=[[],[]];Ext.each(d,function(k,l,h){g[(e&&e(k,l,h))||(!e&&k)?0:1].push(k)});return g},invoke:function(d,e){var h=[],g=Array.prototype.slice.call(arguments,2);Ext.each(d,function(k,l){if(k&&typeof k[e]=="function"){h.push(k[e].apply(k,g))}else{h.push(undefined)}});return h},pluck:function(d,g){var e=[];Ext.each(d,function(h){e.push(h[g])});return e},zip:function(){var n=Ext.partition(arguments,function(i){return typeof i!="function"}),k=n[0],m=n[1][0],d=Ext.max(Ext.pluck(k,"length")),h=[];for(var l=0;l<d;l++){h[l]=[];if(m){h[l]=m.apply(m,Ext.pluck(k,l))}else{for(var g=0,e=k.length;g<e;g++){h[l].push(k[g][l])}}}return h},getCmp:function(d){return Ext.ComponentMgr.get(d)},useShims:c.isIE6||(c.isMac&&c.isGecko2),type:function(e){if(e===undefined||e===null){return false}if(e.htmlElement){return"element"}var d=typeof e;if(d=="object"&&e.nodeName){switch(e.nodeType){case 1:return"element";case 3:return(/\S/).test(e.nodeValue)?"textnode":"whitespace"}}if(d=="object"||d=="function"){switch(e.constructor){case Array:return"array";case RegExp:return"regexp";case Date:return"date"}if(typeof e.length=="number"&&typeof e.item=="function"){return"nodelist"}}return d},intercept:function(h,d,g,e){h[d]=h[d].createInterceptor(g,e)},callback:function(d,h,g,e){if(typeof d=="function"){if(e){d.defer(e,h,g||[])}else{d.apply(h,g||[])}}}}}());Ext.apply(Function.prototype,{createSequence:function(b,a){var c=this;return(typeof b!="function")?this:function(){var d=c.apply(this||window,arguments);b.apply(a||this||window,arguments);return d}}});Ext.applyIf(String,{escape:function(a){return a.replace(/('|\\)/g,"\\$1")},leftPad:function(d,b,c){var a=String(d);if(!c){c=" "}while(a.length<b){a=c+a}return a}});String.prototype.toggle=function(b,a){return this==b?a:b};String.prototype.trim=function(){var a=/^\s+|\s+$/g;return function(){return this.replace(a,"")}}();Date.prototype.getElapsed=function(a){return Math.abs((a||new Date()).getTime()-this.getTime())};Ext.applyIf(Number.prototype,{constrain:function(b,a){return Math.min(Math.max(this,b),a)}});Ext.lib.Dom.getRegion=function(a){return Ext.lib.Region.getRegion(a)};Ext.lib.Region=function(d,g,a,c){var e=this;e.top=d;e[1]=d;e.right=g;e.bottom=a;e.left=c;e[0]=c};Ext.lib.Region.prototype={contains:function(b){var a=this;return(b.left>=a.left&&b.right<=a.right&&b.top>=a.top&&b.bottom<=a.bottom)},getArea:function(){var a=this;return((a.bottom-a.top)*(a.right-a.left))},intersect:function(h){var g=this,d=Math.max(g.top,h.top),e=Math.min(g.right,h.right),a=Math.min(g.bottom,h.bottom),c=Math.max(g.left,h.left);if(a>=d&&e>=c){return new Ext.lib.Region(d,e,a,c)}},union:function(h){var g=this,d=Math.min(g.top,h.top),e=Math.max(g.right,h.right),a=Math.max(g.bottom,h.bottom),c=Math.min(g.left,h.left);return new Ext.lib.Region(d,e,a,c)},constrainTo:function(b){var a=this;a.top=a.top.constrain(b.top,b.bottom);a.bottom=a.bottom.constrain(b.top,b.bottom);a.left=a.left.constrain(b.left,b.right);a.right=a.right.constrain(b.left,b.right);return a},adjust:function(d,c,a,g){var e=this;e.top+=d;e.left+=c;e.right+=g;e.bottom+=a;return e}};Ext.lib.Region.getRegion=function(e){var h=Ext.lib.Dom.getXY(e),d=h[1],g=h[0]+e.offsetWidth,a=h[1]+e.offsetHeight,c=h[0];return new Ext.lib.Region(d,g,a,c)};Ext.lib.Point=function(a,c){if(Ext.isArray(a)){c=a[1];a=a[0]}var b=this;b.x=b.right=b.left=b[0]=a;b.y=b.top=b.bottom=b[1]=c};Ext.lib.Point.prototype=new Ext.lib.Region();Ext.apply(Ext.DomHelper,function(){var e,a="afterbegin",h="afterend",i="beforebegin",d="beforeend",b=/tag|children|cn|html$/i;function g(n,q,p,r,m,k){n=Ext.getDom(n);var l;if(e.useDom){l=c(q,null);if(k){n.appendChild(l)}else{(m=="firstChild"?n:n.parentNode).insertBefore(l,n[m]||n)}}else{l=Ext.DomHelper.insertHtml(r,n,Ext.DomHelper.createHtml(q))}return p?Ext.get(l,true):l}function c(k,s){var m,v=document,q,t,n,u;if(Ext.isArray(k)){m=v.createDocumentFragment();for(var r=0,p=k.length;r<p;r++){c(k[r],m)}}else{if(typeof k=="string"){m=v.createTextNode(k)}else{m=v.createElement(k.tag||"div");q=!!m.setAttribute;for(var t in k){if(!b.test(t)){n=k[t];if(t=="cls"){m.className=n}else{if(q){m.setAttribute(t,n)}else{m[t]=n}}}}Ext.DomHelper.applyStyles(m,k.style);if((u=k.children||k.cn)){c(u,m)}else{if(k.html){m.innerHTML=k.html}}}}if(s){s.appendChild(m)}return m}e={createTemplate:function(l){var k=Ext.DomHelper.createHtml(l);return new Ext.Template(k)},useDom:false,insertBefore:function(k,m,l){return g(k,m,l,i)},insertAfter:function(k,m,l){return g(k,m,l,h,"nextSibling")},insertFirst:function(k,m,l){return g(k,m,l,a,"firstChild")},append:function(k,m,l){return g(k,m,l,d,"",true)},createDom:c};return e}());Ext.apply(Ext.Template.prototype,{disableFormats:false,re:/\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,argsRe:/^\s*['"](.*)["']\s*$/,compileARe:/\\/g,compileBRe:/(\r\n|\n)/g,compileCRe:/'/g,applyTemplate:function(b){var g=this,a=g.disableFormats!==true,e=Ext.util.Format,c=g;if(g.compiled){return g.compiled(b)}function d(k,n,q,l){if(q&&a){if(q.substr(0,5)=="this."){return c.call(q.substr(5),b[n],b)}else{if(l){var p=g.argsRe;l=l.split(",");for(var o=0,h=l.length;o<h;o++){l[o]=l[o].replace(p,"$1")}l=[b[n]].concat(l)}else{l=[b[n]]}return e[q].apply(e,l)}}else{return b[n]!==undefined?b[n]:""}}return g.html.replace(g.re,d)},compile:function(){var me=this,fm=Ext.util.Format,useF=me.disableFormats!==true,sep=Ext.isGecko?"+":",",body;function fn(m,name,format,args){if(format&&useF){args=args?","+args:"";if(format.substr(0,5)!="this."){format="fm."+format+"("}else{format='this.call("'+format.substr(5)+'", ';args=", values"}}else{args="";format="(values['"+name+"'] == undefined ? '' : "}return"'"+sep+format+"values['"+name+"']"+args+")"+sep+"'"}if(Ext.isGecko){body="this.compiled = function(values){ return '"+me.html.replace(me.compileARe,"\\\\").replace(me.compileBRe,"\\n").replace(me.compileCRe,"\\'").replace(me.re,fn)+"';};"}else{body=["this.compiled = function(values){ return ['"];body.push(me.html.replace(me.compileARe,"\\\\").replace(me.compileBRe,"\\n").replace(me.compileCRe,"\\'").replace(me.re,fn));body.push("'].join('');};");body=body.join("")}eval(body);return me},call:function(c,b,a){return this[c](b,a)}});Ext.Template.prototype.apply=Ext.Template.prototype.applyTemplate;Ext.util.Functions={createInterceptor:function(c,b,a){var d=c;if(!Ext.isFunction(b)){return c}else{return function(){var g=this,e=arguments;b.target=g;b.method=c;return(b.apply(a||g||window,e)!==false)?c.apply(g||window,e):null}}},createDelegate:function(c,d,b,a){if(!Ext.isFunction(c)){return c}return function(){var g=b||arguments;if(a===true){g=Array.prototype.slice.call(arguments,0);g=g.concat(b)}else{if(Ext.isNumber(a)){g=Array.prototype.slice.call(arguments,0);var e=[a,0].concat(b);Array.prototype.splice.apply(g,e)}}return c.apply(d||window,g)}},defer:function(d,c,e,b,a){d=Ext.util.Functions.createDelegate(d,e,b,a);if(c>0){return setTimeout(d,c)}d();return 0},createSequence:function(c,b,a){if(!Ext.isFunction(b)){return c}else{return function(){var d=c.apply(this||window,arguments);b.apply(a||this||window,arguments);return d}}}};Ext.defer=Ext.util.Functions.defer;Ext.createInterceptor=Ext.util.Functions.createInterceptor;Ext.createSequence=Ext.util.Functions.createSequence;Ext.createDelegate=Ext.util.Functions.createDelegate;Ext.apply(Ext.util.Observable.prototype,function(){function a(k){var i=(this.methodEvents=this.methodEvents||{})[k],d,c,g,h=this;if(!i){this.methodEvents[k]=i={};i.originalFn=this[k];i.methodName=k;i.before=[];i.after=[];var b=function(m,l,e){if((c=m.apply(l||h,e))!==undefined){if(typeof c=="object"){if(c.returnValue!==undefined){d=c.returnValue}else{d=c}g=!!c.cancel}else{if(c===false){g=true}else{d=c}}}};this[k]=function(){var m=Array.prototype.slice.call(arguments,0),l;d=c=undefined;g=false;for(var n=0,e=i.before.length;n<e;n++){l=i.before[n];b(l.fn,l.scope,m);if(g){return d}}if((c=i.originalFn.apply(h,m))!==undefined){d=c}for(var n=0,e=i.after.length;n<e;n++){l=i.after[n];b(l.fn,l.scope,m);if(g){return d}}return d}}return i}return{beforeMethod:function(d,c,b){a.call(this,d).before.push({fn:c,scope:b})},afterMethod:function(d,c,b){a.call(this,d).after.push({fn:c,scope:b})},removeMethodListener:function(k,g,d){var h=this.getMethodEvent(k);for(var c=0,b=h.before.length;c<b;c++){if(h.before[c].fn==g&&h.before[c].scope==d){h.before.splice(c,1);return}}for(var c=0,b=h.after.length;c<b;c++){if(h.after[c].fn==g&&h.after[c].scope==d){h.after.splice(c,1);return}}},relayEvents:function(k,e){var h=this;function g(i){return function(){return h.fireEvent.apply(h,[i].concat(Array.prototype.slice.call(arguments,0)))}}for(var d=0,b=e.length;d<b;d++){var c=e[d];h.events[c]=h.events[c]||true;k.on(c,g(c),h)}},enableBubble:function(e){var g=this;if(!Ext.isEmpty(e)){e=Ext.isArray(e)?e:Array.prototype.slice.call(arguments,0);for(var d=0,b=e.length;d<b;d++){var c=e[d];c=c.toLowerCase();var h=g.events[c]||true;if(typeof h=="boolean"){h=new Ext.util.Event(g,c);g.events[c]=h}h.bubble=true}}}}}());Ext.util.Observable.capture=function(c,b,a){c.fireEvent=c.fireEvent.createInterceptor(b,a)};Ext.util.Observable.observeClass=function(b,a){if(b){if(!b.fireEvent){Ext.apply(b,new Ext.util.Observable());Ext.util.Observable.capture(b.prototype,b.fireEvent,b)}if(typeof a=="object"){b.on(a)}return b}};Ext.apply(Ext.EventManager,function(){var c,k,e,b,a=Ext.lib.Dom,i=/^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,h=0,g=0,d=Ext.isWebKit?Ext.num(navigator.userAgent.match(/AppleWebKit\/(\d+)/)[1])>=525:!((Ext.isGecko&&!Ext.isWindows)||Ext.isOpera);return{doResizeEvent:function(){var m=a.getViewHeight(),l=a.getViewWidth();if(g!=m||h!=l){c.fire(h=l,g=m)}},onWindowResize:function(n,m,l){if(!c){c=new Ext.util.Event();k=new Ext.util.DelayedTask(this.doResizeEvent);Ext.EventManager.on(window,"resize",this.fireWindowResize,this)}c.addListener(n,m,l)},fireWindowResize:function(){if(c){k.delay(100)}},onTextResize:function(o,n,l){if(!e){e=new Ext.util.Event();var m=new Ext.Element(document.createElement("div"));m.dom.className="x-text-resize";m.dom.innerHTML="X";m.appendTo(document.body);b=m.dom.offsetHeight;setInterval(function(){if(m.dom.offsetHeight!=b){e.fire(b,b=m.dom.offsetHeight)}},this.textResizeInterval)}e.addListener(o,n,l)},removeResizeListener:function(m,l){if(c){c.removeListener(m,l)}},fireResize:function(){if(c){c.fire(a.getViewWidth(),a.getViewHeight())}},textResizeInterval:50,ieDeferSrc:false,getKeyEvent:function(){return d?"keydown":"keypress"},useKeydown:d}}());Ext.EventManager.on=Ext.EventManager.addListener;Ext.apply(Ext.EventObjectImpl.prototype,{BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,RETURN:13,SHIFT:16,CTRL:17,CONTROL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGEUP:33,PAGE_DOWN:34,PAGEDOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,isNavKeyPress:function(){var b=this,a=this.normalizeKey(b.keyCode);return(a>=33&&a<=40)||a==b.RETURN||a==b.TAB||a==b.ESC},isSpecialKey:function(){var a=this.normalizeKey(this.keyCode);return(this.type=="keypress"&&this.ctrlKey)||this.isNavKeyPress()||(a==this.BACKSPACE)||(a>=16&&a<=20)||(a>=44&&a<=46)},getPoint:function(){return new Ext.lib.Point(this.xy[0],this.xy[1])},hasModifier:function(){return((this.ctrlKey||this.altKey)||this.shiftKey)}});Ext.Element.addMethods({swallowEvent:function(a,b){var d=this;function c(g){g.stopPropagation();if(b){g.preventDefault()}}if(Ext.isArray(a)){Ext.each(a,function(g){d.on(g,c)});return d}d.on(a,c);return d},relayEvent:function(a,b){this.on(a,function(c){b.fireEvent(a,c)})},clean:function(b){var d=this,e=d.dom,g=e.firstChild,c=-1;if(Ext.Element.data(e,"isCleaned")&&b!==true){return d}while(g){var a=g.nextSibling;if(g.nodeType==3&&!(/\S/.test(g.nodeValue))){e.removeChild(g)}else{g.nodeIndex=++c}g=a}Ext.Element.data(e,"isCleaned",true);return d},load:function(){var a=this.getUpdater();a.update.apply(a,arguments);return this},getUpdater:function(){return this.updateManager||(this.updateManager=new Ext.Updater(this))},update:function(html,loadScripts,callback){if(!this.dom){return this}html=html||"";if(loadScripts!==true){this.dom.innerHTML=html;if(typeof callback=="function"){callback()}return this}var id=Ext.id(),dom=this.dom;html+='<span id="'+id+'"></span>';Ext.lib.Event.onAvailable(id,function(){var DOC=document,hd=DOC.getElementsByTagName("head")[0],re=/(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,srcRe=/\ssrc=([\'\"])(.*?)\1/i,typeRe=/\stype=([\'\"])(.*?)\1/i,match,attrs,srcMatch,typeMatch,el,s;while((match=re.exec(html))){attrs=match[1];srcMatch=attrs?attrs.match(srcRe):false;if(srcMatch&&srcMatch[2]){s=DOC.createElement("script");s.src=srcMatch[2];typeMatch=attrs.match(typeRe);if(typeMatch&&typeMatch[2]){s.type=typeMatch[2]}hd.appendChild(s)}else{if(match[2]&&match[2].length>0){if(window.execScript){window.execScript(match[2])}else{window.eval(match[2])}}}}el=DOC.getElementById(id);if(el){Ext.removeNode(el)}if(typeof callback=="function"){callback()}});dom.innerHTML=html.replace(/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,"");return this},removeAllListeners:function(){this.removeAnchor();Ext.EventManager.removeAll(this.dom);return this},createProxy:function(a,e,d){a=(typeof a=="object")?a:{tag:"div",cls:a};var c=this,b=e?Ext.DomHelper.append(e,a,true):Ext.DomHelper.insertBefore(c.dom,a,true);if(d&&c.setBox&&c.getBox){b.setBox(c.getBox())}return b}});Ext.Element.prototype.getUpdateManager=Ext.Element.prototype.getUpdater;Ext.Element.addMethods({getAnchorXY:function(e,m,t){e=(e||"tl").toLowerCase();t=t||{};var l=this,b=l.dom==document.body||l.dom==document,p=t.width||b?Ext.lib.Dom.getViewWidth():l.getWidth(),i=t.height||b?Ext.lib.Dom.getViewHeight():l.getHeight(),q,a=Math.round,c=l.getXY(),n=l.getScroll(),k=b?n.left:!m?c[0]:0,g=b?n.top:!m?c[1]:0,d={c:[a(p*0.5),a(i*0.5)],t:[a(p*0.5),0],l:[0,a(i*0.5)],r:[p,a(i*0.5)],b:[a(p*0.5),i],tl:[0,0],bl:[0,i],br:[p,i],tr:[p,0]};q=d[e];return[q[0]+k,q[1]+g]},anchorTo:function(b,h,c,a,l,m){var i=this,e=i.dom,k=!Ext.isEmpty(l),d=function(){Ext.fly(e).alignTo(b,h,c,a);Ext.callback(m,Ext.fly(e))},g=this.getAnchor();this.removeAnchor();Ext.apply(g,{fn:d,scroll:k});Ext.EventManager.onWindowResize(d,null);if(k){Ext.EventManager.on(window,"scroll",d,null,{buffer:!isNaN(l)?l:50})}d.call(i);return i},removeAnchor:function(){var b=this,a=this.getAnchor();if(a&&a.fn){Ext.EventManager.removeResizeListener(a.fn);if(a.scroll){Ext.EventManager.un(window,"scroll",a.fn)}delete a.fn}return b},getAnchor:function(){var b=Ext.Element.data,c=this.dom;if(!c){return}var a=b(c,"_anchor");if(!a){a=b(c,"_anchor",{})}return a},getAlignToXY:function(g,B,C){g=Ext.get(g);if(!g||!g.dom){throw"Element.alignToXY with an element that doesn't exist"}C=C||[0,0];B=(!B||B=="?"?"tl-bl?":(!(/-/).test(B)&&B!==""?"tl-"+B:B||"tl-bl")).toLowerCase();var L=this,I=L.dom,N,M,q,n,t,G,z,u=Ext.lib.Dom.getViewWidth()-10,H=Ext.lib.Dom.getViewHeight()-10,b,i,k,l,v,A,O=document,K=O.documentElement,s=O.body,F=(K.scrollLeft||s.scrollLeft||0)+5,E=(K.scrollTop||s.scrollTop||0)+5,J=false,e="",a="",D=B.match(/^([a-z]+)-([a-z]+)(\?)?$/);if(!D){throw"Element.alignTo with an invalid alignment "+B}e=D[1];a=D[2];J=!!D[3];N=L.getAnchorXY(e,true);M=g.getAnchorXY(a,false);q=M[0]-N[0]+C[0];n=M[1]-N[1]+C[1];if(J){t=L.getWidth();G=L.getHeight();z=g.getRegion();b=e.charAt(0);i=e.charAt(e.length-1);k=a.charAt(0);l=a.charAt(a.length-1);v=((b=="t"&&k=="b")||(b=="b"&&k=="t"));A=((i=="r"&&l=="l")||(i=="l"&&l=="r"));if(q+t>u+F){q=A?z.left-t:u+F-t}if(q<F){q=A?z.right:F}if(n+G>H+E){n=v?z.top-G:H+E-G}if(n<E){n=v?z.bottom:E}}return[q,n]},alignTo:function(c,a,e,b){var d=this;return d.setXY(d.getAlignToXY(c,a,e),d.preanim&&!!b?d.preanim(arguments,3):false)},adjustForConstraints:function(c,a,b){return this.getConstrainToXY(a||document,false,b,c)||c},getConstrainToXY:function(b,a,c,e){var d={top:0,left:0,bottom:0,right:0};return function(i,B,m,o){i=Ext.get(i);m=m?Ext.applyIf(m,d):d;var A,E,z=0,v=0;if(i.dom==document.body||i.dom==document){A=Ext.lib.Dom.getViewWidth();E=Ext.lib.Dom.getViewHeight()}else{A=i.dom.clientWidth;E=i.dom.clientHeight;if(!B){var u=i.getXY();z=u[0];v=u[1]}}var t=i.getScroll();z+=m.left+t.left;v+=m.top+t.top;A-=m.right;E-=m.bottom;var C=z+A,g=v+E,k=o||(!B?this.getXY():[this.getLeft(true),this.getTop(true)]),q=k[0],p=k[1],l=this.getConstrainOffset(),r=this.dom.offsetWidth+l,D=this.dom.offsetHeight+l;var n=false;if((q+r)>C){q=C-r;n=true}if((p+D)>g){p=g-D;n=true}if(q<z){q=z;n=true}if(p<v){p=v;n=true}return n?[q,p]:false}}(),getConstrainOffset:function(){return 0},getCenterXY:function(){return this.getAlignToXY(document,"c-c")},center:function(a){return this.alignTo(a||document,"c-c")}});Ext.Element.addMethods({select:function(a,b){return Ext.Element.select(a,b,this.dom)}});Ext.apply(Ext.Element.prototype,function(){var c=Ext.getDom,a=Ext.get,b=Ext.DomHelper;return{insertSibling:function(i,g,h){var k=this,e,d=(g||"before").toLowerCase()=="after",l;if(Ext.isArray(i)){l=k;Ext.each(i,function(m){e=Ext.fly(l,"_internal").insertSibling(m,g,h);if(d){l=e}});return e}i=i||{};if(i.nodeType||i.dom){e=k.dom.parentNode.insertBefore(c(i),d?k.dom.nextSibling:k.dom);if(!h){e=a(e)}}else{if(d&&!k.dom.nextSibling){e=b.append(k.dom.parentNode,i,!h)}else{e=b[d?"insertAfter":"insertBefore"](k.dom,i,!h)}}return e}}}());Ext.Element.boxMarkup='<div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div><div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div><div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>';Ext.Element.addMethods(function(){var a="_internal",b=/(\d+\.?\d+)px/;return{applyStyles:function(c){Ext.DomHelper.applyStyles(this.dom,c);return this},getStyles:function(){var c={};Ext.each(arguments,function(d){c[d]=this.getStyle(d)},this);return c},setOverflow:function(c){var d=this.dom;if(c=="auto"&&Ext.isMac&&Ext.isGecko2){d.style.overflow="hidden";(function(){d.style.overflow="auto"}).defer(1)}else{d.style.overflow=c}},boxWrap:function(c){c=c||"x-box";var d=Ext.get(this.insertHtml("beforeBegin","<div class='"+c+"'>"+String.format(Ext.Element.boxMarkup,c)+"</div>"));Ext.DomQuery.selectNode("."+c+"-mc",d.dom).appendChild(this.dom);return d},setSize:function(e,c,d){var g=this;if(typeof e=="object"){c=e.height;e=e.width}e=g.adjustWidth(e);c=g.adjustHeight(c);if(!d||!g.anim){g.dom.style.width=g.addUnits(e);g.dom.style.height=g.addUnits(c)}else{g.anim({width:{to:e},height:{to:c}},g.preanim(arguments,2))}return g},getComputedHeight:function(){var d=this,c=Math.max(d.dom.offsetHeight,d.dom.clientHeight);if(!c){c=parseFloat(d.getStyle("height"))||0;if(!d.isBorderBox()){c+=d.getFrameWidth("tb")}}return c},getComputedWidth:function(){var c=Math.max(this.dom.offsetWidth,this.dom.clientWidth);if(!c){c=parseFloat(this.getStyle("width"))||0;if(!this.isBorderBox()){c+=this.getFrameWidth("lr")}}return c},getFrameWidth:function(d,c){return c&&this.isBorderBox()?0:(this.getPadding(d)+this.getBorderWidth(d))},addClassOnOver:function(c){this.hover(function(){Ext.fly(this,a).addClass(c)},function(){Ext.fly(this,a).removeClass(c)});return this},addClassOnFocus:function(c){this.on("focus",function(){Ext.fly(this,a).addClass(c)},this.dom);this.on("blur",function(){Ext.fly(this,a).removeClass(c)},this.dom);return this},addClassOnClick:function(c){var d=this.dom;this.on("mousedown",function(){Ext.fly(d,a).addClass(c);var g=Ext.getDoc(),e=function(){Ext.fly(d,a).removeClass(c);g.removeListener("mouseup",e)};g.on("mouseup",e)});return this},getViewSize:function(){var g=document,h=this.dom,c=(h==g||h==g.body);if(c){var e=Ext.lib.Dom;return{width:e.getViewWidth(),height:e.getViewHeight()}}else{return{width:h.clientWidth,height:h.clientHeight}}},getStyleSize:function(){var k=this,c,i,m=document,n=this.dom,e=(n==m||n==m.body),g=n.style;if(e){var l=Ext.lib.Dom;return{width:l.getViewWidth(),height:l.getViewHeight()}}if(g.width&&g.width!="auto"){c=parseFloat(g.width);if(k.isBorderBox()){c-=k.getFrameWidth("lr")}}if(g.height&&g.height!="auto"){i=parseFloat(g.height);if(k.isBorderBox()){i-=k.getFrameWidth("tb")}}return{width:c||k.getWidth(true),height:i||k.getHeight(true)}},getSize:function(c){return{width:this.getWidth(c),height:this.getHeight(c)}},repaint:function(){var c=this.dom;this.addClass("x-repaint");setTimeout(function(){Ext.fly(c).removeClass("x-repaint")},1);return this},unselectable:function(){this.dom.unselectable="on";return this.swallowEvent("selectstart",true).applyStyles("-moz-user-select:none;-khtml-user-select:none;").addClass("x-unselectable")},getMargins:function(d){var e=this,c,g={t:"top",l:"left",r:"right",b:"bottom"},h={};if(!d){for(c in e.margins){h[g[c]]=parseFloat(e.getStyle(e.margins[c]))||0}return h}else{return e.addStyles.call(e,d,e.margins)}}}}());Ext.Element.addMethods({setBox:function(e,g,b){var d=this,a=e.width,c=e.height;if((g&&!d.autoBoxAdjust)&&!d.isBorderBox()){a-=(d.getBorderWidth("lr")+d.getPadding("lr"));c-=(d.getBorderWidth("tb")+d.getPadding("tb"))}d.setBounds(e.x,e.y,a,c,d.animTest.call(d,arguments,b,2));return d},getBox:function(k,q){var n=this,x,e,p,d=n.getBorderWidth,s=n.getPadding,g,a,v,o;if(!q){x=n.getXY()}else{e=parseInt(n.getStyle("left"),10)||0;p=parseInt(n.getStyle("top"),10)||0;x=[e,p]}var c=n.dom,u=c.offsetWidth,i=c.offsetHeight,m;if(!k){m={x:x[0],y:x[1],0:x[0],1:x[1],width:u,height:i}}else{g=d.call(n,"l")+s.call(n,"l");a=d.call(n,"r")+s.call(n,"r");v=d.call(n,"t")+s.call(n,"t");o=d.call(n,"b")+s.call(n,"b");m={x:x[0]+g,y:x[1]+v,0:x[0]+g,1:x[1]+v,width:u-(g+a),height:i-(v+o)}}m.right=m.x+m.width;m.bottom=m.y+m.height;return m},move:function(k,b,c){var g=this,n=g.getXY(),l=n[0],i=n[1],d=[l-b,i],m=[l+b,i],h=[l,i-b],a=[l,i+b],e={l:d,left:d,r:m,right:m,t:h,top:h,up:h,b:a,bottom:a,down:a};k=k.toLowerCase();g.moveTo(e[k][0],e[k][1],g.animTest.call(g,arguments,c,2))},setLeftTop:function(d,c){var b=this,a=b.dom.style;a.left=b.addUnits(d);a.top=b.addUnits(c);return b},getRegion:function(){return Ext.lib.Dom.getRegion(this.dom)},setBounds:function(b,g,d,a,c){var e=this;if(!c||!e.anim){e.setSize(d,a);e.setLocation(b,g)}else{e.anim({points:{to:[b,g]},width:{to:e.adjustWidth(d)},height:{to:e.adjustHeight(a)}},e.preanim(arguments,4),"motion")}return e},setRegion:function(b,a){return this.setBounds(b.left,b.top,b.right-b.left,b.bottom-b.top,this.animTest.call(this,arguments,a,1))}});Ext.Element.addMethods({scrollTo:function(b,d,a){var e=/top/i.test(b),c=this,g=c.dom,h;if(!a||!c.anim){h="scroll"+(e?"Top":"Left");g[h]=d}else{h="scroll"+(e?"Left":"Top");c.anim({scroll:{to:e?[g[h],d]:[d,g[h]]}},c.preanim(arguments,2),"scroll")}return c},scrollIntoView:function(e,i){var q=Ext.getDom(e)||Ext.getBody().dom,h=this.dom,g=this.getOffsetsTo(q),m=g[0]+q.scrollLeft,v=g[1]+q.scrollTop,s=v+h.offsetHeight,d=m+h.offsetWidth,a=q.clientHeight,n=parseInt(q.scrollTop,10),u=parseInt(q.scrollLeft,10),k=n+a,p=u+q.clientWidth;if(h.offsetHeight>a||v<n){q.scrollTop=v}else{if(s>k){q.scrollTop=s-a}}q.scrollTop=q.scrollTop;if(i!==false){if(h.offsetWidth>q.clientWidth||m<u){q.scrollLeft=m}else{if(d>p){q.scrollLeft=d-q.clientWidth}}q.scrollLeft=q.scrollLeft}return this},scrollChildIntoView:function(b,a){Ext.fly(b,"_scrollChildIntoView").scrollIntoView(this,a)},scroll:function(n,b,d){if(!this.isScrollable()){return false}var e=this.dom,g=e.scrollLeft,q=e.scrollTop,o=e.scrollWidth,m=e.scrollHeight,i=e.clientWidth,a=e.clientHeight,c=false,p,k={l:Math.min(g+b,o-i),r:p=Math.max(g-b,0),t:Math.max(q-b,0),b:Math.min(q+b,m-a)};k.d=k.b;k.u=k.t;n=n.substr(0,1);if((p=k[n])>-1){c=true;this.scrollTo(n=="l"||n=="r"?"left":"top",p,this.preanim(arguments,2))}return c}});Ext.Element.addMethods(function(){var d="visibility",b="display",a="hidden",h="none",c="x-masked",g="x-masked-relative",e=Ext.Element.data;return{isVisible:function(i){var k=!this.isStyle(d,a)&&!this.isStyle(b,h),l=this.dom.parentNode;if(i!==true||!k){return k}while(l&&!(/^body/i.test(l.tagName))){if(!Ext.fly(l,"_isVisible").isVisible()){return false}l=l.parentNode}return true},isDisplayed:function(){return !this.isStyle(b,h)},enableDisplayMode:function(i){this.setVisibilityMode(Ext.Element.DISPLAY);if(!Ext.isEmpty(i)){e(this.dom,"originalDisplay",i)}return this},mask:function(k,o){var q=this,m=q.dom,p=Ext.DomHelper,n="ext-el-mask-msg",i,r;if(!(/^body/i.test(m.tagName)&&q.getStyle("position")=="static")){q.addClass(g)}if(i=e(m,"maskMsg")){i.remove()}if(i=e(m,"mask")){i.remove()}r=p.append(m,{cls:"ext-el-mask"},true);e(m,"mask",r);q.addClass(c);r.setDisplayed(true);if(typeof k=="string"){var l=p.append(m,{cls:n,cn:{tag:"div"}},true);e(m,"maskMsg",l);l.dom.className=o?n+" "+o:n;l.dom.firstChild.innerHTML=k;l.setDisplayed(true);l.center(q)}if(Ext.isIE&&!(Ext.isIE7&&Ext.isStrict)&&q.getStyle("height")=="auto"){r.setSize(undefined,q.getHeight())}return r},unmask:function(){var l=this,m=l.dom,i=e(m,"mask"),k=e(m,"maskMsg");if(i){if(k){k.remove();e(m,"maskMsg",undefined)}i.remove();e(m,"mask",undefined);l.removeClass([c,g])}},isMasked:function(){var i=e(this.dom,"mask");return i&&i.isVisible()},createShim:function(){var i=document.createElement("iframe"),k;i.frameBorder="0";i.className="ext-shim";i.src=Ext.SSL_SECURE_URL;k=Ext.get(this.dom.parentNode.insertBefore(i,this.dom));k.autoBoxAdjust=false;return k}}}());Ext.Element.addMethods({addKeyListener:function(b,d,c){var a;if(typeof b!="object"||Ext.isArray(b)){a={key:b,fn:d,scope:c}}else{a={key:b.key,shift:b.shift,ctrl:b.ctrl,alt:b.alt,fn:d,scope:c}}return new Ext.KeyMap(this,a)},addKeyMap:function(a){return new Ext.KeyMap(this,a)}});Ext.CompositeElementLite.importElementMethods();Ext.apply(Ext.CompositeElementLite.prototype,{addElements:function(c,a){if(!c){return this}if(typeof c=="string"){c=Ext.Element.selectorFunction(c,a)}var b=this.elements;Ext.each(c,function(d){b.push(Ext.get(d))});return this},first:function(){return this.item(0)},last:function(){return this.item(this.getCount()-1)},contains:function(a){return this.indexOf(a)!=-1},removeElement:function(d,e){var c=this,a=this.elements,b;Ext.each(d,function(g){if((b=(a[g]||a[g=c.indexOf(g)]))){if(e){if(b.dom){b.remove()}else{Ext.removeNode(b)}}a.splice(g,1)}});return this}});Ext.CompositeElement=Ext.extend(Ext.CompositeElementLite,{constructor:function(b,a){this.elements=[];this.add(b,a)},getElement:function(a){return a},transformElement:function(a){return Ext.get(a)}});Ext.Element.select=function(a,d,b){var c;if(typeof a=="string"){c=Ext.Element.selectorFunction(a,b)}else{if(a.length!==undefined){c=a}else{throw"Invalid selector"}}return(d===true)?new Ext.CompositeElement(c):new Ext.CompositeElementLite(c)};Ext.select=Ext.Element.select;Ext.UpdateManager=Ext.Updater=Ext.extend(Ext.util.Observable,function(){var b="beforeupdate",d="update",c="failure";function a(h){var i=this;i.transaction=null;if(h.argument.form&&h.argument.reset){try{h.argument.form.reset()}catch(k){}}if(i.loadScripts){i.renderer.render(i.el,h,i,g.createDelegate(i,[h]))}else{i.renderer.render(i.el,h,i);g.call(i,h)}}function g(h,i,k){this.fireEvent(i||d,this.el,h);if(Ext.isFunction(h.argument.callback)){h.argument.callback.call(h.argument.scope,this.el,Ext.isEmpty(k)?true:false,h,h.argument.options)}}function e(h){g.call(this,h,c,!!(this.transaction=null))}return{constructor:function(i,h){var k=this;i=Ext.get(i);if(!h&&i.updateManager){return i.updateManager}k.el=i;k.defaultUrl=null;k.addEvents(b,d,c);Ext.apply(k,Ext.Updater.defaults);k.transaction=null;k.refreshDelegate=k.refresh.createDelegate(k);k.updateDelegate=k.update.createDelegate(k);k.formUpdateDelegate=(k.formUpdate||function(){}).createDelegate(k);k.renderer=k.renderer||k.getDefaultRenderer();Ext.Updater.superclass.constructor.call(k)},setRenderer:function(h){this.renderer=h},getRenderer:function(){return this.renderer},getDefaultRenderer:function(){return new Ext.Updater.BasicRenderer()},setDefaultUrl:function(h){this.defaultUrl=h},getEl:function(){return this.el},update:function(i,p,q,m){var l=this,h,k;if(l.fireEvent(b,l.el,i,p)!==false){if(Ext.isObject(i)){h=i;i=h.url;p=p||h.params;q=q||h.callback;m=m||h.discardUrl;k=h.scope;if(!Ext.isEmpty(h.nocache)){l.disableCaching=h.nocache}if(!Ext.isEmpty(h.text)){l.indicatorText='<div class="loading-indicator">'+h.text+"</div>"}if(!Ext.isEmpty(h.scripts)){l.loadScripts=h.scripts}if(!Ext.isEmpty(h.timeout)){l.timeout=h.timeout}}l.showLoading();if(!m){l.defaultUrl=i}if(Ext.isFunction(i)){i=i.call(l)}var n=Ext.apply({},{url:i,params:(Ext.isFunction(p)&&k)?p.createDelegate(k):p,success:a,failure:e,scope:l,callback:undefined,timeout:(l.timeout*1000),disableCaching:l.disableCaching,argument:{options:h,url:i,form:null,callback:q,scope:k||window,params:p}},h);l.transaction=Ext.Ajax.request(n)}},formUpdate:function(l,h,k,m){var i=this;if(i.fireEvent(b,i.el,l,h)!==false){if(Ext.isFunction(h)){h=h.call(i)}l=Ext.getDom(l);i.transaction=Ext.Ajax.request({form:l,url:h,success:a,failure:e,scope:i,timeout:(i.timeout*1000),argument:{url:h,form:l,callback:m,reset:k}});i.showLoading.defer(1,i)}},startAutoRefresh:function(i,k,m,n,h){var l=this;if(h){l.update(k||l.defaultUrl,m,n,true)}if(l.autoRefreshProcId){clearInterval(l.autoRefreshProcId)}l.autoRefreshProcId=setInterval(l.update.createDelegate(l,[k||l.defaultUrl,m,n,true]),i*1000)},stopAutoRefresh:function(){if(this.autoRefreshProcId){clearInterval(this.autoRefreshProcId);delete this.autoRefreshProcId}},isAutoRefreshing:function(){return !!this.autoRefreshProcId},showLoading:function(){if(this.showLoadIndicator){this.el.dom.innerHTML=this.indicatorText}},abort:function(){if(this.transaction){Ext.Ajax.abort(this.transaction)}},isUpdating:function(){return this.transaction?Ext.Ajax.isLoading(this.transaction):false},refresh:function(h){if(this.defaultUrl){this.update(this.defaultUrl,null,h,true)}}}}());Ext.Updater.defaults={timeout:30,disableCaching:false,showLoadIndicator:true,indicatorText:'<div class="loading-indicator">Loading...</div>',loadScripts:false,sslBlankUrl:Ext.SSL_SECURE_URL};Ext.Updater.updateElement=function(d,c,e,b){var a=Ext.get(d).getUpdater();Ext.apply(a,b);a.update(c,e,b?b.callback:null)};Ext.Updater.BasicRenderer=function(){};Ext.Updater.BasicRenderer.prototype={render:function(c,a,b,d){c.update(a.responseText,b.loadScripts,d)}};(function(){Date.useStrict=false;function b(d){var c=Array.prototype.slice.call(arguments,1);return d.replace(/\{(\d+)\}/g,function(e,g){return c[g]})}Date.formatCodeToRegex=function(d,c){var e=Date.parseCodes[d];if(e){e=typeof e=="function"?e():e;Date.parseCodes[d]=e}return e?Ext.applyIf({c:e.c?b(e.c,c||"{0}"):e.c},e):{g:0,c:null,s:Ext.escapeRe(d)}};var a=Date.formatCodeToRegex;Ext.apply(Date,{parseFunctions:{"M$":function(d,c){var e=new RegExp("\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/");var g=(d||"").match(e);return g?new Date(((g[1]||"")+g[2])*1):null}},parseRegexes:[],formatFunctions:{"M$":function(){return"\\/Date("+this.getTime()+")\\/"}},y2kYear:50,MILLI:"ms",SECOND:"s",MINUTE:"mi",HOUR:"h",DAY:"d",MONTH:"mo",YEAR:"y",defaults:{},dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNumbers:{Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},getShortMonthName:function(c){return Date.monthNames[c].substring(0,3)},getShortDayName:function(c){return Date.dayNames[c].substring(0,3)},getMonthNumber:function(c){return Date.monthNumbers[c.substring(0,1).toUpperCase()+c.substring(1,3).toLowerCase()]},formatCodes:{d:"String.leftPad(this.getDate(), 2, '0')",D:"Date.getShortDayName(this.getDay())",j:"this.getDate()",l:"Date.dayNames[this.getDay()]",N:"(this.getDay() ? this.getDay() : 7)",S:"this.getSuffix()",w:"this.getDay()",z:"this.getDayOfYear()",W:"String.leftPad(this.getWeekOfYear(), 2, '0')",F:"Date.monthNames[this.getMonth()]",m:"String.leftPad(this.getMonth() + 1, 2, '0')",M:"Date.getShortMonthName(this.getMonth())",n:"(this.getMonth() + 1)",t:"this.getDaysInMonth()",L:"(this.isLeapYear() ? 1 : 0)",o:"(this.getFullYear() + (this.getWeekOfYear() == 1 && this.getMonth() > 0 ? +1 : (this.getWeekOfYear() >= 52 && this.getMonth() < 11 ? -1 : 0)))",Y:"String.leftPad(this.getFullYear(), 4, '0')",y:"('' + this.getFullYear()).substring(2, 4)",a:"(this.getHours() < 12 ? 'am' : 'pm')",A:"(this.getHours() < 12 ? 'AM' : 'PM')",g:"((this.getHours() % 12) ? this.getHours() % 12 : 12)",G:"this.getHours()",h:"String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",H:"String.leftPad(this.getHours(), 2, '0')",i:"String.leftPad(this.getMinutes(), 2, '0')",s:"String.leftPad(this.getSeconds(), 2, '0')",u:"String.leftPad(this.getMilliseconds(), 3, '0')",O:"this.getGMTOffset()",P:"this.getGMTOffset(true)",T:"this.getTimezone()",Z:"(this.getTimezoneOffset() * -60)",c:function(){for(var m="Y-m-dTH:i:sP",h=[],g=0,d=m.length;g<d;++g){var k=m.charAt(g);h.push(k=="T"?"'T'":Date.getFormatCode(k))}return h.join(" + ")},U:"Math.round(this.getTime() / 1000)"},isValid:function(p,c,o,l,g,k,e){l=l||0;g=g||0;k=k||0;e=e||0;var n=new Date(p<100?100:p,c-1,o,l,g,k,e).add(Date.YEAR,p<100?p-100:0);return p==n.getFullYear()&&c==n.getMonth()+1&&o==n.getDate()&&l==n.getHours()&&g==n.getMinutes()&&k==n.getSeconds()&&e==n.getMilliseconds()},parseDate:function(d,g,c){var e=Date.parseFunctions;if(e[g]==null){Date.createParser(g)}return e[g](d,Ext.isDefined(c)?c:Date.useStrict)},getFormatCode:function(d){var c=Date.formatCodes[d];if(c){c=typeof c=="function"?c():c;Date.formatCodes[d]=c}return c||("'"+String.escape(d)+"'")},createFormat:function(h){var g=[],c=false,e="";for(var d=0;d<h.length;++d){e=h.charAt(d);if(!c&&e=="\\"){c=true}else{if(c){c=false;g.push("'"+String.escape(e)+"'")}else{g.push(Date.getFormatCode(e))}}}Date.formatFunctions[h]=new Function("return "+g.join("+"))},createParser:function(){var c=["var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,","def = Date.defaults,","results = String(input).match(Date.parseRegexes[{0}]);","if(results){","{1}","if(u != null){","v = new Date(u * 1000);","}else{","dt = (new Date()).clearTime();","y = Ext.num(y, Ext.num(def.y, dt.getFullYear()));","m = Ext.num(m, Ext.num(def.m - 1, dt.getMonth()));","d = Ext.num(d, Ext.num(def.d, dt.getDate()));","h = Ext.num(h, Ext.num(def.h, dt.getHours()));","i = Ext.num(i, Ext.num(def.i, dt.getMinutes()));","s = Ext.num(s, Ext.num(def.s, dt.getSeconds()));","ms = Ext.num(ms, Ext.num(def.ms, dt.getMilliseconds()));","if(z >= 0 && y >= 0){","v = new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0);","v = !strict? v : (strict === true && (z <= 364 || (v.isLeapYear() && z <= 365))? v.add(Date.DAY, z) : null);","}else if(strict === true && !Date.isValid(y, m + 1, d, h, i, s, ms)){","v = null;","}else{","v = new Date(y < 100 ? 100 : y, m, d, h, i, s, ms).add(Date.YEAR, y < 100 ? y - 100 : 0);","}","}","}","if(v){","if(zz != null){","v = v.add(Date.SECOND, -v.getTimezoneOffset() * 60 - zz);","}else if(o){","v = v.add(Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));","}","}","return v;"].join("\n");return function(n){var e=Date.parseRegexes.length,p=1,g=[],m=[],l=false,d="",k=0,h,o;for(;k<n.length;++k){d=n.charAt(k);if(!l&&d=="\\"){l=true}else{if(l){l=false;m.push(String.escape(d))}else{h=a(d,p);p+=h.g;m.push(h.s);if(h.g&&h.c){if(h.calcLast){o=h.c}else{g.push(h.c)}}}}}if(o){g.push(o)}Date.parseRegexes[e]=new RegExp("^"+m.join("")+"$","i");Date.parseFunctions[n]=new Function("input","strict",b(c,e,g.join("")))}}(),parseCodes:{d:{g:1,c:"d = parseInt(results[{0}], 10);\n",s:"(\\d{2})"},j:{g:1,c:"d = parseInt(results[{0}], 10);\n",s:"(\\d{1,2})"},D:function(){for(var c=[],d=0;d<7;c.push(Date.getShortDayName(d)),++d){}return{g:0,c:null,s:"(?:"+c.join("|")+")"}},l:function(){return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"}},N:{g:0,c:null,s:"[1-7]"},S:{g:0,c:null,s:"(?:st|nd|rd|th)"},w:{g:0,c:null,s:"[0-6]"},z:{g:1,c:"z = parseInt(results[{0}], 10);\n",s:"(\\d{1,3})"},W:{g:0,c:null,s:"(?:\\d{2})"},F:function(){return{g:1,c:"m = parseInt(Date.getMonthNumber(results[{0}]), 10);\n",s:"("+Date.monthNames.join("|")+")"}},M:function(){for(var c=[],d=0;d<12;c.push(Date.getShortMonthName(d)),++d){}return Ext.applyIf({s:"("+c.join("|")+")"},a("F"))},m:{g:1,c:"m = parseInt(results[{0}], 10) - 1;\n",s:"(\\d{2})"},n:{g:1,c:"m = parseInt(results[{0}], 10) - 1;\n",s:"(\\d{1,2})"},t:{g:0,c:null,s:"(?:\\d{2})"},L:{g:0,c:null,s:"(?:1|0)"},o:function(){return a("Y")},Y:{g:1,c:"y = parseInt(results[{0}], 10);\n",s:"(\\d{4})"},y:{g:1,c:"var ty = parseInt(results[{0}], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"},a:function(){return a("A")},A:{calcLast:true,g:1,c:"if (/(am)/i.test(results[{0}])) {\nif (!h || h == 12) { h = 0; }\n} else { if (!h || h < 12) { h = (h || 0) + 12; }}",s:"(AM|PM|am|pm)"},g:function(){return a("G")},G:{g:1,c:"h = parseInt(results[{0}], 10);\n",s:"(\\d{1,2})"},h:function(){return a("H")},H:{g:1,c:"h = parseInt(results[{0}], 10);\n",s:"(\\d{2})"},i:{g:1,c:"i = parseInt(results[{0}], 10);\n",s:"(\\d{2})"},s:{g:1,c:"s = parseInt(results[{0}], 10);\n",s:"(\\d{2})"},u:{g:1,c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",s:"(\\d+)"},O:{g:1,c:["o = results[{0}];","var sn = o.substring(0,1),","hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),","mn = o.substring(3,5) % 60;","o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n"].join("\n"),s:"([+-]\\d{4})"},P:{g:1,c:["o = results[{0}];","var sn = o.substring(0,1),","hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),","mn = o.substring(4,6) % 60;","o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + String.leftPad(hr, 2, '0') + String.leftPad(mn, 2, '0')) : null;\n"].join("\n"),s:"([+-]\\d{2}:\\d{2})"},T:{g:0,c:null,s:"[A-Z]{1,4}"},Z:{g:1,c:"zz = results[{0}] * 1;\nzz = (-43200 <= zz && zz <= 50400)? zz : null;\n",s:"([+-]?\\d{1,5})"},c:function(){var e=[],c=[a("Y",1),a("m",2),a("d",3),a("h",4),a("i",5),a("s",6),{c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"},{c:["if(results[8]) {","if(results[8] == 'Z'){","zz = 0;","}else if (results[8].indexOf(':') > -1){",a("P",8).c,"}else{",a("O",8).c,"}","}"].join("\n")}];for(var g=0,d=c.length;g<d;++g){e.push(c[g].c)}return{g:1,c:e.join(""),s:[c[0].s,"(?:","-",c[1].s,"(?:","-",c[2].s,"(?:","(?:T| )?",c[3].s,":",c[4].s,"(?::",c[5].s,")?","(?:(?:\\.|,)(\\d+))?","(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?",")?",")?",")?"].join("")}},U:{g:1,c:"u = parseInt(results[{0}], 10);\n",s:"(-?\\d+)"}}})}());Ext.apply(Date.prototype,{dateFormat:function(a){if(Date.formatFunctions[a]==null){Date.createFormat(a)}return Date.formatFunctions[a].call(this)},getTimezone:function(){return this.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/,"$1$2").replace(/[^A-Z]/g,"")},getGMTOffset:function(a){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+(a?":":"")+String.leftPad(Math.abs(this.getTimezoneOffset()%60),2,"0")},getDayOfYear:function(){var b=0,e=this.clone(),a=this.getMonth(),c;for(c=0,e.setDate(1),e.setMonth(0);c<a;e.setMonth(++c)){b+=e.getDaysInMonth()}return b+this.getDate()-1},getWeekOfYear:function(){var a=86400000,b=7*a;return function(){var d=Date.UTC(this.getFullYear(),this.getMonth(),this.getDate()+3)/a,c=Math.floor(d/7),e=new Date(c*b).getUTCFullYear();return c-Math.floor(Date.UTC(e,0,7)/b)+1}}(),isLeapYear:function(){var a=this.getFullYear();return !!((a&3)==0&&(a%100||(a%400==0&&a)))},getFirstDayOfMonth:function(){var a=(this.getDay()-(this.getDate()-1))%7;return(a<0)?(a+7):a},getLastDayOfMonth:function(){return this.getLastDateOfMonth().getDay()},getFirstDateOfMonth:function(){return new Date(this.getFullYear(),this.getMonth(),1)},getLastDateOfMonth:function(){return new Date(this.getFullYear(),this.getMonth(),this.getDaysInMonth())},getDaysInMonth:function(){var a=[31,28,31,30,31,30,31,31,30,31,30,31];return function(){var b=this.getMonth();return b==1&&this.isLeapYear()?29:a[b]}}(),getSuffix:function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},clone:function(){return new Date(this.getTime())},isDST:function(){return new Date(this.getFullYear(),0,1).getTimezoneOffset()!=this.getTimezoneOffset()},clearTime:function(g){if(g){return this.clone().clearTime()}var b=this.getDate();this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);if(this.getDate()!=b){for(var a=1,e=this.add(Date.HOUR,a);e.getDate()!=b;a++,e=this.add(Date.HOUR,a)){}this.setDate(b);this.setHours(e.getHours())}return this},add:function(b,c){var e=this.clone();if(!b||c===0){return e}switch(b.toLowerCase()){case Date.MILLI:e.setMilliseconds(this.getMilliseconds()+c);break;case Date.SECOND:e.setSeconds(this.getSeconds()+c);break;case Date.MINUTE:e.setMinutes(this.getMinutes()+c);break;case Date.HOUR:e.setHours(this.getHours()+c);break;case Date.DAY:e.setDate(this.getDate()+c);break;case Date.MONTH:var a=this.getDate();if(a>28){a=Math.min(a,this.getFirstDateOfMonth().add("mo",c).getLastDateOfMonth().getDate())}e.setDate(a);e.setMonth(this.getMonth()+c);break;case Date.YEAR:e.setFullYear(this.getFullYear()+c);break}return e},between:function(c,a){var b=this.getTime();return c.getTime()<=b&&b<=a.getTime()}});Date.prototype.format=Date.prototype.dateFormat;if(Ext.isSafari&&(navigator.userAgent.match(/WebKit\/(\d+)/)[1]||NaN)<420){Ext.apply(Date.prototype,{_xMonth:Date.prototype.setMonth,_xDate:Date.prototype.setDate,setMonth:function(a){if(a<=-1){var d=Math.ceil(-a),c=Math.ceil(d/12),b=(d%12)?12-d%12:0;this.setFullYear(this.getFullYear()-c);return this._xMonth(b)}else{return this._xMonth(a)}},setDate:function(a){return this.setTime(this.getTime()-(this.getDate()-a)*86400000)}})}Ext.util.MixedCollection=function(b,a){this.items=[];this.map={};this.keys=[];this.length=0;this.addEvents("clear","add","replace","remove","sort");this.allowFunctions=b===true;if(a){this.getKey=a}Ext.util.MixedCollection.superclass.constructor.call(this)};Ext.extend(Ext.util.MixedCollection,Ext.util.Observable,{allowFunctions:false,add:function(b,c){if(arguments.length==1){c=arguments[0];b=this.getKey(c)}if(typeof b!="undefined"&&b!==null){var a=this.map[b];if(typeof a!="undefined"){return this.replace(b,c)}this.map[b]=c}this.length++;this.items.push(c);this.keys.push(b);this.fireEvent("add",this.length-1,c,b);return c},getKey:function(a){return a.id},replace:function(c,d){if(arguments.length==1){d=arguments[0];c=this.getKey(d)}var a=this.map[c];if(typeof c=="undefined"||c===null||typeof a=="undefined"){return this.add(c,d)}var b=this.indexOfKey(c);this.items[b]=d;this.map[c]=d;this.fireEvent("replace",c,a,d);return d},addAll:function(e){if(arguments.length>1||Ext.isArray(e)){var b=arguments.length>1?arguments:e;for(var d=0,a=b.length;d<a;d++){this.add(b[d])}}else{for(var c in e){if(this.allowFunctions||typeof e[c]!="function"){this.add(c,e[c])}}}},each:function(e,d){var b=[].concat(this.items);for(var c=0,a=b.length;c<a;c++){if(e.call(d||b[c],b[c],c,a)===false){break}}},eachKey:function(d,c){for(var b=0,a=this.keys.length;b<a;b++){d.call(c||window,this.keys[b],this.items[b],b,a)}},find:function(d,c){for(var b=0,a=this.items.length;b<a;b++){if(d.call(c||window,this.items[b],this.keys[b])){return this.items[b]}}return null},insert:function(a,b,c){if(arguments.length==2){c=arguments[1];b=this.getKey(c)}if(this.containsKey(b)){this.suspendEvents();this.removeKey(b);this.resumeEvents()}if(a>=this.length){return this.add(b,c)}this.length++;this.items.splice(a,0,c);if(typeof b!="undefined"&&b!==null){this.map[b]=c}this.keys.splice(a,0,b);this.fireEvent("add",a,c,b);return c},remove:function(a){return this.removeAt(this.indexOf(a))},removeAt:function(a){if(a<this.length&&a>=0){this.length--;var c=this.items[a];this.items.splice(a,1);var b=this.keys[a];if(typeof b!="undefined"){delete this.map[b]}this.keys.splice(a,1);this.fireEvent("remove",c,b);return c}return false},removeKey:function(a){return this.removeAt(this.indexOfKey(a))},getCount:function(){return this.length},indexOf:function(a){return this.items.indexOf(a)},indexOfKey:function(a){return this.keys.indexOf(a)},item:function(b){var a=this.map[b],c=a!==undefined?a:(typeof b=="number")?this.items[b]:undefined;return typeof c!="function"||this.allowFunctions?c:null},itemAt:function(a){return this.items[a]},key:function(a){return this.map[a]},contains:function(a){return this.indexOf(a)!=-1},containsKey:function(a){return typeof this.map[a]!="undefined"},clear:function(){this.length=0;this.items=[];this.keys=[];this.map={};this.fireEvent("clear")},first:function(){return this.items[0]},last:function(){return this.items[this.length-1]},_sort:function(l,a,k){var d,e,b=String(a).toUpperCase()=="DESC"?-1:1,h=[],m=this.keys,g=this.items;k=k||function(i,c){return i-c};for(d=0,e=g.length;d<e;d++){h[h.length]={key:m[d],value:g[d],index:d}}h.sort(function(i,c){var n=k(i[l],c[l])*b;if(n===0){n=(i.index<c.index?-1:1)}return n});for(d=0,e=h.length;d<e;d++){g[d]=h[d].value;m[d]=h[d].key}this.fireEvent("sort",this)},sort:function(a,b){this._sort("value",a,b)},reorder:function(d){this.suspendEvents();var b=this.items,c=0,g=b.length,a=[],e=[],h;for(h in d){a[d[h]]=b[h]}for(c=0;c<g;c++){if(d[c]==undefined){e.push(b[c])}}for(c=0;c<g;c++){if(a[c]==undefined){a[c]=e.shift()}}this.clear();this.addAll(a);this.resumeEvents();this.fireEvent("sort",this)},keySort:function(a,b){this._sort("key",a,b||function(d,c){var g=String(d).toUpperCase(),e=String(c).toUpperCase();return g>e?1:(g<e?-1:0)})},getRange:function(e,a){var b=this.items;if(b.length<1){return[]}e=e||0;a=Math.min(typeof a=="undefined"?this.length-1:a,this.length-1);var c,d=[];if(e<=a){for(c=e;c<=a;c++){d[d.length]=b[c]}}else{for(c=e;c>=a;c--){d[d.length]=b[c]}}return d},filter:function(c,b,d,a){if(Ext.isEmpty(b,false)){return this.clone()}b=this.createValueMatcher(b,d,a);return this.filterBy(function(e){return e&&b.test(e[c])})},filterBy:function(g,e){var h=new Ext.util.MixedCollection();h.getKey=this.getKey;var b=this.keys,d=this.items;for(var c=0,a=d.length;c<a;c++){if(g.call(e||this,d[c],b[c])){h.add(b[c],d[c])}}return h},findIndex:function(c,b,e,d,a){if(Ext.isEmpty(b,false)){return -1}b=this.createValueMatcher(b,d,a);return this.findIndexBy(function(g){return g&&b.test(g[c])},null,e)},findIndexBy:function(g,e,h){var b=this.keys,d=this.items;for(var c=(h||0),a=d.length;c<a;c++){if(g.call(e||this,d[c],b[c])){return c}}return -1},createValueMatcher:function(c,e,a,b){if(!c.exec){var d=Ext.escapeRe;c=String(c);if(e===true){c=d(c)}else{c="^"+d(c);if(b===true){c+="$"}}c=new RegExp(c,a?"":"i")}return c},clone:function(){var e=new Ext.util.MixedCollection();var b=this.keys,d=this.items;for(var c=0,a=d.length;c<a;c++){e.add(b[c],d[c])}e.getKey=this.getKey;return e}});Ext.util.MixedCollection.prototype.get=Ext.util.MixedCollection.prototype.item;Ext.AbstractManager=Ext.extend(Object,{typeName:"type",constructor:function(a){Ext.apply(this,a||{});this.all=new Ext.util.MixedCollection();this.types={}},get:function(a){return this.all.get(a)},register:function(a){this.all.add(a)},unregister:function(a){this.all.remove(a)},registerType:function(b,a){this.types[b]=a;a[this.typeName]=b},isRegistered:function(a){return this.types[a]!==undefined},create:function(a,d){var b=a[this.typeName]||a.type||d,c=this.types[b];if(c==undefined){throw new Error(String.format("The '{0}' type has not been registered with this manager",b))}return new c(a)},onAvailable:function(d,c,b){var a=this.all;a.on("add",function(e,g){if(g.id==d){c.call(b||g,g);a.un("add",c,b)}})}});Ext.util.Format=function(){var trimRe=/^\s+|\s+$/g,stripTagsRE=/<\/?[^>]+>/gi,stripScriptsRe=/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,nl2brRe=/\r?\n/g;return{ellipsis:function(value,len,word){if(value&&value.length>len){if(word){var vs=value.substr(0,len-2),index=Math.max(vs.lastIndexOf(" "),vs.lastIndexOf("."),vs.lastIndexOf("!"),vs.lastIndexOf("?"));if(index==-1||index<(len-15)){return value.substr(0,len-3)+"..."}else{return vs.substr(0,index)+"..."}}else{return value.substr(0,len-3)+"..."}}return value},undef:function(value){return value!==undefined?value:""},defaultValue:function(value,defaultValue){return value!==undefined&&value!==""?value:defaultValue},htmlEncode:function(value){return !value?value:String(value).replace(/&/g,"&").replace(/>/g,">").replace(/</g,"<").replace(/"/g,""")},htmlDecode:function(value){return !value?value:String(value).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&")},trim:function(value){return String(value).replace(trimRe,"")},substr:function(value,start,length){return String(value).substr(start,length)},lowercase:function(value){return String(value).toLowerCase()},uppercase:function(value){return String(value).toUpperCase()},capitalize:function(value){return !value?value:value.charAt(0).toUpperCase()+value.substr(1).toLowerCase()},call:function(value,fn){if(arguments.length>2){var args=Array.prototype.slice.call(arguments,2);args.unshift(value);return eval(fn).apply(window,args)}else{return eval(fn).call(window,value)}},usMoney:function(v){v=(Math.round((v-0)*100))/100;v=(v==Math.floor(v))?v+".00":((v*10==Math.floor(v*10))?v+"0":v);v=String(v);var ps=v.split("."),whole=ps[0],sub=ps[1]?"."+ps[1]:".00",r=/(\d+)(\d{3})/;while(r.test(whole)){whole=whole.replace(r,"$1,$2")}v=whole+sub;if(v.charAt(0)=="-"){return"-$"+v.substr(1)}return"$"+v},date:function(v,format){if(!v){return""}if(!Ext.isDate(v)){v=new Date(Date.parse(v))}return v.dateFormat(format||"m/d/Y")},dateRenderer:function(format){return function(v){return Ext.util.Format.date(v,format)}},stripTags:function(v){return !v?v:String(v).replace(stripTagsRE,"")},stripScripts:function(v){return !v?v:String(v).replace(stripScriptsRe,"")},fileSize:function(size){if(size<1024){return size+" bytes"}else{if(size<1048576){return(Math.round(((size*10)/1024))/10)+" KB"}else{return(Math.round(((size*10)/1048576))/10)+" MB"}}},math:function(){var fns={};return function(v,a){if(!fns[a]){fns[a]=new Function("v","return v "+a+";")}return fns[a](v)}}(),round:function(value,precision){var result=Number(value);if(typeof precision=="number"){precision=Math.pow(10,precision);result=Math.round(value*precision)/precision}return result},number:function(v,format){if(!format){return v}v=Ext.num(v,NaN);if(isNaN(v)){return""}var comma=",",dec=".",i18n=false,neg=v<0;v=Math.abs(v);if(format.substr(format.length-2)=="/i"){format=format.substr(0,format.length-2);i18n=true;comma=".";dec=","}var hasComma=format.indexOf(comma)!=-1,psplit=(i18n?format.replace(/[^\d\,]/g,""):format.replace(/[^\d\.]/g,"")).split(dec);if(1<psplit.length){v=v.toFixed(psplit[1].length)}else{if(2<psplit.length){throw ("NumberFormatException: invalid format, formats should have no more than 1 period: "+format)}else{v=v.toFixed(0)}}var fnum=v.toString();psplit=fnum.split(".");if(hasComma){var cnum=psplit[0],parr=[],j=cnum.length,m=Math.floor(j/3),n=cnum.length%3||3,i;for(i=0;i<j;i+=n){if(i!=0){n=3}parr[parr.length]=cnum.substr(i,n);m-=1}fnum=parr.join(comma);if(psplit[1]){fnum+=dec+psplit[1]}}else{if(psplit[1]){fnum=psplit[0]+dec+psplit[1]}}return(neg?"-":"")+format.replace(/[\d,?\.?]+/,fnum)},numberRenderer:function(format){return function(v){return Ext.util.Format.number(v,format)}},plural:function(v,s,p){return v+" "+(v==1?s:(p?p:s+"s"))},nl2br:function(v){return Ext.isEmpty(v)?"":v.replace(nl2brRe,"<br/>")}}}();Ext.XTemplate=function(){Ext.XTemplate.superclass.constructor.apply(this,arguments);var z=this,k=z.html,r=/<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,d=/^<tpl\b[^>]*?for="(.*?)"/,w=/^<tpl\b[^>]*?if="(.*?)"/,y=/^<tpl\b[^>]*?exec="(.*?)"/,t,q=0,l=[],p="values",x="parent",n="xindex",o="xcount",e="return ",c="with(values){ ";k=["<tpl>",k,"</tpl>"].join("");while((t=k.match(r))){var b=t[0].match(d),a=t[0].match(w),B=t[0].match(y),g=null,h=null,u=null,A=b&&b[1]?b[1]:"";if(a){g=a&&a[1]?a[1]:null;if(g){h=new Function(p,x,n,o,c+e+(Ext.util.Format.htmlDecode(g))+"; }")}}if(B){g=B&&B[1]?B[1]:null;if(g){u=new Function(p,x,n,o,c+(Ext.util.Format.htmlDecode(g))+"; }")}}if(A){switch(A){case".":A=new Function(p,x,c+e+p+"; }");break;case"..":A=new Function(p,x,c+e+x+"; }");break;default:A=new Function(p,x,c+e+A+"; }")}}l.push({id:q,target:A,exec:u,test:h,body:t[1]||""});k=k.replace(t[0],"{xtpl"+q+"}");++q}for(var v=l.length-1;v>=0;--v){z.compileTpl(l[v])}z.master=l[l.length-1];z.tpls=l};Ext.extend(Ext.XTemplate,Ext.Template,{re:/\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,codeRe:/\{\[((?:\\\]|.|\n)*?)\]\}/g,applySubTemplate:function(a,l,k,d,c){var h=this,g,n=h.tpls[a],m,b=[];if((n.test&&!n.test.call(h,l,k,d,c))||(n.exec&&n.exec.call(h,l,k,d,c))){return""}m=n.target?n.target.call(h,l,k):l;g=m.length;k=n.target?l:k;if(n.target&&Ext.isArray(m)){for(var e=0,g=m.length;e<g;e++){b[b.length]=n.compiled.call(h,m[e],k,e+1,g)}return b.join("")}return n.compiled.call(h,m,k,d,c)},compileTpl:function(tpl){var fm=Ext.util.Format,useF=this.disableFormats!==true,sep=Ext.isGecko?"+":",",body;function fn(m,name,format,args,math){if(name.substr(0,4)=="xtpl"){return"'"+sep+"this.applySubTemplate("+name.substr(4)+", values, parent, xindex, xcount)"+sep+"'"}var v;if(name==="."){v="values"}else{if(name==="#"){v="xindex"}else{if(name.indexOf(".")!=-1){v=name}else{v="values['"+name+"']"}}}if(math){v="("+v+math+")"}if(format&&useF){args=args?","+args:"";if(format.substr(0,5)!="this."){format="fm."+format+"("}else{format='this.call("'+format.substr(5)+'", ';args=", values"}}else{args="";format="("+v+" === undefined ? '' : "}return"'"+sep+format+v+args+")"+sep+"'"}function codeFn(m,code){return"'"+sep+"("+code.replace(/\\'/g,"'")+")"+sep+"'"}if(Ext.isGecko){body="tpl.compiled = function(values, parent, xindex, xcount){ return '"+tpl.body.replace(/(\r\n|\n)/g,"\\n").replace(/'/g,"\\'").replace(this.re,fn).replace(this.codeRe,codeFn)+"';};"}else{body=["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];body.push(tpl.body.replace(/(\r\n|\n)/g,"\\n").replace(/'/g,"\\'").replace(this.re,fn).replace(this.codeRe,codeFn));body.push("'].join('');};");body=body.join("")}eval(body);return this},applyTemplate:function(a){return this.master.compiled.call(this,a,{},1,1)},compile:function(){return this}});Ext.XTemplate.prototype.apply=Ext.XTemplate.prototype.applyTemplate;Ext.XTemplate.from=function(a){a=Ext.getDom(a);return new Ext.XTemplate(a.value||a.innerHTML)};Ext.util.CSS=function(){var d=null;var c=document;var b=/(-[a-z])/gi;var a=function(e,g){return g.charAt(1).toUpperCase()};return{createStyleSheet:function(i,m){var h;var g=c.getElementsByTagName("head")[0];var l=c.createElement("style");l.setAttribute("type","text/css");if(m){l.setAttribute("id",m)}if(Ext.isIE){g.appendChild(l);h=l.styleSheet;h.cssText=i}else{try{l.appendChild(c.createTextNode(i))}catch(k){l.cssText=i}g.appendChild(l);h=l.styleSheet?l.styleSheet:(l.sheet||c.styleSheets[c.styleSheets.length-1])}this.cacheStyleSheet(h);return h},removeStyleSheet:function(g){var e=c.getElementById(g);if(e){e.parentNode.removeChild(e)}},swapStyleSheet:function(h,e){this.removeStyleSheet(h);var g=c.createElement("link");g.setAttribute("rel","stylesheet");g.setAttribute("type","text/css");g.setAttribute("id",h);g.setAttribute("href",e);c.getElementsByTagName("head")[0].appendChild(g)},refreshCache:function(){return this.getRules(true)},cacheStyleSheet:function(h){if(!d){d={}}try{var k=h.cssRules||h.rules;for(var g=k.length-1;g>=0;--g){d[k[g].selectorText.toLowerCase()]=k[g]}}catch(i){}},getRules:function(h){if(d===null||h){d={};var l=c.styleSheets;for(var k=0,g=l.length;k<g;k++){try{this.cacheStyleSheet(l[k])}catch(m){}}}return d},getRule:function(e,h){var g=this.getRules(h);if(!Ext.isArray(e)){return g[e.toLowerCase()]}for(var k=0;k<e.length;k++){if(g[e[k]]){return g[e[k].toLowerCase()]}}return null},updateRule:function(e,k,h){if(!Ext.isArray(e)){var l=this.getRule(e);if(l){l.style[k.replace(b,a)]=h;return true}}else{for(var g=0;g<e.length;g++){if(this.updateRule(e[g],k,h)){return true}}}return false}}}();Ext.util.ClickRepeater=Ext.extend(Ext.util.Observable,{constructor:function(b,a){this.el=Ext.get(b);this.el.unselectable();Ext.apply(this,a);this.addEvents("mousedown","click","mouseup");if(!this.disabled){this.disabled=true;this.enable()}if(this.handler){this.on("click",this.handler,this.scope||this)}Ext.util.ClickRepeater.superclass.constructor.call(this)},interval:20,delay:250,preventDefault:true,stopDefault:false,timer:0,enable:function(){if(this.disabled){this.el.on("mousedown",this.handleMouseDown,this);if(Ext.isIE){this.el.on("dblclick",this.handleDblClick,this)}if(this.preventDefault||this.stopDefault){this.el.on("click",this.eventOptions,this)}}this.disabled=false},disable:function(a){if(a||!this.disabled){clearTimeout(this.timer);if(this.pressClass){this.el.removeClass(this.pressClass)}Ext.getDoc().un("mouseup",this.handleMouseUp,this);this.el.removeAllListeners()}this.disabled=true},setDisabled:function(a){this[a?"disable":"enable"]()},eventOptions:function(a){if(this.preventDefault){a.preventDefault()}if(this.stopDefault){a.stopEvent()}},destroy:function(){this.disable(true);Ext.destroy(this.el);this.purgeListeners()},handleDblClick:function(a){clearTimeout(this.timer);this.el.blur();this.fireEvent("mousedown",this,a);this.fireEvent("click",this,a)},handleMouseDown:function(a){clearTimeout(this.timer);this.el.blur();if(this.pressClass){this.el.addClass(this.pressClass)}this.mousedownTime=new Date();Ext.getDoc().on("mouseup",this.handleMouseUp,this);this.el.on("mouseout",this.handleMouseOut,this);this.fireEvent("mousedown",this,a);this.fireEvent("click",this,a);if(this.accelerate){this.delay=400}this.timer=this.click.defer(this.delay||this.interval,this,[a])},click:function(a){this.fireEvent("click",this,a);this.timer=this.click.defer(this.accelerate?this.easeOutExpo(this.mousedownTime.getElapsed(),400,-390,12000):this.interval,this,[a])},easeOutExpo:function(e,a,h,g){return(e==g)?a+h:h*(-Math.pow(2,-10*e/g)+1)+a},handleMouseOut:function(){clearTimeout(this.timer);if(this.pressClass){this.el.removeClass(this.pressClass)}this.el.on("mouseover",this.handleMouseReturn,this)},handleMouseReturn:function(){this.el.un("mouseover",this.handleMouseReturn,this);if(this.pressClass){this.el.addClass(this.pressClass)}this.click()},handleMouseUp:function(a){clearTimeout(this.timer);this.el.un("mouseover",this.handleMouseReturn,this);this.el.un("mouseout",this.handleMouseOut,this);Ext.getDoc().un("mouseup",this.handleMouseUp,this);this.el.removeClass(this.pressClass);this.fireEvent("mouseup",this,a)}});Ext.KeyNav=function(b,a){this.el=Ext.get(b);Ext.apply(this,a);if(!this.disabled){this.disabled=true;this.enable()}};Ext.KeyNav.prototype={disabled:false,defaultEventAction:"stopEvent",forceKeyDown:false,relay:function(c){var a=c.getKey(),b=this.keyToHandler[a];if(b&&this[b]){if(this.doRelay(c,this[b],b)!==true){c[this.defaultEventAction]()}}},doRelay:function(c,b,a){return b.call(this.scope||this,c,a)},enter:false,left:false,right:false,up:false,down:false,tab:false,esc:false,pageUp:false,pageDown:false,del:false,home:false,end:false,keyToHandler:{37:"left",39:"right",38:"up",40:"down",33:"pageUp",34:"pageDown",46:"del",36:"home",35:"end",13:"enter",27:"esc",9:"tab"},stopKeyUp:function(b){var a=b.getKey();if(a>=37&&a<=40){b.stopEvent()}},destroy:function(){this.disable()},enable:function(){if(this.disabled){if(Ext.isSafari2){this.el.on("keyup",this.stopKeyUp,this)}this.el.on(this.isKeydown()?"keydown":"keypress",this.relay,this);this.disabled=false}},disable:function(){if(!this.disabled){if(Ext.isSafari2){this.el.un("keyup",this.stopKeyUp,this)}this.el.un(this.isKeydown()?"keydown":"keypress",this.relay,this);this.disabled=true}},setDisabled:function(a){this[a?"disable":"enable"]()},isKeydown:function(){return this.forceKeyDown||Ext.EventManager.useKeydown}};Ext.KeyMap=function(c,b,a){this.el=Ext.get(c);this.eventName=a||"keydown";this.bindings=[];if(b){this.addBinding(b)}this.enable()};Ext.KeyMap.prototype={stopEvent:false,addBinding:function(b){if(Ext.isArray(b)){Ext.each(b,function(m){this.addBinding(m)},this);return}var k=b.key,g=b.fn||b.handler,l=b.scope;if(b.stopEvent){this.stopEvent=b.stopEvent}if(typeof k=="string"){var h=[];var e=k.toUpperCase();for(var c=0,d=e.length;c<d;c++){h.push(e.charCodeAt(c))}k=h}var a=Ext.isArray(k);var i=function(p){if(this.checkModifiers(b,p)){var n=p.getKey();if(a){for(var o=0,m=k.length;o<m;o++){if(k[o]==n){if(this.stopEvent){p.stopEvent()}g.call(l||window,n,p);return}}}else{if(n==k){if(this.stopEvent){p.stopEvent()}g.call(l||window,n,p)}}}};this.bindings.push(i)},checkModifiers:function(b,h){var k,d,g=["shift","ctrl","alt"];for(var c=0,a=g.length;c<a;++c){d=g[c];k=b[d];if(!(k===undefined||(k===h[d+"Key"]))){return false}}return true},on:function(b,d,c){var h,a,e,g;if(typeof b=="object"&&!Ext.isArray(b)){h=b.key;a=b.shift;e=b.ctrl;g=b.alt}else{h=b}this.addBinding({key:h,shift:a,ctrl:e,alt:g,fn:d,scope:c})},handleKeyDown:function(g){if(this.enabled){var c=this.bindings;for(var d=0,a=c.length;d<a;d++){c[d].call(this,g)}}},isEnabled:function(){return this.enabled},enable:function(){if(!this.enabled){this.el.on(this.eventName,this.handleKeyDown,this);this.enabled=true}},disable:function(){if(this.enabled){this.el.removeListener(this.eventName,this.handleKeyDown,this);this.enabled=false}},setDisabled:function(a){this[a?"disable":"enable"]()}};Ext.util.TextMetrics=function(){var a;return{measure:function(b,c,d){if(!a){a=Ext.util.TextMetrics.Instance(b,d)}a.bind(b);a.setFixedWidth(d||"auto");return a.getSize(c)},createInstance:function(b,c){return Ext.util.TextMetrics.Instance(b,c)}}}();Ext.util.TextMetrics.Instance=function(b,d){var c=new Ext.Element(document.createElement("div"));document.body.appendChild(c.dom);c.position("absolute");c.setLeftTop(-1000,-1000);c.hide();if(d){c.setWidth(d)}var a={getSize:function(g){c.update(g);var e=c.getSize();c.update("");return e},bind:function(e){c.setStyle(Ext.fly(e).getStyles("font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"))},setFixedWidth:function(e){c.setWidth(e)},getWidth:function(e){c.dom.style.width="auto";return this.getSize(e).width},getHeight:function(e){return this.getSize(e).height}};a.bind(b);return a};Ext.Element.addMethods({getTextWidth:function(c,b,a){return(Ext.util.TextMetrics.measure(this.dom,Ext.value(c,this.dom.innerHTML,true)).width).constrain(b||0,a||1000000)}});Ext.util.Cookies={set:function(c,e){var a=arguments;var i=arguments.length;var b=(i>2)?a[2]:null;var h=(i>3)?a[3]:"/";var d=(i>4)?a[4]:null;var g=(i>5)?a[5]:false;document.cookie=c+"="+escape(e)+((b===null)?"":("; expires="+b.toGMTString()))+((h===null)?"":("; path="+h))+((d===null)?"":("; domain="+d))+((g===true)?"; secure":"")},get:function(d){var b=d+"=";var g=b.length;var a=document.cookie.length;var e=0;var c=0;while(e<a){c=e+g;if(document.cookie.substring(e,c)==b){return Ext.util.Cookies.getCookieVal(c)}e=document.cookie.indexOf(" ",e)+1;if(e===0){break}}return null},clear:function(a){if(Ext.util.Cookies.get(a)){document.cookie=a+"=; expires=Thu, 01-Jan-70 00:00:01 GMT"}},getCookieVal:function(b){var a=document.cookie.indexOf(";",b);if(a==-1){a=document.cookie.length}return unescape(document.cookie.substring(b,a))}};Ext.handleError=function(a){throw a};Ext.Error=function(a){this.message=(this.lang[a])?this.lang[a]:a};Ext.Error.prototype=new Error();Ext.apply(Ext.Error.prototype,{lang:{},name:"Ext.Error",getName:function(){return this.name},getMessage:function(){return this.message},toJson:function(){return Ext.encode(this)}});Ext.ComponentMgr=function(){var c=new Ext.util.MixedCollection();var b={};var a={};return{register:function(d){c.add(d)},unregister:function(d){c.remove(d)},get:function(d){return c.get(d)},onAvailable:function(g,e,d){c.on("add",function(h,i){if(i.id==g){e.call(d||i,i);c.un("add",e,d)}})},all:c,types:b,ptypes:a,isRegistered:function(d){return b[d]!==undefined},isPluginRegistered:function(d){return a[d]!==undefined},registerType:function(e,d){b[e]=d;d.xtype=e},create:function(d,e){return d.render?d:new b[d.xtype||e](d)},registerPlugin:function(e,d){a[e]=d;d.ptype=e},createPlugin:function(e,g){var d=a[e.ptype||g];if(d.init){return d}else{return new d(e)}}}}();Ext.reg=Ext.ComponentMgr.registerType;Ext.preg=Ext.ComponentMgr.registerPlugin;Ext.create=Ext.ComponentMgr.create;Ext.Component=function(b){b=b||{};if(b.initialConfig){if(b.isAction){this.baseAction=b}b=b.initialConfig}else{if(b.tagName||b.dom||Ext.isString(b)){b={applyTo:b,id:b.id||b}}}this.initialConfig=b;Ext.apply(this,b);this.addEvents("added","disable","enable","beforeshow","show","beforehide","hide","removed","beforerender","render","afterrender","beforedestroy","destroy","beforestaterestore","staterestore","beforestatesave","statesave");this.getId();Ext.ComponentMgr.register(this);Ext.Component.superclass.constructor.call(this);if(this.baseAction){this.baseAction.addComponent(this)}this.initComponent();if(this.plugins){if(Ext.isArray(this.plugins)){for(var c=0,a=this.plugins.length;c<a;c++){this.plugins[c]=this.initPlugin(this.plugins[c])}}else{this.plugins=this.initPlugin(this.plugins)}}if(this.stateful!==false){this.initState()}if(this.applyTo){this.applyToMarkup(this.applyTo);delete this.applyTo}else{if(this.renderTo){this.render(this.renderTo);delete this.renderTo}}};Ext.Component.AUTO_ID=1000;Ext.extend(Ext.Component,Ext.util.Observable,{disabled:false,hidden:false,autoEl:"div",disabledClass:"x-item-disabled",allowDomMove:true,autoShow:false,hideMode:"display",hideParent:false,rendered:false,tplWriteMode:"overwrite",bubbleEvents:[],ctype:"Ext.Component",actionMode:"el",getActionEl:function(){return this[this.actionMode]},initPlugin:function(a){if(a.ptype&&!Ext.isFunction(a.init)){a=Ext.ComponentMgr.createPlugin(a)}else{if(Ext.isString(a)){a=Ext.ComponentMgr.createPlugin({ptype:a})}}a.init(this);return a},initComponent:function(){if(this.listeners){this.on(this.listeners);delete this.listeners}this.enableBubble(this.bubbleEvents)},render:function(b,a){if(!this.rendered&&this.fireEvent("beforerender",this)!==false){if(!b&&this.el){this.el=Ext.get(this.el);b=this.el.dom.parentNode;this.allowDomMove=false}this.container=Ext.get(b);if(this.ctCls){this.container.addClass(this.ctCls)}this.rendered=true;if(a!==undefined){if(Ext.isNumber(a)){a=this.container.dom.childNodes[a]}else{a=Ext.getDom(a)}}this.onRender(this.container,a||null);if(this.autoShow){this.el.removeClass(["x-hidden","x-hide-"+this.hideMode])}if(this.cls){this.el.addClass(this.cls);delete this.cls}if(this.style){this.el.applyStyles(this.style);delete this.style}if(this.overCls){this.el.addClassOnOver(this.overCls)}this.fireEvent("render",this);var c=this.getContentTarget();if(this.html){c.update(Ext.DomHelper.markup(this.html));delete this.html}if(this.contentEl){var d=Ext.getDom(this.contentEl);Ext.fly(d).removeClass(["x-hidden","x-hide-display"]);c.appendChild(d)}if(this.tpl){if(!this.tpl.compile){this.tpl=new Ext.XTemplate(this.tpl)}if(this.data){this.tpl[this.tplWriteMode](c,this.data);delete this.data}}this.afterRender(this.container);if(this.hidden){this.doHide()}if(this.disabled){this.disable(true)}if(this.stateful!==false){this.initStateEvents()}this.fireEvent("afterrender",this)}return this},update:function(b,d,a){var c=this.getContentTarget();if(this.tpl&&typeof b!=="string"){this.tpl[this.tplWriteMode](c,b||{})}else{var e=Ext.isObject(b)?Ext.DomHelper.markup(b):b;c.update(e,d,a)}},onAdded:function(a,b){this.ownerCt=a;this.initRef();this.fireEvent("added",this,a,b)},onRemoved:function(){this.removeRef();this.fireEvent("removed",this,this.ownerCt);delete this.ownerCt},initRef:function(){if(this.ref&&!this.refOwner){var d=this.ref.split("/"),c=d.length,b=0,a=this;while(a&&b<c){a=a.ownerCt;++b}if(a){a[this.refName=d[--b]]=this;this.refOwner=a}}},removeRef:function(){if(this.refOwner&&this.refName){delete this.refOwner[this.refName];delete this.refOwner}},initState:function(){if(Ext.state.Manager){var b=this.getStateId();if(b){var a=Ext.state.Manager.get(b);if(a){if(this.fireEvent("beforestaterestore",this,a)!==false){this.applyState(Ext.apply({},a));this.fireEvent("staterestore",this,a)}}}}},getStateId:function(){return this.stateId||((/^(ext-comp-|ext-gen)/).test(String(this.id))?null:this.id)},initStateEvents:function(){if(this.stateEvents){for(var a=0,b;b=this.stateEvents[a];a++){this.on(b,this.saveState,this,{delay:100})}}},applyState:function(a){if(a){Ext.apply(this,a)}},getState:function(){return null},saveState:function(){if(Ext.state.Manager&&this.stateful!==false){var b=this.getStateId();if(b){var a=this.getState();if(this.fireEvent("beforestatesave",this,a)!==false){Ext.state.Manager.set(b,a);this.fireEvent("statesave",this,a)}}}},applyToMarkup:function(a){this.allowDomMove=false;this.el=Ext.get(a);this.render(this.el.dom.parentNode)},addClass:function(a){if(this.el){this.el.addClass(a)}else{this.cls=this.cls?this.cls+" "+a:a}return this},removeClass:function(a){if(this.el){this.el.removeClass(a)}else{if(this.cls){this.cls=this.cls.split(" ").remove(a).join(" ")}}return this},onRender:function(b,a){if(!this.el&&this.autoEl){if(Ext.isString(this.autoEl)){this.el=document.createElement(this.autoEl)}else{var c=document.createElement("div");Ext.DomHelper.overwrite(c,this.autoEl);this.el=c.firstChild}if(!this.el.id){this.el.id=this.getId()}}if(this.el){this.el=Ext.get(this.el);if(this.allowDomMove!==false){b.dom.insertBefore(this.el.dom,a);if(c){Ext.removeNode(c);c=null}}}},getAutoCreate:function(){var a=Ext.isObject(this.autoCreate)?this.autoCreate:Ext.apply({},this.defaultAutoCreate);if(this.id&&!a.id){a.id=this.id}return a},afterRender:Ext.emptyFn,destroy:function(){if(!this.isDestroyed){if(this.fireEvent("beforedestroy",this)!==false){this.destroying=true;this.beforeDestroy();if(this.ownerCt&&this.ownerCt.remove){this.ownerCt.remove(this,false)}if(this.rendered){this.el.remove();if(this.actionMode=="container"||this.removeMode=="container"){this.container.remove()}}if(this.focusTask&&this.focusTask.cancel){this.focusTask.cancel()}this.onDestroy();Ext.ComponentMgr.unregister(this);this.fireEvent("destroy",this);this.purgeListeners();this.destroying=false;this.isDestroyed=true}}},deleteMembers:function(){var b=arguments;for(var c=0,a=b.length;c<a;++c){delete this[b[c]]}},beforeDestroy:Ext.emptyFn,onDestroy:Ext.emptyFn,getEl:function(){return this.el},getContentTarget:function(){return this.el},getId:function(){return this.id||(this.id="ext-comp-"+(++Ext.Component.AUTO_ID))},getItemId:function(){return this.itemId||this.getId()},focus:function(b,a){if(a){this.focusTask=new Ext.util.DelayedTask(this.focus,this,[b,false]);this.focusTask.delay(Ext.isNumber(a)?a:10);return this}if(this.rendered&&!this.isDestroyed){this.el.focus();if(b===true){this.el.dom.select()}}return this},blur:function(){if(this.rendered){this.el.blur()}return this},disable:function(a){if(this.rendered){this.onDisable()}this.disabled=true;if(a!==true){this.fireEvent("disable",this)}return this},onDisable:function(){this.getActionEl().addClass(this.disabledClass);this.el.dom.disabled=true},enable:function(){if(this.rendered){this.onEnable()}this.disabled=false;this.fireEvent("enable",this);return this},onEnable:function(){this.getActionEl().removeClass(this.disabledClass);this.el.dom.disabled=false},setDisabled:function(a){return this[a?"disable":"enable"]()},show:function(){if(this.fireEvent("beforeshow",this)!==false){this.hidden=false;if(this.autoRender){this.render(Ext.isBoolean(this.autoRender)?Ext.getBody():this.autoRender)}if(this.rendered){this.onShow()}this.fireEvent("show",this)}return this},onShow:function(){this.getVisibilityEl().removeClass("x-hide-"+this.hideMode)},hide:function(){if(this.fireEvent("beforehide",this)!==false){this.doHide();this.fireEvent("hide",this)}return this},doHide:function(){this.hidden=true;if(this.rendered){this.onHide()}},onHide:function(){this.getVisibilityEl().addClass("x-hide-"+this.hideMode)},getVisibilityEl:function(){return this.hideParent?this.container:this.getActionEl()},setVisible:function(a){return this[a?"show":"hide"]()},isVisible:function(){return this.rendered&&this.getVisibilityEl().isVisible()},cloneConfig:function(b){b=b||{};var c=b.id||Ext.id();var a=Ext.applyIf(b,this.initialConfig);a.id=c;return new this.constructor(a)},getXType:function(){return this.constructor.xtype},isXType:function(b,a){if(Ext.isFunction(b)){b=b.xtype}else{if(Ext.isObject(b)){b=b.constructor.xtype}}return !a?("/"+this.getXTypes()+"/").indexOf("/"+b+"/")!=-1:this.constructor.xtype==b},getXTypes:function(){var a=this.constructor;if(!a.xtypes){var d=[],b=this;while(b&&b.constructor.xtype){d.unshift(b.constructor.xtype);b=b.constructor.superclass}a.xtypeChain=d;a.xtypes=d.join("/")}return a.xtypes},findParentBy:function(a){for(var b=this.ownerCt;(b!=null)&&!a(b,this);b=b.ownerCt){}return b||null},findParentByType:function(b,a){return this.findParentBy(function(d){return d.isXType(b,a)})},bubble:function(c,b,a){var d=this;while(d){if(c.apply(b||d,a||[d])===false){break}d=d.ownerCt}return this},getPositionEl:function(){return this.positionEl||this.el},purgeListeners:function(){Ext.Component.superclass.purgeListeners.call(this);if(this.mons){this.on("beforedestroy",this.clearMons,this,{single:true})}},clearMons:function(){Ext.each(this.mons,function(a){a.item.un(a.ename,a.fn,a.scope)},this);this.mons=[]},createMons:function(){if(!this.mons){this.mons=[];this.on("beforedestroy",this.clearMons,this,{single:true})}},mon:function(g,b,d,c,a){this.createMons();if(Ext.isObject(b)){var k=/^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;var i=b;for(var h in i){if(k.test(h)){continue}if(Ext.isFunction(i[h])){this.mons.push({item:g,ename:h,fn:i[h],scope:i.scope});g.on(h,i[h],i.scope,i)}else{this.mons.push({item:g,ename:h,fn:i[h],scope:i.scope});g.on(h,i[h])}}return}this.mons.push({item:g,ename:b,fn:d,scope:c});g.on(b,d,c,a)},mun:function(h,c,g,e){var k,d;this.createMons();for(var b=0,a=this.mons.length;b<a;++b){d=this.mons[b];if(h===d.item&&c==d.ename&&g===d.fn&&e===d.scope){this.mons.splice(b,1);h.un(c,g,e);k=true;break}}return k},nextSibling:function(){if(this.ownerCt){var a=this.ownerCt.items.indexOf(this);if(a!=-1&&a+1<this.ownerCt.items.getCount()){return this.ownerCt.items.itemAt(a+1)}}return null},previousSibling:function(){if(this.ownerCt){var a=this.ownerCt.items.indexOf(this);if(a>0){return this.ownerCt.items.itemAt(a-1)}}return null},getBubbleTarget:function(){return this.ownerCt}});Ext.reg("component",Ext.Component);Ext.Action=Ext.extend(Object,{constructor:function(a){this.initialConfig=a;this.itemId=a.itemId=(a.itemId||a.id||Ext.id());this.items=[]},isAction:true,setText:function(a){this.initialConfig.text=a;this.callEach("setText",[a])},getText:function(){return this.initialConfig.text},setIconClass:function(a){this.initialConfig.iconCls=a;this.callEach("setIconClass",[a])},getIconClass:function(){return this.initialConfig.iconCls},setDisabled:function(a){this.initialConfig.disabled=a;this.callEach("setDisabled",[a])},enable:function(){this.setDisabled(false)},disable:function(){this.setDisabled(true)},isDisabled:function(){return this.initialConfig.disabled},setHidden:function(a){this.initialConfig.hidden=a;this.callEach("setVisible",[!a])},show:function(){this.setHidden(false)},hide:function(){this.setHidden(true)},isHidden:function(){return this.initialConfig.hidden},setHandler:function(b,a){this.initialConfig.handler=b;this.initialConfig.scope=a;this.callEach("setHandler",[b,a])},each:function(b,a){Ext.each(this.items,b,a)},callEach:function(e,b){var d=this.items;for(var c=0,a=d.length;c<a;c++){d[c][e].apply(d[c],b)}},addComponent:function(a){this.items.push(a);a.on("destroy",this.removeComponent,this)},removeComponent:function(a){this.items.remove(a)},execute:function(){this.initialConfig.handler.apply(this.initialConfig.scope||window,arguments)}});(function(){Ext.Layer=function(d,c){d=d||{};var e=Ext.DomHelper,h=d.parentEl,g=h?Ext.getDom(h):document.body;if(c){this.dom=Ext.getDom(c)}if(!this.dom){var i=d.dh||{tag:"div",cls:"x-layer"};this.dom=e.append(g,i)}if(d.cls){this.addClass(d.cls)}this.constrain=d.constrain!==false;this.setVisibilityMode(Ext.Element.VISIBILITY);if(d.id){this.id=this.dom.id=d.id}else{this.id=Ext.id(this.dom)}this.zindex=d.zindex||this.getZIndex();this.position("absolute",this.zindex);if(d.shadow){this.shadowOffset=d.shadowOffset||4;this.shadow=new Ext.Shadow({offset:this.shadowOffset,mode:d.shadow})}else{this.shadowOffset=0}this.useShim=d.shim!==false&&Ext.useShims;this.useDisplay=d.useDisplay;this.hide()};var a=Ext.Element.prototype;var b=[];Ext.extend(Ext.Layer,Ext.Element,{getZIndex:function(){return this.zindex||parseInt((this.getShim()||this).getStyle("z-index"),10)||11000},getShim:function(){if(!this.useShim){return null}if(this.shim){return this.shim}var d=b.shift();if(!d){d=this.createShim();d.enableDisplayMode("block");d.dom.style.display="none";d.dom.style.visibility="visible"}var c=this.dom.parentNode;if(d.dom.parentNode!=c){c.insertBefore(d.dom,this.dom)}d.setStyle("z-index",this.getZIndex()-2);this.shim=d;return d},hideShim:function(){if(this.shim){this.shim.setDisplayed(false);b.push(this.shim);delete this.shim}},disableShadow:function(){if(this.shadow){this.shadowDisabled=true;this.shadow.hide();this.lastShadowOffset=this.shadowOffset;this.shadowOffset=0}},enableShadow:function(c){if(this.shadow){this.shadowDisabled=false;this.shadowOffset=this.lastShadowOffset;delete this.lastShadowOffset;if(c){this.sync(true)}}},sync:function(d){var o=this.shadow;if(!this.updating&&this.isVisible()&&(o||this.useShim)){var i=this.getShim(),n=this.getWidth(),k=this.getHeight(),e=this.getLeft(true),p=this.getTop(true);if(o&&!this.shadowDisabled){if(d&&!o.isVisible()){o.show(this)}else{o.realign(e,p,n,k)}if(i){if(d){i.show()}var m=o.el.getXY(),g=i.dom.style,c=o.el.getSize();g.left=(m[0])+"px";g.top=(m[1])+"px";g.width=(c.width)+"px";g.height=(c.height)+"px"}}else{if(i){if(d){i.show()}i.setSize(n,k);i.setLeftTop(e,p)}}}},destroy:function(){this.hideShim();if(this.shadow){this.shadow.hide()}this.removeAllListeners();Ext.removeNode(this.dom);delete this.dom},remove:function(){this.destroy()},beginUpdate:function(){this.updating=true},endUpdate:function(){this.updating=false;this.sync(true)},hideUnders:function(c){if(this.shadow){this.shadow.hide()}this.hideShim()},constrainXY:function(){if(this.constrain){var k=Ext.lib.Dom.getViewWidth(),d=Ext.lib.Dom.getViewHeight();var p=Ext.getDoc().getScroll();var o=this.getXY();var l=o[0],i=o[1];var c=this.shadowOffset;var m=this.dom.offsetWidth+c,e=this.dom.offsetHeight+c;var g=false;if((l+m)>k+p.left){l=k-m-c;g=true}if((i+e)>d+p.top){i=d-e-c;g=true}if(l<p.left){l=p.left;g=true}if(i<p.top){i=p.top;g=true}if(g){if(this.avoidY){var n=this.avoidY;if(i<=n&&(i+e)>=n){i=n-e-5}}o=[l,i];this.storeXY(o);a.setXY.call(this,o);this.sync()}}return this},getConstrainOffset:function(){return this.shadowOffset},isVisible:function(){return this.visible},showAction:function(){this.visible=true;if(this.useDisplay===true){this.setDisplayed("")}else{if(this.lastXY){a.setXY.call(this,this.lastXY)}else{if(this.lastLT){a.setLeftTop.call(this,this.lastLT[0],this.lastLT[1])}}}},hideAction:function(){this.visible=false;if(this.useDisplay===true){this.setDisplayed(false)}else{this.setLeftTop(-10000,-10000)}},setVisible:function(i,h,l,m,k){if(i){this.showAction()}if(h&&i){var g=function(){this.sync(true);if(m){m()}}.createDelegate(this);a.setVisible.call(this,true,true,l,g,k)}else{if(!i){this.hideUnders(true)}var g=m;if(h){g=function(){this.hideAction();if(m){m()}}.createDelegate(this)}a.setVisible.call(this,i,h,l,g,k);if(i){this.sync(true)}else{if(!h){this.hideAction()}}}return this},storeXY:function(c){delete this.lastLT;this.lastXY=c},storeLeftTop:function(d,c){delete this.lastXY;this.lastLT=[d,c]},beforeFx:function(){this.beforeAction();return Ext.Layer.superclass.beforeFx.apply(this,arguments)},afterFx:function(){Ext.Layer.superclass.afterFx.apply(this,arguments);this.sync(this.isVisible())},beforeAction:function(){if(!this.updating&&this.shadow){this.shadow.hide()}},setLeft:function(c){this.storeLeftTop(c,this.getTop(true));a.setLeft.apply(this,arguments);this.sync();return this},setTop:function(c){this.storeLeftTop(this.getLeft(true),c);a.setTop.apply(this,arguments);this.sync();return this},setLeftTop:function(d,c){this.storeLeftTop(d,c);a.setLeftTop.apply(this,arguments);this.sync();return this},setXY:function(k,h,l,m,i){this.fixDisplay();this.beforeAction();this.storeXY(k);var g=this.createCB(m);a.setXY.call(this,k,h,l,g,i);if(!h){g()}return this},createCB:function(e){var d=this;return function(){d.constrainXY();d.sync(true);if(e){e()}}},setX:function(g,h,k,l,i){this.setXY([g,this.getY()],h,k,l,i);return this},setY:function(l,g,i,k,h){this.setXY([this.getX(),l],g,i,k,h);return this},setSize:function(k,l,i,n,o,m){this.beforeAction();var g=this.createCB(o);a.setSize.call(this,k,l,i,n,g,m);if(!i){g()}return this},setWidth:function(i,h,l,m,k){this.beforeAction();var g=this.createCB(m);a.setWidth.call(this,i,h,l,g,k);if(!h){g()}return this},setHeight:function(k,i,m,n,l){this.beforeAction();var g=this.createCB(n);a.setHeight.call(this,k,i,m,g,l);if(!i){g()}return this},setBounds:function(p,n,q,i,o,l,m,k){this.beforeAction();var g=this.createCB(m);if(!o){this.storeXY([p,n]);a.setXY.call(this,[p,n]);a.setSize.call(this,q,i,o,l,g,k);g()}else{a.setBounds.call(this,p,n,q,i,o,l,g,k)}return this},setZIndex:function(c){this.zindex=c;this.setStyle("z-index",c+2);if(this.shadow){this.shadow.setZIndex(c+1)}if(this.shim){this.shim.setStyle("z-index",c)}return this}})})();Ext.Shadow=function(d){Ext.apply(this,d);if(typeof this.mode!="string"){this.mode=this.defaultMode}var e=this.offset,c={h:0},b=Math.floor(this.offset/2);switch(this.mode.toLowerCase()){case"drop":c.w=0;c.l=c.t=e;c.t-=1;if(Ext.isIE){c.l-=this.offset+b;c.t-=this.offset+b;c.w-=b;c.h-=b;c.t+=1}break;case"sides":c.w=(e*2);c.l=-e;c.t=e-1;if(Ext.isIE){c.l-=(this.offset-b);c.t-=this.offset+b;c.l+=1;c.w-=(this.offset-b)*2;c.w-=b+1;c.h-=1}break;case"frame":c.w=c.h=(e*2);c.l=c.t=-e;c.t+=1;c.h-=2;if(Ext.isIE){c.l-=(this.offset-b);c.t-=(this.offset-b);c.l+=1;c.w-=(this.offset+b+1);c.h-=(this.offset+b);c.h+=1}break}this.adjusts=c};Ext.Shadow.prototype={offset:4,defaultMode:"drop",show:function(a){a=Ext.get(a);if(!this.el){this.el=Ext.Shadow.Pool.pull();if(this.el.dom.nextSibling!=a.dom){this.el.insertBefore(a)}}this.el.setStyle("z-index",this.zIndex||parseInt(a.getStyle("z-index"),10)-1);if(Ext.isIE){this.el.dom.style.filter="progid:DXImageTransform.Microsoft.alpha(opacity=50) progid:DXImageTransform.Microsoft.Blur(pixelradius="+(this.offset)+")"}this.realign(a.getLeft(true),a.getTop(true),a.getWidth(),a.getHeight());this.el.dom.style.display="block"},isVisible:function(){return this.el?true:false},realign:function(b,u,r,g){if(!this.el){return}var o=this.adjusts,m=this.el.dom,v=m.style,i=0,q=(r+o.w),e=(g+o.h),k=q+"px",p=e+"px",n,c;v.left=(b+o.l)+"px";v.top=(u+o.t)+"px";if(v.width!=k||v.height!=p){v.width=k;v.height=p;if(!Ext.isIE){n=m.childNodes;c=Math.max(0,(q-12))+"px";n[0].childNodes[1].style.width=c;n[1].childNodes[1].style.width=c;n[2].childNodes[1].style.width=c;n[1].style.height=Math.max(0,(e-12))+"px"}}},hide:function(){if(this.el){this.el.dom.style.display="none";Ext.Shadow.Pool.push(this.el);delete this.el}},setZIndex:function(a){this.zIndex=a;if(this.el){this.el.setStyle("z-index",a)}}};Ext.Shadow.Pool=function(){var b=[],a=Ext.isIE?'<div class="x-ie-shadow"></div>':'<div class="x-shadow"><div class="xst"><div class="xstl"></div><div class="xstc"></div><div class="xstr"></div></div><div class="xsc"><div class="xsml"></div><div class="xsmc"></div><div class="xsmr"></div></div><div class="xsb"><div class="xsbl"></div><div class="xsbc"></div><div class="xsbr"></div></div></div>';return{pull:function(){var c=b.shift();if(!c){c=Ext.get(Ext.DomHelper.insertHtml("beforeBegin",document.body.firstChild,a));c.autoBoxAdjust=false}return c},push:function(c){b.push(c)}}}();Ext.BoxComponent=Ext.extend(Ext.Component,{initComponent:function(){Ext.BoxComponent.superclass.initComponent.call(this);this.addEvents("resize","move")},boxReady:false,deferHeight:false,setSize:function(b,d){if(typeof b=="object"){d=b.height;b=b.width}if(Ext.isDefined(b)&&Ext.isDefined(this.boxMinWidth)&&(b<this.boxMinWidth)){b=this.boxMinWidth}if(Ext.isDefined(d)&&Ext.isDefined(this.boxMinHeight)&&(d<this.boxMinHeight)){d=this.boxMinHeight}if(Ext.isDefined(b)&&Ext.isDefined(this.boxMaxWidth)&&(b>this.boxMaxWidth)){b=this.boxMaxWidth}if(Ext.isDefined(d)&&Ext.isDefined(this.boxMaxHeight)&&(d>this.boxMaxHeight)){d=this.boxMaxHeight}if(!this.boxReady){this.width=b;this.height=d;return this}if(this.cacheSizes!==false&&this.lastSize&&this.lastSize.width==b&&this.lastSize.height==d){return this}this.lastSize={width:b,height:d};var c=this.adjustSize(b,d),g=c.width,a=c.height,e;if(g!==undefined||a!==undefined){e=this.getResizeEl();if(!this.deferHeight&&g!==undefined&&a!==undefined){e.setSize(g,a)}else{if(!this.deferHeight&&a!==undefined){e.setHeight(a)}else{if(g!==undefined){e.setWidth(g)}}}this.onResize(g,a,b,d);this.fireEvent("resize",this,g,a,b,d)}return this},setWidth:function(a){return this.setSize(a)},setHeight:function(a){return this.setSize(undefined,a)},getSize:function(){return this.getResizeEl().getSize()},getWidth:function(){return this.getResizeEl().getWidth()},getHeight:function(){return this.getResizeEl().getHeight()},getOuterSize:function(){var a=this.getResizeEl();return{width:a.getWidth()+a.getMargins("lr"),height:a.getHeight()+a.getMargins("tb")}},getPosition:function(a){var b=this.getPositionEl();if(a===true){return[b.getLeft(true),b.getTop(true)]}return this.xy||b.getXY()},getBox:function(a){var c=this.getPosition(a);var b=this.getSize();b.x=c[0];b.y=c[1];return b},updateBox:function(a){this.setSize(a.width,a.height);this.setPagePosition(a.x,a.y);return this},getResizeEl:function(){return this.resizeEl||this.el},setAutoScroll:function(a){if(this.rendered){this.getContentTarget().setOverflow(a?"auto":"")}this.autoScroll=a;return this},setPosition:function(a,g){if(a&&typeof a[1]=="number"){g=a[1];a=a[0]}this.x=a;this.y=g;if(!this.boxReady){return this}var b=this.adjustPosition(a,g);var e=b.x,d=b.y;var c=this.getPositionEl();if(e!==undefined||d!==undefined){if(e!==undefined&&d!==undefined){c.setLeftTop(e,d)}else{if(e!==undefined){c.setLeft(e)}else{if(d!==undefined){c.setTop(d)}}}this.onPosition(e,d);this.fireEvent("move",this,e,d)}return this},setPagePosition:function(a,c){if(a&&typeof a[1]=="number"){c=a[1];a=a[0]}this.pageX=a;this.pageY=c;if(!this.boxReady){return}if(a===undefined||c===undefined){return}var b=this.getPositionEl().translatePoints(a,c);this.setPosition(b.left,b.top);return this},afterRender:function(){Ext.BoxComponent.superclass.afterRender.call(this);if(this.resizeEl){this.resizeEl=Ext.get(this.resizeEl)}if(this.positionEl){this.positionEl=Ext.get(this.positionEl)}this.boxReady=true;Ext.isDefined(this.autoScroll)&&this.setAutoScroll(this.autoScroll);this.setSize(this.width,this.height);if(this.x||this.y){this.setPosition(this.x,this.y)}else{if(this.pageX||this.pageY){this.setPagePosition(this.pageX,this.pageY)}}},syncSize:function(){delete this.lastSize;this.setSize(this.autoWidth?undefined:this.getResizeEl().getWidth(),this.autoHeight?undefined:this.getResizeEl().getHeight());return this},onResize:function(d,b,a,c){},onPosition:function(a,b){},adjustSize:function(a,b){if(this.autoWidth){a="auto"}if(this.autoHeight){b="auto"}return{width:a,height:b}},adjustPosition:function(a,b){return{x:a,y:b}}});Ext.reg("box",Ext.BoxComponent);Ext.Spacer=Ext.extend(Ext.BoxComponent,{autoEl:"div"});Ext.reg("spacer",Ext.Spacer);Ext.SplitBar=function(c,e,b,d,a){this.el=Ext.get(c,true);this.el.dom.unselectable="on";this.resizingEl=Ext.get(e,true);this.orientation=b||Ext.SplitBar.HORIZONTAL;this.minSize=0;this.maxSize=2000;this.animate=false;this.useShim=false;this.shim=null;if(!a){this.proxy=Ext.SplitBar.createProxy(this.orientation)}else{this.proxy=Ext.get(a).dom}this.dd=new Ext.dd.DDProxy(this.el.dom.id,"XSplitBars",{dragElId:this.proxy.id});this.dd.b4StartDrag=this.onStartProxyDrag.createDelegate(this);this.dd.endDrag=this.onEndProxyDrag.createDelegate(this);this.dragSpecs={};this.adapter=new Ext.SplitBar.BasicLayoutAdapter();this.adapter.init(this);if(this.orientation==Ext.SplitBar.HORIZONTAL){this.placement=d||(this.el.getX()>this.resizingEl.getX()?Ext.SplitBar.LEFT:Ext.SplitBar.RIGHT);this.el.addClass("x-splitbar-h")}else{this.placement=d||(this.el.getY()>this.resizingEl.getY()?Ext.SplitBar.TOP:Ext.SplitBar.BOTTOM);this.el.addClass("x-splitbar-v")}this.addEvents("resize","moved","beforeresize","beforeapply");Ext.SplitBar.superclass.constructor.call(this)};Ext.extend(Ext.SplitBar,Ext.util.Observable,{onStartProxyDrag:function(a,e){this.fireEvent("beforeresize",this);this.overlay=Ext.DomHelper.append(document.body,{cls:"x-drag-overlay",html:" "},true);this.overlay.unselectable();this.overlay.setSize(Ext.lib.Dom.getViewWidth(true),Ext.lib.Dom.getViewHeight(true));this.overlay.show();Ext.get(this.proxy).setDisplayed("block");var c=this.adapter.getElementSize(this);this.activeMinSize=this.getMinimumSize();this.activeMaxSize=this.getMaximumSize();var d=c-this.activeMinSize;var b=Math.max(this.activeMaxSize-c,0);if(this.orientation==Ext.SplitBar.HORIZONTAL){this.dd.resetConstraints();this.dd.setXConstraint(this.placement==Ext.SplitBar.LEFT?d:b,this.placement==Ext.SplitBar.LEFT?b:d,this.tickSize);this.dd.setYConstraint(0,0)}else{this.dd.resetConstraints();this.dd.setXConstraint(0,0);this.dd.setYConstraint(this.placement==Ext.SplitBar.TOP?d:b,this.placement==Ext.SplitBar.TOP?b:d,this.tickSize)}this.dragSpecs.startSize=c;this.dragSpecs.startPoint=[a,e];Ext.dd.DDProxy.prototype.b4StartDrag.call(this.dd,a,e)},onEndProxyDrag:function(c){Ext.get(this.proxy).setDisplayed(false);var b=Ext.lib.Event.getXY(c);if(this.overlay){Ext.destroy(this.overlay);delete this.overlay}var a;if(this.orientation==Ext.SplitBar.HORIZONTAL){a=this.dragSpecs.startSize+(this.placement==Ext.SplitBar.LEFT?b[0]-this.dragSpecs.startPoint[0]:this.dragSpecs.startPoint[0]-b[0])}else{a=this.dragSpecs.startSize+(this.placement==Ext.SplitBar.TOP?b[1]-this.dragSpecs.startPoint[1]:this.dragSpecs.startPoint[1]-b[1])}a=Math.min(Math.max(a,this.activeMinSize),this.activeMaxSize);if(a!=this.dragSpecs.startSize){if(this.fireEvent("beforeapply",this,a)!==false){this.adapter.setElementSize(this,a);this.fireEvent("moved",this,a);this.fireEvent("resize",this,a)}}},getAdapter:function(){return this.adapter},setAdapter:function(a){this.adapter=a;this.adapter.init(this)},getMinimumSize:function(){return this.minSize},setMinimumSize:function(a){this.minSize=a},getMaximumSize:function(){return this.maxSize},setMaximumSize:function(a){this.maxSize=a},setCurrentSize:function(b){var a=this.animate;this.animate=false;this.adapter.setElementSize(this,b);this.animate=a},destroy:function(a){Ext.destroy(this.shim,Ext.get(this.proxy));this.dd.unreg();if(a){this.el.remove()}this.purgeListeners()}});Ext.SplitBar.createProxy=function(b){var c=new Ext.Element(document.createElement("div"));document.body.appendChild(c.dom);c.unselectable();var a="x-splitbar-proxy";c.addClass(a+" "+(b==Ext.SplitBar.HORIZONTAL?a+"-h":a+"-v"));return c.dom};Ext.SplitBar.BasicLayoutAdapter=function(){};Ext.SplitBar.BasicLayoutAdapter.prototype={init:function(a){},getElementSize:function(a){if(a.orientation==Ext.SplitBar.HORIZONTAL){return a.resizingEl.getWidth()}else{return a.resizingEl.getHeight()}},setElementSize:function(b,a,c){if(b.orientation==Ext.SplitBar.HORIZONTAL){if(!b.animate){b.resizingEl.setWidth(a);if(c){c(b,a)}}else{b.resizingEl.setWidth(a,true,0.1,c,"easeOut")}}else{if(!b.animate){b.resizingEl.setHeight(a);if(c){c(b,a)}}else{b.resizingEl.setHeight(a,true,0.1,c,"easeOut")}}}};Ext.SplitBar.AbsoluteLayoutAdapter=function(a){this.basic=new Ext.SplitBar.BasicLayoutAdapter();this.container=Ext.get(a)};Ext.SplitBar.AbsoluteLayoutAdapter.prototype={init:function(a){this.basic.init(a)},getElementSize:function(a){return this.basic.getElementSize(a)},setElementSize:function(b,a,c){this.basic.setElementSize(b,a,this.moveSplitter.createDelegate(this,[b]))},moveSplitter:function(a){var b=Ext.SplitBar;switch(a.placement){case b.LEFT:a.el.setX(a.resizingEl.getRight());break;case b.RIGHT:a.el.setStyle("right",(this.container.getWidth()-a.resizingEl.getLeft())+"px");break;case b.TOP:a.el.setY(a.resizingEl.getBottom());break;case b.BOTTOM:a.el.setY(a.resizingEl.getTop()-a.el.getHeight());break}}};Ext.SplitBar.VERTICAL=1;Ext.SplitBar.HORIZONTAL=2;Ext.SplitBar.LEFT=1;Ext.SplitBar.RIGHT=2;Ext.SplitBar.TOP=3;Ext.SplitBar.BOTTOM=4;Ext.Container=Ext.extend(Ext.BoxComponent,{bufferResize:50,autoDestroy:true,forceLayout:false,defaultType:"panel",resizeEvent:"resize",bubbleEvents:["add","remove"],initComponent:function(){Ext.Container.superclass.initComponent.call(this);this.addEvents("afterlayout","beforeadd","beforeremove","add","remove");var a=this.items;if(a){delete this.items;this.add(a)}},initItems:function(){if(!this.items){this.items=new Ext.util.MixedCollection(false,this.getComponentId);this.getLayout()}},setLayout:function(a){if(this.layout&&this.layout!=a){this.layout.setContainer(null)}this.layout=a;this.initItems();a.setContainer(this)},afterRender:function(){Ext.Container.superclass.afterRender.call(this);if(!this.layout){this.layout="auto"}if(Ext.isObject(this.layout)&&!this.layout.layout){this.layoutConfig=this.layout;this.layout=this.layoutConfig.type}if(Ext.isString(this.layout)){this.layout=new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig)}this.setLayout(this.layout);if(this.activeItem!==undefined&&this.layout.setActiveItem){var a=this.activeItem;delete this.activeItem;this.layout.setActiveItem(a)}if(!this.ownerCt){this.doLayout(false,true)}if(this.monitorResize===true){Ext.EventManager.onWindowResize(this.doLayout,this,[false])}},getLayoutTarget:function(){return this.el},getComponentId:function(a){return a.getItemId()},add:function(b){this.initItems();var e=arguments.length>1;if(e||Ext.isArray(b)){var a=[];Ext.each(e?arguments:b,function(h){a.push(this.add(h))},this);return a}var g=this.lookupComponent(this.applyDefaults(b));var d=this.items.length;if(this.fireEvent("beforeadd",this,g,d)!==false&&this.onBeforeAdd(g)!==false){this.items.add(g);g.onAdded(this,d);this.onAdd(g);this.fireEvent("add",this,g,d)}return g},onAdd:function(a){},onAdded:function(a,b){this.ownerCt=a;this.initRef();this.cascade(function(d){d.initRef()});this.fireEvent("added",this,a,b)},insert:function(e,b){var d=arguments,h=d.length,a=[],g,k;this.initItems();if(h>2){for(g=h-1;g>=1;--g){a.push(this.insert(e,d[g]))}return a}k=this.lookupComponent(this.applyDefaults(b));e=Math.min(e,this.items.length);if(this.fireEvent("beforeadd",this,k,e)!==false&&this.onBeforeAdd(k)!==false){if(k.ownerCt==this){this.items.remove(k)}this.items.insert(e,k);k.onAdded(this,e);this.onAdd(k);this.fireEvent("add",this,k,e)}return k},applyDefaults:function(b){var a=this.defaults;if(a){if(Ext.isFunction(a)){a=a.call(this,b)}if(Ext.isString(b)){b=Ext.ComponentMgr.get(b);Ext.apply(b,a)}else{if(!b.events){Ext.applyIf(b.isAction?b.initialConfig:b,a)}else{Ext.apply(b,a)}}}return b},onBeforeAdd:function(a){if(a.ownerCt){a.ownerCt.remove(a,false)}if(this.hideBorders===true){a.border=(a.border===true)}},remove:function(a,b){this.initItems();var d=this.getComponent(a);if(d&&this.fireEvent("beforeremove",this,d)!==false){this.doRemove(d,b);this.fireEvent("remove",this,d)}return d},onRemove:function(a){},doRemove:function(e,d){var b=this.layout,a=b&&this.rendered;if(a){b.onRemove(e)}this.items.remove(e);e.onRemoved();this.onRemove(e);if(d===true||(d!==false&&this.autoDestroy)){e.destroy()}if(a){b.afterRemove(e)}},removeAll:function(c){this.initItems();var e,g=[],b=[];this.items.each(function(h){g.push(h)});for(var d=0,a=g.length;d<a;++d){e=g[d];this.remove(e,c);if(e.ownerCt!==this){b.push(e)}}return b},getComponent:function(a){if(Ext.isObject(a)){a=a.getItemId()}return this.items.get(a)},lookupComponent:function(a){if(Ext.isString(a)){return Ext.ComponentMgr.get(a)}else{if(!a.events){return this.createComponent(a)}}return a},createComponent:function(a,d){if(a.render){return a}var b=Ext.create(Ext.apply({ownerCt:this},a),d||this.defaultType);delete b.initialConfig.ownerCt;delete b.ownerCt;return b},canLayout:function(){var a=this.getVisibilityEl();return a&&a.dom&&!a.isStyle("display","none")},doLayout:function(g,e){var l=this.rendered,k=e||this.forceLayout;if(this.collapsed||!this.canLayout()){this.deferLayout=this.deferLayout||!g;if(!k){return}g=g&&!this.deferLayout}else{delete this.deferLayout}if(l&&this.layout){this.layout.layout()}if(g!==true&&this.items){var d=this.items.items;for(var b=0,a=d.length;b<a;b++){var h=d[b];if(h.doLayout){h.doLayout(false,k)}}}if(l){this.onLayout(g,k)}this.hasLayout=true;delete this.forceLayout},onLayout:Ext.emptyFn,shouldBufferLayout:function(){var a=this.hasLayout;if(this.ownerCt){return a?!this.hasLayoutPending():false}return a},hasLayoutPending:function(){var a=false;this.ownerCt.bubble(function(b){if(b.layoutPending){a=true;return false}});return a},onShow:function(){Ext.Container.superclass.onShow.call(this);if(Ext.isDefined(this.deferLayout)){delete this.deferLayout;this.doLayout(true)}},getLayout:function(){if(!this.layout){var a=new Ext.layout.AutoLayout(this.layoutConfig);this.setLayout(a)}return this.layout},beforeDestroy:function(){var a;if(this.items){while(a=this.items.first()){this.doRemove(a,true)}}if(this.monitorResize){Ext.EventManager.removeResizeListener(this.doLayout,this)}Ext.destroy(this.layout);Ext.Container.superclass.beforeDestroy.call(this)},cascade:function(g,e,b){if(g.apply(e||this,b||[this])!==false){if(this.items){var d=this.items.items;for(var c=0,a=d.length;c<a;c++){if(d[c].cascade){d[c].cascade(g,e,b)}else{g.apply(e||d[c],b||[d[c]])}}}}return this},findById:function(c){var a=null,b=this;this.cascade(function(d){if(b!=d&&d.id===c){a=d;return false}});return a},findByType:function(b,a){return this.findBy(function(d){return d.isXType(b,a)})},find:function(b,a){return this.findBy(function(d){return d[b]===a})},findBy:function(d,c){var a=[],b=this;this.cascade(function(e){if(b!=e&&d.call(c||e,e,b)===true){a.push(e)}});return a},get:function(a){return this.getComponent(a)}});Ext.Container.LAYOUTS={};Ext.reg("container",Ext.Container);Ext.layout.ContainerLayout=Ext.extend(Object,{monitorResize:false,activeItem:null,constructor:function(a){this.id=Ext.id(null,"ext-layout-");Ext.apply(this,a)},type:"container",IEMeasureHack:function(l,g){var a=l.dom.childNodes,b=a.length,o,n=[],m,h,k;for(h=0;h<b;h++){o=a[h];m=Ext.get(o);if(m){n[h]=m.getStyle("display");m.setStyle({display:"none"})}}k=l?l.getViewSize(g):{};for(h=0;h<b;h++){o=a[h];m=Ext.get(o);if(m){m.setStyle({display:n[h]})}}return k},getLayoutTargetSize:Ext.EmptyFn,layout:function(){var a=this.container,b=a.getLayoutTarget();if(!(this.hasLayout||Ext.isEmpty(this.targetCls))){b.addClass(this.targetCls)}this.onLayout(a,b);a.fireEvent("afterlayout",a,this)},onLayout:function(a,b){this.renderAll(a,b)},isValidParent:function(b,a){return a&&b.getPositionEl().dom.parentNode==(a.dom||a)},renderAll:function(e,g){var b=e.items.items,d,h,a=b.length;for(d=0;d<a;d++){h=b[d];if(h&&(!h.rendered||!this.isValidParent(h,g))){this.renderItem(h,d,g)}}},renderItem:function(d,a,b){if(d){if(!d.rendered){d.render(b,a);this.configureItem(d)}else{if(!this.isValidParent(d,b)){if(Ext.isNumber(a)){a=b.dom.childNodes[a]}b.dom.insertBefore(d.getPositionEl().dom,a||null);d.container=b;this.configureItem(d)}}}},getRenderedItems:function(g){var e=g.getLayoutTarget(),h=g.items.items,a=h.length,d,k,b=[];for(d=0;d<a;d++){if((k=h[d]).rendered&&this.isValidParent(k,e)&&k.shouldLayout!==false){b.push(k)}}return b},configureItem:function(b){if(this.extraCls){var a=b.getPositionEl?b.getPositionEl():b;a.addClass(this.extraCls)}if(b.doLayout&&this.forceLayout){b.doLayout()}if(this.renderHidden&&b!=this.activeItem){b.hide()}},onRemove:function(b){if(this.activeItem==b){delete this.activeItem}if(b.rendered&&this.extraCls){var a=b.getPositionEl?b.getPositionEl():b;a.removeClass(this.extraCls)}},afterRemove:function(a){if(a.removeRestore){a.removeMode="container";delete a.removeRestore}},onResize:function(){var c=this.container,a;if(c.collapsed){return}if(a=c.bufferResize&&c.shouldBufferLayout()){if(!this.resizeTask){this.resizeTask=new Ext.util.DelayedTask(this.runLayout,this);this.resizeBuffer=Ext.isNumber(a)?a:50}c.layoutPending=true;this.resizeTask.delay(this.resizeBuffer)}else{this.runLayout()}},runLayout:function(){var a=this.container;this.layout();a.onLayout();delete a.layoutPending},setContainer:function(b){if(this.monitorResize&&b!=this.container){var a=this.container;if(a){a.un(a.resizeEvent,this.onResize,this)}if(b){b.on(b.resizeEvent,this.onResize,this)}}this.container=b},parseMargins:function(b){if(Ext.isNumber(b)){b=b.toString()}var c=b.split(" "),a=c.length;if(a==1){c[1]=c[2]=c[3]=c[0]}else{if(a==2){c[2]=c[0];c[3]=c[1]}else{if(a==3){c[3]=c[1]}}}return{top:parseInt(c[0],10)||0,right:parseInt(c[1],10)||0,bottom:parseInt(c[2],10)||0,left:parseInt(c[3],10)||0}},fieldTpl:(function(){var a=new Ext.Template('<div class="x-form-item {itemCls}" tabIndex="-1">','<label for="{id}" style="{labelStyle}" class="x-form-item-label">{label}{labelSeparator}</label>','<div class="x-form-element" id="x-form-el-{id}" style="{elementStyle}">','</div><div class="{clearCls}"></div>',"</div>");a.disableFormats=true;return a.compile()})(),destroy:function(){if(this.resizeTask&&this.resizeTask.cancel){this.resizeTask.cancel()}if(this.container){this.container.un(this.container.resizeEvent,this.onResize,this)}if(!Ext.isEmpty(this.targetCls)){var a=this.container.getLayoutTarget();if(a){a.removeClass(this.targetCls)}}}});Ext.layout.AutoLayout=Ext.extend(Ext.layout.ContainerLayout,{type:"auto",monitorResize:true,onLayout:function(d,g){Ext.layout.AutoLayout.superclass.onLayout.call(this,d,g);var e=this.getRenderedItems(d),a=e.length,b,h;for(b=0;b<a;b++){h=e[b];if(h.doLayout){h.doLayout(true)}}}});Ext.Container.LAYOUTS.auto=Ext.layout.AutoLayout;Ext.layout.FitLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,type:"fit",getLayoutTargetSize:function(){var a=this.container.getLayoutTarget();if(!a){return{}}return a.getStyleSize()},onLayout:function(a,b){Ext.layout.FitLayout.superclass.onLayout.call(this,a,b);if(!a.collapsed){this.setItemSize(this.activeItem||a.items.itemAt(0),this.getLayoutTargetSize())}},setItemSize:function(b,a){if(b&&a.height>0){b.setSize(a)}}});Ext.Container.LAYOUTS.fit=Ext.layout.FitLayout;Ext.layout.CardLayout=Ext.extend(Ext.layout.FitLayout,{deferredRender:false,layoutOnCardChange:false,renderHidden:true,type:"card",setActiveItem:function(d){var a=this.activeItem,b=this.container;d=b.getComponent(d);if(d&&a!=d){if(a){a.hide();if(a.hidden!==true){return false}a.fireEvent("deactivate",a)}var c=d.doLayout&&(this.layoutOnCardChange||!d.rendered);this.activeItem=d;delete d.deferLayout;d.show();this.layout();if(c){d.doLayout()}d.fireEvent("activate",d)}},renderAll:function(a,b){if(this.deferredRender){this.renderItem(this.activeItem,undefined,b)}else{Ext.layout.CardLayout.superclass.renderAll.call(this,a,b)}}});Ext.Container.LAYOUTS.card=Ext.layout.CardLayout;Ext.layout.AnchorLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,type:"anchor",defaultAnchor:"100%",parseAnchorRE:/^(r|right|b|bottom)$/i,getLayoutTargetSize:function(){var b=this.container.getLayoutTarget(),a={};if(b){a=b.getViewSize();if(Ext.isIE&&Ext.isStrict&&a.width==0){a=b.getStyleSize()}a.width-=b.getPadding("lr");a.height-=b.getPadding("tb")}return a},onLayout:function(n,x){Ext.layout.AnchorLayout.superclass.onLayout.call(this,n,x);var q=this.getLayoutTargetSize(),l=q.width,p=q.height,r=x.getStyle("overflow"),o=this.getRenderedItems(n),u=o.length,g=[],k,a,w,m,h,c,e,d,v=0,t,b;if(l<20&&p<20){return}if(n.anchorSize){if(typeof n.anchorSize=="number"){a=n.anchorSize}else{a=n.anchorSize.width;w=n.anchorSize.height}}else{a=n.initialConfig.width;w=n.initialConfig.height}for(t=0;t<u;t++){m=o[t];b=m.getPositionEl();if(!m.anchor&&m.items&&!Ext.isNumber(m.width)&&!(Ext.isIE6&&Ext.isStrict)){m.anchor=this.defaultAnchor}if(m.anchor){h=m.anchorSpec;if(!h){d=m.anchor.split(" ");m.anchorSpec=h={right:this.parseAnchor(d[0],m.initialConfig.width,a),bottom:this.parseAnchor(d[1],m.initialConfig.height,w)}}c=h.right?this.adjustWidthAnchor(h.right(l)-b.getMargins("lr"),m):undefined;e=h.bottom?this.adjustHeightAnchor(h.bottom(p)-b.getMargins("tb"),m):undefined;if(c||e){g.push({component:m,width:c||undefined,height:e||undefined})}}}for(t=0,u=g.length;t<u;t++){k=g[t];k.component.setSize(k.width,k.height)}if(r&&r!="hidden"&&!this.adjustmentPass){var s=this.getLayoutTargetSize();if(s.width!=q.width||s.height!=q.height){this.adjustmentPass=true;this.onLayout(n,x)}}delete this.adjustmentPass},parseAnchor:function(c,h,b){if(c&&c!="none"){var e;if(this.parseAnchorRE.test(c)){var g=b-h;return function(a){if(a!==e){e=a;return a-g}}}else{if(c.indexOf("%")!=-1){var d=parseFloat(c.replace("%",""))*0.01;return function(a){if(a!==e){e=a;return Math.floor(a*d)}}}else{c=parseInt(c,10);if(!isNaN(c)){return function(a){if(a!==e){e=a;return a+c}}}}}}return false},adjustWidthAnchor:function(b,a){return b},adjustHeightAnchor:function(b,a){return b}});Ext.Container.LAYOUTS.anchor=Ext.layout.AnchorLayout;Ext.layout.ColumnLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,type:"column",extraCls:"x-column",scrollOffset:0,targetCls:"x-column-layout-ct",isValidParent:function(b,a){return this.innerCt&&b.getPositionEl().dom.parentNode==this.innerCt.dom},getLayoutTargetSize:function(){var b=this.container.getLayoutTarget(),a;if(b){a=b.getViewSize();if(Ext.isIE&&Ext.isStrict&&a.width==0){a=b.getStyleSize()}a.width-=b.getPadding("lr");a.height-=b.getPadding("tb")}return a},renderAll:function(a,b){if(!this.innerCt){this.innerCt=b.createChild({cls:"x-column-inner"});this.innerCt.createChild({cls:"x-clear"})}Ext.layout.ColumnLayout.superclass.renderAll.call(this,a,this.innerCt)},onLayout:function(e,l){var g=e.items.items,k=g.length,o,b,a,p=[];this.renderAll(e,l);var s=this.getLayoutTargetSize();if(s.width<1&&s.height<1){return}var q=s.width-this.scrollOffset,d=s.height,r=q;this.innerCt.setWidth(q);for(b=0;b<k;b++){o=g[b];a=o.getPositionEl().getMargins("lr");p[b]=a;if(!o.columnWidth){r-=(o.getWidth()+a)}}r=r<0?0:r;for(b=0;b<k;b++){o=g[b];a=p[b];if(o.columnWidth){o.setSize(Math.floor(o.columnWidth*r)-a)}}if(Ext.isIE){if(b=l.getStyle("overflow")&&b!="hidden"&&!this.adjustmentPass){var n=this.getLayoutTargetSize();if(n.width!=s.width){this.adjustmentPass=true;this.onLayout(e,l)}}}delete this.adjustmentPass}});Ext.Container.LAYOUTS.column=Ext.layout.ColumnLayout;Ext.layout.BorderLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,rendered:false,type:"border",targetCls:"x-border-layout-ct",getLayoutTargetSize:function(){var a=this.container.getLayoutTarget();return a?a.getViewSize():{}},onLayout:function(g,J){var k,C,G,p,y=g.items.items,D=y.length;if(!this.rendered){k=[];for(C=0;C<D;C++){G=y[C];p=G.region;if(G.collapsed){k.push(G)}G.collapsed=false;if(!G.rendered){G.render(J,C);G.getPositionEl().addClass("x-border-panel")}this[p]=p!="center"&&G.split?new Ext.layout.BorderLayout.SplitRegion(this,G.initialConfig,p):new Ext.layout.BorderLayout.Region(this,G.initialConfig,p);this[p].render(J,G)}this.rendered=true}var x=this.getLayoutTargetSize();if(x.width<20||x.height<20){if(k){this.restoreCollapsed=k}return}else{if(this.restoreCollapsed){k=this.restoreCollapsed;delete this.restoreCollapsed}}var u=x.width,E=x.height,t=u,B=E,q=0,r=0,z=this.north,v=this.south,o=this.west,F=this.east,G=this.center,I,A,d,H;if(!G&&Ext.layout.BorderLayout.WARN!==false){throw"No center region defined in BorderLayout "+g.id}if(z&&z.isVisible()){I=z.getSize();A=z.getMargins();I.width=u-(A.left+A.right);I.x=A.left;I.y=A.top;q=I.height+I.y+A.bottom;B-=q;z.applyLayout(I)}if(v&&v.isVisible()){I=v.getSize();A=v.getMargins();I.width=u-(A.left+A.right);I.x=A.left;H=(I.height+A.top+A.bottom);I.y=E-H+A.top;B-=H;v.applyLayout(I)}if(o&&o.isVisible()){I=o.getSize();A=o.getMargins();I.height=B-(A.top+A.bottom);I.x=A.left;I.y=q+A.top;d=(I.width+A.left+A.right);r+=d;t-=d;o.applyLayout(I)}if(F&&F.isVisible()){I=F.getSize();A=F.getMargins();I.height=B-(A.top+A.bottom);d=(I.width+A.left+A.right);I.x=u-d+A.left;I.y=q+A.top;t-=d;F.applyLayout(I)}if(G){A=G.getMargins();var l={x:r+A.left,y:q+A.top,width:t-(A.left+A.right),height:B-(A.top+A.bottom)};G.applyLayout(l)}if(k){for(C=0,D=k.length;C<D;C++){k[C].collapse(false)}}if(Ext.isIE&&Ext.isStrict){J.repaint()}if(C=J.getStyle("overflow")&&C!="hidden"&&!this.adjustmentPass){var a=this.getLayoutTargetSize();if(a.width!=x.width||a.height!=x.height){this.adjustmentPass=true;this.onLayout(g,J)}}delete this.adjustmentPass},destroy:function(){var b=["north","south","east","west"],a,c;for(a=0;a<b.length;a++){c=this[b[a]];if(c){if(c.destroy){c.destroy()}else{if(c.split){c.split.destroy(true)}}}}Ext.layout.BorderLayout.superclass.destroy.call(this)}});Ext.layout.BorderLayout.Region=function(b,a,c){Ext.apply(this,a);this.layout=b;this.position=c;this.state={};if(typeof this.margins=="string"){this.margins=this.layout.parseMargins(this.margins)}this.margins=Ext.applyIf(this.margins||{},this.defaultMargins);if(this.collapsible){if(typeof this.cmargins=="string"){this.cmargins=this.layout.parseMargins(this.cmargins)}if(this.collapseMode=="mini"&&!this.cmargins){this.cmargins={left:0,top:0,right:0,bottom:0}}else{this.cmargins=Ext.applyIf(this.cmargins||{},c=="north"||c=="south"?this.defaultNSCMargins:this.defaultEWCMargins)}}};Ext.layout.BorderLayout.Region.prototype={collapsible:false,split:false,floatable:true,minWidth:50,minHeight:50,defaultMargins:{left:0,top:0,right:0,bottom:0},defaultNSCMargins:{left:5,top:5,right:5,bottom:5},defaultEWCMargins:{left:5,top:0,right:5,bottom:0},floatingZIndex:100,isCollapsed:false,render:function(b,c){this.panel=c;c.el.enableDisplayMode();this.targetEl=b;this.el=c.el;var a=c.getState,d=this.position;c.getState=function(){return Ext.apply(a.call(c)||{},this.state)}.createDelegate(this);if(d!="center"){c.allowQueuedExpand=false;c.on({beforecollapse:this.beforeCollapse,collapse:this.onCollapse,beforeexpand:this.beforeExpand,expand:this.onExpand,hide:this.onHide,show:this.onShow,scope:this});if(this.collapsible||this.floatable){c.collapseEl="el";c.slideAnchor=this.getSlideAnchor()}if(c.tools&&c.tools.toggle){c.tools.toggle.addClass("x-tool-collapse-"+d);c.tools.toggle.addClassOnOver("x-tool-collapse-"+d+"-over")}}},getCollapsedEl:function(){if(!this.collapsedEl){if(!this.toolTemplate){var b=new Ext.Template('<div class="x-tool x-tool-{id}"> </div>');b.disableFormats=true;b.compile();Ext.layout.BorderLayout.Region.prototype.toolTemplate=b}this.collapsedEl=this.targetEl.createChild({cls:"x-layout-collapsed x-layout-collapsed-"+this.position,id:this.panel.id+"-xcollapsed"});this.collapsedEl.enableDisplayMode("block");if(this.collapseMode=="mini"){this.collapsedEl.addClass("x-layout-cmini-"+this.position);this.miniCollapsedEl=this.collapsedEl.createChild({cls:"x-layout-mini x-layout-mini-"+this.position,html:" "});this.miniCollapsedEl.addClassOnOver("x-layout-mini-over");this.collapsedEl.addClassOnOver("x-layout-collapsed-over");this.collapsedEl.on("click",this.onExpandClick,this,{stopEvent:true})}else{if(this.collapsible!==false&&!this.hideCollapseTool){var a=this.expandToolEl=this.toolTemplate.append(this.collapsedEl.dom,{id:"expand-"+this.position},true);a.addClassOnOver("x-tool-expand-"+this.position+"-over");a.on("click",this.onExpandClick,this,{stopEvent:true})}if(this.floatable!==false||this.titleCollapse){this.collapsedEl.addClassOnOver("x-layout-collapsed-over");this.collapsedEl.on("click",this[this.floatable?"collapseClick":"onExpandClick"],this)}}}return this.collapsedEl},onExpandClick:function(a){if(this.isSlid){this.panel.expand(false)}else{this.panel.expand()}},onCollapseClick:function(a){this.panel.collapse()},beforeCollapse:function(c,a){this.lastAnim=a;if(this.splitEl){this.splitEl.hide()}this.getCollapsedEl().show();var b=this.panel.getEl();this.originalZIndex=b.getStyle("z-index");b.setStyle("z-index",100);this.isCollapsed=true;this.layout.layout()},onCollapse:function(a){this.panel.el.setStyle("z-index",1);if(this.lastAnim===false||this.panel.animCollapse===false){this.getCollapsedEl().dom.style.visibility="visible"}else{this.getCollapsedEl().slideIn(this.panel.slideAnchor,{duration:0.2})}this.state.collapsed=true;this.panel.saveState()},beforeExpand:function(a){if(this.isSlid){this.afterSlideIn()}var b=this.getCollapsedEl();this.el.show();if(this.position=="east"||this.position=="west"){this.panel.setSize(undefined,b.getHeight())}else{this.panel.setSize(b.getWidth(),undefined)}b.hide();b.dom.style.visibility="hidden";this.panel.el.setStyle("z-index",this.floatingZIndex)},onExpand:function(){this.isCollapsed=false;if(this.splitEl){this.splitEl.show()}this.layout.layout();this.panel.el.setStyle("z-index",this.originalZIndex);this.state.collapsed=false;this.panel.saveState()},collapseClick:function(a){if(this.isSlid){a.stopPropagation();this.slideIn()}else{a.stopPropagation();this.slideOut()}},onHide:function(){if(this.isCollapsed){this.getCollapsedEl().hide()}else{if(this.splitEl){this.splitEl.hide()}}},onShow:function(){if(this.isCollapsed){this.getCollapsedEl().show()}else{if(this.splitEl){this.splitEl.show()}}},isVisible:function(){return !this.panel.hidden},getMargins:function(){return this.isCollapsed&&this.cmargins?this.cmargins:this.margins},getSize:function(){return this.isCollapsed?this.getCollapsedEl().getSize():this.panel.getSize()},setPanel:function(a){this.panel=a},getMinWidth:function(){return this.minWidth},getMinHeight:function(){return this.minHeight},applyLayoutCollapsed:function(a){var b=this.getCollapsedEl();b.setLeftTop(a.x,a.y);b.setSize(a.width,a.height)},applyLayout:function(a){if(this.isCollapsed){this.applyLayoutCollapsed(a)}else{this.panel.setPosition(a.x,a.y);this.panel.setSize(a.width,a.height)}},beforeSlide:function(){this.panel.beforeEffect()},afterSlide:function(){this.panel.afterEffect()},initAutoHide:function(){if(this.autoHide!==false){if(!this.autoHideHd){this.autoHideSlideTask=new Ext.util.DelayedTask(this.slideIn,this);this.autoHideHd={mouseout:function(a){if(!a.within(this.el,true)){this.autoHideSlideTask.delay(500)}},mouseover:function(a){this.autoHideSlideTask.cancel()},scope:this}}this.el.on(this.autoHideHd);this.collapsedEl.on(this.autoHideHd)}},clearAutoHide:function(){if(this.autoHide!==false){this.el.un("mouseout",this.autoHideHd.mouseout);this.el.un("mouseover",this.autoHideHd.mouseover);this.collapsedEl.un("mouseout",this.autoHideHd.mouseout);this.collapsedEl.un("mouseover",this.autoHideHd.mouseover)}},clearMonitor:function(){Ext.getDoc().un("click",this.slideInIf,this)},slideOut:function(){if(this.isSlid||this.el.hasActiveFx()){return}this.isSlid=true;var b=this.panel.tools,c,a;if(b&&b.toggle){b.toggle.hide()}this.el.show();a=this.panel.collapsed;this.panel.collapsed=false;if(this.position=="east"||this.position=="west"){c=this.panel.deferHeight;this.panel.deferHeight=false;this.panel.setSize(undefined,this.collapsedEl.getHeight());this.panel.deferHeight=c}else{this.panel.setSize(this.collapsedEl.getWidth(),undefined)}this.panel.collapsed=a;this.restoreLT=[this.el.dom.style.left,this.el.dom.style.top];this.el.alignTo(this.collapsedEl,this.getCollapseAnchor());this.el.setStyle("z-index",this.floatingZIndex+2);this.panel.el.replaceClass("x-panel-collapsed","x-panel-floating");if(this.animFloat!==false){this.beforeSlide();this.el.slideIn(this.getSlideAnchor(),{callback:function(){this.afterSlide();this.initAutoHide();Ext.getDoc().on("click",this.slideInIf,this)},scope:this,block:true})}else{this.initAutoHide();Ext.getDoc().on("click",this.slideInIf,this)}},afterSlideIn:function(){this.clearAutoHide();this.isSlid=false;this.clearMonitor();this.el.setStyle("z-index","");this.panel.el.replaceClass("x-panel-floating","x-panel-collapsed");this.el.dom.style.left=this.restoreLT[0];this.el.dom.style.top=this.restoreLT[1];var a=this.panel.tools;if(a&&a.toggle){a.toggle.show()}},slideIn:function(a){if(!this.isSlid||this.el.hasActiveFx()){Ext.callback(a);return}this.isSlid=false;if(this.animFloat!==false){this.beforeSlide();this.el.slideOut(this.getSlideAnchor(),{callback:function(){this.el.hide();this.afterSlide();this.afterSlideIn();Ext.callback(a)},scope:this,block:true})}else{this.el.hide();this.afterSlideIn()}},slideInIf:function(a){if(!a.within(this.el)){this.slideIn()}},anchors:{west:"left",east:"right",north:"top",south:"bottom"},sanchors:{west:"l",east:"r",north:"t",south:"b"},canchors:{west:"tl-tr",east:"tr-tl",north:"tl-bl",south:"bl-tl"},getAnchor:function(){return this.anchors[this.position]},getCollapseAnchor:function(){return this.canchors[this.position]},getSlideAnchor:function(){return this.sanchors[this.position]},getAlignAdj:function(){var a=this.cmargins;switch(this.position){case"west":return[0,0];break;case"east":return[0,0];break;case"north":return[0,0];break;case"south":return[0,0];break}},getExpandAdj:function(){var b=this.collapsedEl,a=this.cmargins;switch(this.position){case"west":return[-(a.right+b.getWidth()+a.left),0];break;case"east":return[a.right+b.getWidth()+a.left,0];break;case"north":return[0,-(a.top+a.bottom+b.getHeight())];break;case"south":return[0,a.top+a.bottom+b.getHeight()];break}},destroy:function(){if(this.autoHideSlideTask&&this.autoHideSlideTask.cancel){this.autoHideSlideTask.cancel()}Ext.destroyMembers(this,"miniCollapsedEl","collapsedEl","expandToolEl")}};Ext.layout.BorderLayout.SplitRegion=function(b,a,c){Ext.layout.BorderLayout.SplitRegion.superclass.constructor.call(this,b,a,c);this.applyLayout=this.applyFns[c]};Ext.extend(Ext.layout.BorderLayout.SplitRegion,Ext.layout.BorderLayout.Region,{splitTip:"Drag to resize.",collapsibleSplitTip:"Drag to resize. Double click to hide.",useSplitTips:false,splitSettings:{north:{orientation:Ext.SplitBar.VERTICAL,placement:Ext.SplitBar.TOP,maxFn:"getVMaxSize",minProp:"minHeight",maxProp:"maxHeight"},south:{orientation:Ext.SplitBar.VERTICAL,placement:Ext.SplitBar.BOTTOM,maxFn:"getVMaxSize",minProp:"minHeight",maxProp:"maxHeight"},east:{orientation:Ext.SplitBar.HORIZONTAL,placement:Ext.SplitBar.RIGHT,maxFn:"getHMaxSize",minProp:"minWidth",maxProp:"maxWidth"},west:{orientation:Ext.SplitBar.HORIZONTAL,placement:Ext.SplitBar.LEFT,maxFn:"getHMaxSize",minProp:"minWidth",maxProp:"maxWidth"}},applyFns:{west:function(c){if(this.isCollapsed){return this.applyLayoutCollapsed(c)}var d=this.splitEl.dom,b=d.style;this.panel.setPosition(c.x,c.y);var a=d.offsetWidth;b.left=(c.x+c.width-a)+"px";b.top=(c.y)+"px";b.height=Math.max(0,c.height)+"px";this.panel.setSize(c.width-a,c.height)},east:function(c){if(this.isCollapsed){return this.applyLayoutCollapsed(c)}var d=this.splitEl.dom,b=d.style;var a=d.offsetWidth;this.panel.setPosition(c.x+a,c.y);b.left=(c.x)+"px";b.top=(c.y)+"px";b.height=Math.max(0,c.height)+"px";this.panel.setSize(c.width-a,c.height)},north:function(c){if(this.isCollapsed){return this.applyLayoutCollapsed(c)}var d=this.splitEl.dom,b=d.style;var a=d.offsetHeight;this.panel.setPosition(c.x,c.y);b.left=(c.x)+"px";b.top=(c.y+c.height-a)+"px";b.width=Math.max(0,c.width)+"px";this.panel.setSize(c.width,c.height-a)},south:function(c){if(this.isCollapsed){return this.applyLayoutCollapsed(c)}var d=this.splitEl.dom,b=d.style;var a=d.offsetHeight;this.panel.setPosition(c.x,c.y+a);b.left=(c.x)+"px";b.top=(c.y)+"px";b.width=Math.max(0,c.width)+"px";this.panel.setSize(c.width,c.height-a)}},render:function(a,c){Ext.layout.BorderLayout.SplitRegion.superclass.render.call(this,a,c);var d=this.position;this.splitEl=a.createChild({cls:"x-layout-split x-layout-split-"+d,html:" ",id:this.panel.id+"-xsplit"});if(this.collapseMode=="mini"){this.miniSplitEl=this.splitEl.createChild({cls:"x-layout-mini x-layout-mini-"+d,html:" "});this.miniSplitEl.addClassOnOver("x-layout-mini-over");this.miniSplitEl.on("click",this.onCollapseClick,this,{stopEvent:true})}var b=this.splitSettings[d];this.split=new Ext.SplitBar(this.splitEl.dom,c.el,b.orientation);this.split.tickSize=this.tickSize;this.split.placement=b.placement;this.split.getMaximumSize=this[b.maxFn].createDelegate(this);this.split.minSize=this.minSize||this[b.minProp];this.split.on("beforeapply",this.onSplitMove,this);this.split.useShim=this.useShim===true;this.maxSize=this.maxSize||this[b.maxProp];if(c.hidden){this.splitEl.hide()}if(this.useSplitTips){this.splitEl.dom.title=this.collapsible?this.collapsibleSplitTip:this.splitTip}if(this.collapsible){this.splitEl.on("dblclick",this.onCollapseClick,this)}},getSize:function(){if(this.isCollapsed){return this.collapsedEl.getSize()}var a=this.panel.getSize();if(this.position=="north"||this.position=="south"){a.height+=this.splitEl.dom.offsetHeight}else{a.width+=this.splitEl.dom.offsetWidth}return a},getHMaxSize:function(){var b=this.maxSize||10000;var a=this.layout.center;return Math.min(b,(this.el.getWidth()+a.el.getWidth())-a.getMinWidth())},getVMaxSize:function(){var b=this.maxSize||10000;var a=this.layout.center;return Math.min(b,(this.el.getHeight()+a.el.getHeight())-a.getMinHeight())},onSplitMove:function(b,a){var c=this.panel.getSize();this.lastSplitSize=a;if(this.position=="north"||this.position=="south"){this.panel.setSize(c.width,a);this.state.height=a}else{this.panel.setSize(a,c.height);this.state.width=a}this.layout.layout();this.panel.saveState();return false},getSplitBar:function(){return this.split},destroy:function(){Ext.destroy(this.miniSplitEl,this.split,this.splitEl);Ext.layout.BorderLayout.SplitRegion.superclass.destroy.call(this)}});Ext.Container.LAYOUTS.border=Ext.layout.BorderLayout;Ext.layout.FormLayout=Ext.extend(Ext.layout.AnchorLayout,{labelSeparator:":",trackLabels:true,type:"form",onRemove:function(d){Ext.layout.FormLayout.superclass.onRemove.call(this,d);if(this.trackLabels){d.un("show",this.onFieldShow,this);d.un("hide",this.onFieldHide,this)}var b=d.getPositionEl(),a=d.getItemCt&&d.getItemCt();if(d.rendered&&a){if(b&&b.dom){b.insertAfter(a)}Ext.destroy(a);Ext.destroyMembers(d,"label","itemCt");if(d.customItemCt){Ext.destroyMembers(d,"getItemCt","customItemCt")}}},setContainer:function(a){Ext.layout.FormLayout.superclass.setContainer.call(this,a);if(a.labelAlign){a.addClass("x-form-label-"+a.labelAlign)}if(a.hideLabels){Ext.apply(this,{labelStyle:"display:none",elementStyle:"padding-left:0;",labelAdjust:0})}else{this.labelSeparator=Ext.isDefined(a.labelSeparator)?a.labelSeparator:this.labelSeparator;a.labelWidth=a.labelWidth||100;if(Ext.isNumber(a.labelWidth)){var b=Ext.isNumber(a.labelPad)?a.labelPad:5;Ext.apply(this,{labelAdjust:a.labelWidth+b,labelStyle:"width:"+a.labelWidth+"px;",elementStyle:"padding-left:"+(a.labelWidth+b)+"px"})}if(a.labelAlign=="top"){Ext.apply(this,{labelStyle:"width:auto;",labelAdjust:0,elementStyle:"padding-left:0;"})}}},isHide:function(a){return a.hideLabel||this.container.hideLabels},onFieldShow:function(a){a.getItemCt().removeClass("x-hide-"+a.hideMode);if(a.isComposite){a.doLayout()}},onFieldHide:function(a){a.getItemCt().addClass("x-hide-"+a.hideMode)},getLabelStyle:function(e){var b="",c=[this.labelStyle,e];for(var d=0,a=c.length;d<a;++d){if(c[d]){b+=c[d];if(b.substr(-1,1)!=";"){b+=";"}}}return b},renderItem:function(e,a,d){if(e&&(e.isFormField||e.fieldLabel)&&e.inputType!="hidden"){var b=this.getTemplateArgs(e);if(Ext.isNumber(a)){a=d.dom.childNodes[a]||null}if(a){e.itemCt=this.fieldTpl.insertBefore(a,b,true)}else{e.itemCt=this.fieldTpl.append(d,b,true)}if(!e.getItemCt){Ext.apply(e,{getItemCt:function(){return e.itemCt},customItemCt:true})}e.label=e.getItemCt().child("label.x-form-item-label");if(!e.rendered){e.render("x-form-el-"+e.id)}else{if(!this.isValidParent(e,d)){Ext.fly("x-form-el-"+e.id).appendChild(e.getPositionEl())}}if(this.trackLabels){if(e.hidden){this.onFieldHide(e)}e.on({scope:this,show:this.onFieldShow,hide:this.onFieldHide})}this.configureItem(e)}else{Ext.layout.FormLayout.superclass.renderItem.apply(this,arguments)}},getTemplateArgs:function(b){var a=!b.fieldLabel||b.hideLabel;return{id:b.id,label:b.fieldLabel,itemCls:(b.itemCls||this.container.itemCls||"")+(b.hideLabel?" x-hide-label":""),clearCls:b.clearCls||"x-form-clear-left",labelStyle:this.getLabelStyle(b.labelStyle),elementStyle:this.elementStyle||"",labelSeparator:a?"":(Ext.isDefined(b.labelSeparator)?b.labelSeparator:this.labelSeparator)}},adjustWidthAnchor:function(a,d){if(d.label&&!this.isHide(d)&&(this.container.labelAlign!="top")){var b=Ext.isIE6||(Ext.isIE&&!Ext.isStrict);return a-this.labelAdjust+(b?-3:0)}return a},adjustHeightAnchor:function(a,b){if(b.label&&!this.isHide(b)&&(this.container.labelAlign=="top")){return a-b.label.getHeight()}return a},isValidParent:function(b,a){return a&&this.container.getEl().contains(b.getPositionEl())}});Ext.Container.LAYOUTS.form=Ext.layout.FormLayout;Ext.layout.AccordionLayout=Ext.extend(Ext.layout.FitLayout,{fill:true,autoWidth:true,titleCollapse:true,hideCollapseTool:false,collapseFirst:false,animate:false,sequence:false,activeOnTop:false,type:"accordion",renderItem:function(a){if(this.animate===false){a.animCollapse=false}a.collapsible=true;if(this.autoWidth){a.autoWidth=true}if(this.titleCollapse){a.titleCollapse=true}if(this.hideCollapseTool){a.hideCollapseTool=true}if(this.collapseFirst!==undefined){a.collapseFirst=this.collapseFirst}if(!this.activeItem&&!a.collapsed){this.setActiveItem(a,true)}else{if(this.activeItem&&this.activeItem!=a){a.collapsed=true}}Ext.layout.AccordionLayout.superclass.renderItem.apply(this,arguments);a.header.addClass("x-accordion-hd");a.on("beforeexpand",this.beforeExpand,this)},onRemove:function(a){Ext.layout.AccordionLayout.superclass.onRemove.call(this,a);if(a.rendered){a.header.removeClass("x-accordion-hd")}a.un("beforeexpand",this.beforeExpand,this)},beforeExpand:function(c,b){var a=this.activeItem;if(a){if(this.sequence){delete this.activeItem;if(!a.collapsed){a.collapse({callback:function(){c.expand(b||true)},scope:this});return false}}else{a.collapse(this.animate)}}this.setActive(c);if(this.activeOnTop){c.el.dom.parentNode.insertBefore(c.el.dom,c.el.dom.parentNode.firstChild)}this.layout()},setItemSize:function(g,e){if(this.fill&&g){var d=0,c,b=this.getRenderedItems(this.container),a=b.length,h;for(c=0;c<a;c++){if((h=b[c])!=g&&!h.hidden){d+=h.header.getHeight()}}e.height-=d;g.setSize(e)}},setActiveItem:function(a){this.setActive(a,true)},setActive:function(c,b){var a=this.activeItem;c=this.container.getComponent(c);if(a!=c){if(c.rendered&&c.collapsed&&b){c.expand()}else{if(a){a.fireEvent("deactivate",a)}this.activeItem=c;c.fireEvent("activate",c)}}}});Ext.Container.LAYOUTS.accordion=Ext.layout.AccordionLayout;Ext.layout.Accordion=Ext.layout.AccordionLayout;Ext.layout.TableLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:false,type:"table",targetCls:"x-table-layout-ct",tableAttrs:null,setContainer:function(a){Ext.layout.TableLayout.superclass.setContainer.call(this,a);this.currentRow=0;this.currentColumn=0;this.cells=[]},onLayout:function(d,g){var e=d.items.items,a=e.length,h,b;if(!this.table){g.addClass("x-table-layout-ct");this.table=g.createChild(Ext.apply({tag:"table",cls:"x-table-layout",cellspacing:0,cn:{tag:"tbody"}},this.tableAttrs),null,true)}this.renderAll(d,g)},getRow:function(a){var b=this.table.tBodies[0].childNodes[a];if(!b){b=document.createElement("tr");this.table.tBodies[0].appendChild(b)}return b},getNextCell:function(k){var a=this.getNextNonSpan(this.currentColumn,this.currentRow);var g=this.currentColumn=a[0],e=this.currentRow=a[1];for(var i=e;i<e+(k.rowspan||1);i++){if(!this.cells[i]){this.cells[i]=[]}for(var d=g;d<g+(k.colspan||1);d++){this.cells[i][d]=true}}var h=document.createElement("td");if(k.cellId){h.id=k.cellId}var b="x-table-layout-cell";if(k.cellCls){b+=" "+k.cellCls}h.className=b;if(k.colspan){h.colSpan=k.colspan}if(k.rowspan){h.rowSpan=k.rowspan}this.getRow(e).appendChild(h);return h},getNextNonSpan:function(a,c){var b=this.columns;while((b&&a>=b)||(this.cells[c]&&this.cells[c][a])){if(b&&a>=b){c++;a=0}else{a++}}return[a,c]},renderItem:function(e,a,d){if(!this.table){this.table=d.createChild(Ext.apply({tag:"table",cls:"x-table-layout",cellspacing:0,cn:{tag:"tbody"}},this.tableAttrs),null,true)}if(e&&!e.rendered){e.render(this.getNextCell(e));this.configureItem(e)}else{if(e&&!this.isValidParent(e,d)){var b=this.getNextCell(e);b.insertBefore(e.getPositionEl().dom,null);e.container=Ext.get(b);this.configureItem(e)}}},isValidParent:function(b,a){return b.getPositionEl().up("table",5).dom.parentNode===(a.dom||a)},destroy:function(){delete this.table;Ext.layout.TableLayout.superclass.destroy.call(this)}});Ext.Container.LAYOUTS.table=Ext.layout.TableLayout;Ext.layout.AbsoluteLayout=Ext.extend(Ext.layout.AnchorLayout,{extraCls:"x-abs-layout-item",type:"absolute",onLayout:function(a,b){b.position();this.paddingLeft=b.getPadding("l");this.paddingTop=b.getPadding("t");Ext.layout.AbsoluteLayout.superclass.onLayout.call(this,a,b)},adjustWidthAnchor:function(b,a){return b?b-a.getPosition(true)[0]+this.paddingLeft:b},adjustHeightAnchor:function(b,a){return b?b-a.getPosition(true)[1]+this.paddingTop:b}});Ext.Container.LAYOUTS.absolute=Ext.layout.AbsoluteLayout;Ext.layout.BoxLayout=Ext.extend(Ext.layout.ContainerLayout,{defaultMargins:{left:0,top:0,right:0,bottom:0},padding:"0",pack:"start",monitorResize:true,type:"box",scrollOffset:0,extraCls:"x-box-item",targetCls:"x-box-layout-ct",innerCls:"x-box-inner",constructor:function(a){Ext.layout.BoxLayout.superclass.constructor.call(this,a);if(Ext.isString(this.defaultMargins)){this.defaultMargins=this.parseMargins(this.defaultMargins)}var d=this.overflowHandler;if(typeof d=="string"){d={type:d}}var c="none";if(d&&d.type!=undefined){c=d.type}var b=Ext.layout.boxOverflow[c];if(b[this.type]){b=b[this.type]}this.overflowHandler=new b(this,d)},onLayout:function(b,h){Ext.layout.BoxLayout.superclass.onLayout.call(this,b,h);var d=this.getLayoutTargetSize(),i=this.getVisibleItems(b),c=this.calculateChildBoxes(i,d),g=c.boxes,k=c.meta;if(d.width>0){var l=this.overflowHandler,a=k.tooNarrow?"handleOverflow":"clearOverflow";var e=l[a](c,d);if(e){if(e.targetSize){d=e.targetSize}if(e.recalculate){i=this.getVisibleItems(b);c=this.calculateChildBoxes(i,d);g=c.boxes}}}this.layoutTargetLastSize=d;this.childBoxCache=c;this.updateInnerCtSize(d,c);this.updateChildBoxes(g);this.handleTargetOverflow(d,b,h)},updateChildBoxes:function(c){for(var b=0,e=c.length;b<e;b++){var d=c[b],a=d.component;if(d.dirtySize){a.setSize(d.width,d.height)}if(isNaN(d.left)||isNaN(d.top)){continue}a.setPosition(d.left,d.top)}},updateInnerCtSize:function(c,h){var i=this.align,g=this.padding,e=c.width,a=c.height;if(this.type=="hbox"){var b=e,d=h.meta.maxHeight+g.top+g.bottom;if(i=="stretch"){d=a}else{if(i=="middle"){d=Math.max(a,d)}}}else{var d=a,b=h.meta.maxWidth+g.left+g.right;if(i=="stretch"){b=e}else{if(i=="center"){b=Math.max(e,b)}}}this.innerCt.setSize(b||undefined,d||undefined)},handleTargetOverflow:function(d,a,c){var e=c.getStyle("overflow");if(e&&e!="hidden"&&!this.adjustmentPass){var b=this.getLayoutTargetSize();if(b.width!=d.width||b.height!=d.height){this.adjustmentPass=true;this.onLayout(a,c)}}delete this.adjustmentPass},isValidParent:function(b,a){return this.innerCt&&b.getPositionEl().dom.parentNode==this.innerCt.dom},getVisibleItems:function(g){var g=g||this.container,e=g.getLayoutTarget(),h=g.items.items,a=h.length,d,k,b=[];for(d=0;d<a;d++){if((k=h[d]).rendered&&this.isValidParent(k,e)&&k.hidden!==true&&k.collapsed!==true&&k.shouldLayout!==false){b.push(k)}}return b},renderAll:function(a,b){if(!this.innerCt){this.innerCt=b.createChild({cls:this.innerCls});this.padding=this.parseMargins(this.padding)}Ext.layout.BoxLayout.superclass.renderAll.call(this,a,this.innerCt)},getLayoutTargetSize:function(){var b=this.container.getLayoutTarget(),a;if(b){a=b.getViewSize();if(Ext.isIE&&Ext.isStrict&&a.width==0){a=b.getStyleSize()}a.width-=b.getPadding("lr");a.height-=b.getPadding("tb")}return a},renderItem:function(a){if(Ext.isString(a.margins)){a.margins=this.parseMargins(a.margins)}else{if(!a.margins){a.margins=this.defaultMargins}}Ext.layout.BoxLayout.superclass.renderItem.apply(this,arguments)},destroy:function(){Ext.destroy(this.overflowHandler);Ext.layout.BoxLayout.superclass.destroy.apply(this,arguments)}});Ext.ns("Ext.layout.boxOverflow");Ext.layout.boxOverflow.None=Ext.extend(Object,{constructor:function(b,a){this.layout=b;Ext.apply(this,a||{})},handleOverflow:Ext.emptyFn,clearOverflow:Ext.emptyFn});Ext.layout.boxOverflow.none=Ext.layout.boxOverflow.None;Ext.layout.boxOverflow.Menu=Ext.extend(Ext.layout.boxOverflow.None,{afterCls:"x-strip-right",noItemsMenuText:'<div class="x-toolbar-no-items">(None)</div>',constructor:function(a){Ext.layout.boxOverflow.Menu.superclass.constructor.apply(this,arguments);this.menuItems=[]},createInnerElements:function(){if(!this.afterCt){this.afterCt=this.layout.innerCt.insertSibling({cls:this.afterCls},"before")}},clearOverflow:function(a,g){var e=g.width+(this.afterCt?this.afterCt.getWidth():0),b=this.menuItems;this.hideTrigger();for(var c=0,d=b.length;c<d;c++){b.pop().component.show()}return{targetSize:{height:g.height,width:e}}},showTrigger:function(){this.createMenu();this.menuTrigger.show()},hideTrigger:function(){if(this.menuTrigger!=undefined){this.menuTrigger.hide()}},beforeMenuShow:function(h){var b=this.menuItems,a=b.length,g,e;var c=function(k,i){return k.isXType("buttongroup")&&!(i instanceof Ext.Toolbar.Separator)};this.clearMenu();h.removeAll();for(var d=0;d<a;d++){g=b[d].component;if(e&&(c(g,e)||c(e,g))){h.add("-")}this.addComponentToMenu(h,g);e=g}if(h.items.length<1){h.add(this.noItemsMenuText)}},createMenuConfig:function(c,a){var b=Ext.apply({},c.initialConfig),d=c.toggleGroup;Ext.copyTo(b,c,["iconCls","icon","itemId","disabled","handler","scope","menu"]);Ext.apply(b,{text:c.overflowText||c.text,hideOnClick:a});if(d||c.enableToggle){Ext.apply(b,{group:d,checked:c.pressed,listeners:{checkchange:function(g,e){c.toggle(e)}}})}delete b.ownerCt;delete b.xtype;delete b.id;return b},addComponentToMenu:function(b,a){if(a instanceof Ext.Toolbar.Separator){b.add("-")}else{if(Ext.isFunction(a.isXType)){if(a.isXType("splitbutton")){b.add(this.createMenuConfig(a,true))}else{if(a.isXType("button")){b.add(this.createMenuConfig(a,!a.menu))}else{if(a.isXType("buttongroup")){a.items.each(function(c){this.addComponentToMenu(b,c)},this)}}}}}},clearMenu:function(){var a=this.moreMenu;if(a&&a.items){a.items.each(function(b){delete b.menu})}},createMenu:function(){if(!this.menuTrigger){this.createInnerElements();this.menu=new Ext.menu.Menu({ownerCt:this.layout.container,listeners:{scope:this,beforeshow:this.beforeMenuShow}});this.menuTrigger=new Ext.Button({iconCls:"x-toolbar-more-icon",cls:"x-toolbar-more",menu:this.menu,renderTo:this.afterCt})}},destroy:function(){Ext.destroy(this.menu,this.menuTrigger)}});Ext.layout.boxOverflow.menu=Ext.layout.boxOverflow.Menu;Ext.layout.boxOverflow.HorizontalMenu=Ext.extend(Ext.layout.boxOverflow.Menu,{constructor:function(){Ext.layout.boxOverflow.HorizontalMenu.superclass.constructor.apply(this,arguments);var c=this,b=c.layout,a=b.calculateChildBoxes;b.calculateChildBoxes=function(d,i){var m=a.apply(b,arguments),l=m.meta,e=c.menuItems;var k=0;for(var g=0,h=e.length;g<h;g++){k+=e[g].width}l.minimumWidth+=k;l.tooNarrow=l.minimumWidth>i.width;return m}},handleOverflow:function(d,h){this.showTrigger();var l=h.width-this.afterCt.getWidth(),m=d.boxes,e=0,s=false;for(var p=0,c=m.length;p<c;p++){e+=m[p].width}var a=l-e,g=0;for(var p=0,c=this.menuItems.length;p<c;p++){var o=this.menuItems[p],n=o.component,b=o.width;if(b<a){n.show();a-=b;g++;s=true}else{break}}if(s){this.menuItems=this.menuItems.slice(g)}else{for(var k=m.length-1;k>=0;k--){var r=m[k].component,q=m[k].left+m[k].width;if(q>=l){this.menuItems.unshift({component:r,width:m[k].width});r.hide()}else{break}}}if(this.menuItems.length==0){this.hideTrigger()}return{targetSize:{height:h.height,width:l},recalculate:s}}});Ext.layout.boxOverflow.menu.hbox=Ext.layout.boxOverflow.HorizontalMenu;Ext.layout.boxOverflow.Scroller=Ext.extend(Ext.layout.boxOverflow.None,{animateScroll:true,scrollIncrement:100,wheelIncrement:3,scrollRepeatInterval:400,scrollDuration:0.4,beforeCls:"x-strip-left",afterCls:"x-strip-right",scrollerCls:"x-strip-scroller",beforeScrollerCls:"x-strip-scroller-left",afterScrollerCls:"x-strip-scroller-right",createWheelListener:function(){this.layout.innerCt.on({scope:this,mousewheel:function(a){a.stopEvent();this.scrollBy(a.getWheelDelta()*this.wheelIncrement*-1,false)}})},handleOverflow:function(a,b){this.createInnerElements();this.showScrollers()},clearOverflow:function(){this.hideScrollers()},showScrollers:function(){this.createScrollers();this.beforeScroller.show();this.afterScroller.show();this.updateScrollButtons()},hideScrollers:function(){if(this.beforeScroller!=undefined){this.beforeScroller.hide();this.afterScroller.hide()}},createScrollers:function(){if(!this.beforeScroller&&!this.afterScroller){var a=this.beforeCt.createChild({cls:String.format("{0} {1} ",this.scrollerCls,this.beforeScrollerCls)});var b=this.afterCt.createChild({cls:String.format("{0} {1}",this.scrollerCls,this.afterScrollerCls)});a.addClassOnOver(this.beforeScrollerCls+"-hover");b.addClassOnOver(this.afterScrollerCls+"-hover");a.setVisibilityMode(Ext.Element.DISPLAY);b.setVisibilityMode(Ext.Element.DISPLAY);this.beforeRepeater=new Ext.util.ClickRepeater(a,{interval:this.scrollRepeatInterval,handler:this.scrollLeft,scope:this});this.afterRepeater=new Ext.util.ClickRepeater(b,{interval:this.scrollRepeatInterval,handler:this.scrollRight,scope:this});this.beforeScroller=a;this.afterScroller=b}},destroy:function(){Ext.destroy(this.beforeScroller,this.afterScroller,this.beforeRepeater,this.afterRepeater,this.beforeCt,this.afterCt)},scrollBy:function(b,a){this.scrollTo(this.getScrollPosition()+b,a)},getItem:function(a){if(Ext.isString(a)){a=Ext.getCmp(a)}else{if(Ext.isNumber(a)){a=this.items[a]}}return a},getScrollAnim:function(){return{duration:this.scrollDuration,callback:this.updateScrollButtons,scope:this}},updateScrollButtons:function(){if(this.beforeScroller==undefined||this.afterScroller==undefined){return}var d=this.atExtremeBefore()?"addClass":"removeClass",c=this.atExtremeAfter()?"addClass":"removeClass",a=this.beforeScrollerCls+"-disabled",b=this.afterScrollerCls+"-disabled";this.beforeScroller[d](a);this.afterScroller[c](b);this.scrolling=false},atExtremeBefore:function(){return this.getScrollPosition()===0},scrollLeft:function(a){this.scrollBy(-this.scrollIncrement,a)},scrollRight:function(a){this.scrollBy(this.scrollIncrement,a)},scrollToItem:function(d,b){d=this.getItem(d);if(d!=undefined){var a=this.getItemVisibility(d);if(!a.fullyVisible){var c=d.getBox(true,true),e=c.x;if(a.hiddenRight){e-=(this.layout.innerCt.getWidth()-c.width)}this.scrollTo(e,b)}}},getItemVisibility:function(e){var d=this.getItem(e).getBox(true,true),a=d.x,c=d.x+d.width,g=this.getScrollPosition(),b=this.layout.innerCt.getWidth()+g;return{hiddenLeft:a<g,hiddenRight:c>b,fullyVisible:a>g&&c<b}}});Ext.layout.boxOverflow.scroller=Ext.layout.boxOverflow.Scroller;Ext.layout.boxOverflow.VerticalScroller=Ext.extend(Ext.layout.boxOverflow.Scroller,{scrollIncrement:75,wheelIncrement:2,handleOverflow:function(a,b){Ext.layout.boxOverflow.VerticalScroller.superclass.handleOverflow.apply(this,arguments);return{targetSize:{height:b.height-(this.beforeCt.getHeight()+this.afterCt.getHeight()),width:b.width}}},createInnerElements:function(){var a=this.layout.innerCt;if(!this.beforeCt){this.beforeCt=a.insertSibling({cls:this.beforeCls},"before");this.afterCt=a.insertSibling({cls:this.afterCls},"after");this.createWheelListener()}},scrollTo:function(a,b){var d=this.getScrollPosition(),c=a.constrain(0,this.getMaxScrollBottom());if(c!=d&&!this.scrolling){if(b==undefined){b=this.animateScroll}this.layout.innerCt.scrollTo("top",c,b?this.getScrollAnim():false);if(b){this.scrolling=true}else{this.scrolling=false;this.updateScrollButtons()}}},getScrollPosition:function(){return parseInt(this.layout.innerCt.dom.scrollTop,10)||0},getMaxScrollBottom:function(){return this.layout.innerCt.dom.scrollHeight-this.layout.innerCt.getHeight()},atExtremeAfter:function(){return this.getScrollPosition()>=this.getMaxScrollBottom()}});Ext.layout.boxOverflow.scroller.vbox=Ext.layout.boxOverflow.VerticalScroller;Ext.layout.boxOverflow.HorizontalScroller=Ext.extend(Ext.layout.boxOverflow.Scroller,{handleOverflow:function(a,b){Ext.layout.boxOverflow.HorizontalScroller.superclass.handleOverflow.apply(this,arguments);return{targetSize:{height:b.height,width:b.width-(this.beforeCt.getWidth()+this.afterCt.getWidth())}}},createInnerElements:function(){var a=this.layout.innerCt;if(!this.beforeCt){this.afterCt=a.insertSibling({cls:this.afterCls},"before");this.beforeCt=a.insertSibling({cls:this.beforeCls},"before");this.createWheelListener()}},scrollTo:function(a,b){var d=this.getScrollPosition(),c=a.constrain(0,this.getMaxScrollRight());if(c!=d&&!this.scrolling){if(b==undefined){b=this.animateScroll}this.layout.innerCt.scrollTo("left",c,b?this.getScrollAnim():false);if(b){this.scrolling=true}else{this.scrolling=false;this.updateScrollButtons()}}},getScrollPosition:function(){return parseInt(this.layout.innerCt.dom.scrollLeft,10)||0},getMaxScrollRight:function(){return this.layout.innerCt.dom.scrollWidth-this.layout.innerCt.getWidth()},atExtremeAfter:function(){return this.getScrollPosition()>=this.getMaxScrollRight()}});Ext.layout.boxOverflow.scroller.hbox=Ext.layout.boxOverflow.HorizontalScroller;Ext.layout.HBoxLayout=Ext.extend(Ext.layout.BoxLayout,{align:"top",type:"hbox",calculateChildBoxes:function(s,b){var G=s.length,S=this.padding,E=S.top,V=S.left,z=E+S.bottom,P=V+S.right,a=b.width-this.scrollOffset,e=b.height,p=Math.max(0,e-z),Q=this.pack=="start",X=this.pack=="center",B=this.pack=="end",M=0,R=0,U=0,m=0,Y=0,I=[],l,K,N,W,x,k,T,J,c,y,r,O;for(T=0;T<G;T++){l=s[T];N=l.height;K=l.width;k=!l.hasLayout&&typeof l.doLayout=="function";if(typeof K!="number"){if(l.flex&&!K){U+=l.flex}else{if(!K&&k){l.doLayout()}W=l.getSize();K=W.width;N=W.height}}x=l.margins;y=x.left+x.right;M+=y+(K||0);m+=y+(l.flex?l.minWidth||0:K);Y+=y+(l.minWidth||K||0);if(typeof N!="number"){if(k){l.doLayout()}N=l.getHeight()}R=Math.max(R,N+x.top+x.bottom);I.push({component:l,height:N||undefined,width:K||undefined})}var L=m-a,q=Y>a;var o=Math.max(0,a-M-P);if(q){for(T=0;T<G;T++){I[T].width=s[T].minWidth||s[T].width||I[T].width}}else{if(L>0){var D=[];for(var F=0,w=G;F<w;F++){var C=s[F],u=C.minWidth||0;if(C.flex){I[F].width=u}else{D.push({minWidth:u,available:I[F].width-u,index:F})}}D.sort(function(Z,i){return Z.available>i.available?1:-1});for(var T=0,w=D.length;T<w;T++){var H=D[T].index;if(H==undefined){continue}var C=s[H],n=I[H],v=n.width,u=C.minWidth,d=Math.max(u,v-Math.ceil(L/(w-T))),g=v-d;I[H].width=d;L-=g}}else{var h=o,t=U;for(T=0;T<G;T++){l=s[T];J=I[T];x=l.margins;r=x.top+x.bottom;if(Q&&l.flex&&!l.width){c=Math.ceil((l.flex/t)*h);h-=c;t-=l.flex;J.width=c;J.dirtySize=true}}}}if(X){V+=o/2}else{if(B){V+=o}}for(T=0;T<G;T++){l=s[T];J=I[T];x=l.margins;V+=x.left;r=x.top+x.bottom;J.left=V;J.top=E+x.top;switch(this.align){case"stretch":O=p-r;J.height=O.constrain(l.minHeight||0,l.maxHeight||1000000);J.dirtySize=true;break;case"stretchmax":O=R-r;J.height=O.constrain(l.minHeight||0,l.maxHeight||1000000);J.dirtySize=true;break;case"middle":var A=p-J.height-r;if(A>0){J.top=E+r+(A/2)}}V+=J.width+x.right}return{boxes:I,meta:{maxHeight:R,nonFlexWidth:M,desiredWidth:m,minimumWidth:Y,shortfall:m-a,tooNarrow:q}}}});Ext.Container.LAYOUTS.hbox=Ext.layout.HBoxLayout;Ext.layout.VBoxLayout=Ext.extend(Ext.layout.BoxLayout,{align:"left",type:"vbox",calculateChildBoxes:function(q,b){var G=q.length,T=this.padding,E=T.top,W=T.left,z=E+T.bottom,Q=W+T.right,a=b.width-this.scrollOffset,d=b.height,M=Math.max(0,a-Q),R=this.pack=="start",Y=this.pack=="center",B=this.pack=="end",m=0,w=0,V=0,N=0,o=0,I=[],k,K,P,X,v,h,U,J,c,y,p,e;for(U=0;U<G;U++){k=q[U];P=k.height;K=k.width;h=!k.hasLayout&&typeof k.doLayout=="function";if(typeof P!="number"){if(k.flex&&!P){V+=k.flex}else{if(!P&&h){k.doLayout()}X=k.getSize();K=X.width;P=X.height}}v=k.margins;p=v.top+v.bottom;m+=p+(P||0);N+=p+(k.flex?k.minHeight||0:P);o+=p+(k.minHeight||P||0);if(typeof K!="number"){if(h){k.doLayout()}K=k.getWidth()}w=Math.max(w,K+v.left+v.right);I.push({component:k,height:P||undefined,width:K||undefined})}var O=N-d,n=o>d;var s=Math.max(0,(d-m-z));if(n){for(U=0,t=G;U<t;U++){I[U].height=q[U].minHeight||q[U].height||I[U].height}}else{if(O>0){var L=[];for(var F=0,t=G;F<t;F++){var C=q[F],u=C.minHeight||0;if(C.flex){I[F].height=u}else{L.push({minHeight:u,available:I[F].height-u,index:F})}}L.sort(function(Z,i){return Z.available>i.available?1:-1});for(var U=0,t=L.length;U<t;U++){var H=L[U].index;if(H==undefined){continue}var C=q[H],l=I[H],x=l.height,u=C.minHeight,D=Math.max(u,x-Math.ceil(O/(t-U))),g=x-D;I[H].height=D;O-=g}}else{var S=s,r=V;for(U=0;U<G;U++){k=q[U];J=I[U];v=k.margins;y=v.left+v.right;if(R&&k.flex&&!k.height){flexedHeight=Math.ceil((k.flex/r)*S);S-=flexedHeight;r-=k.flex;J.height=flexedHeight;J.dirtySize=true}}}}if(Y){E+=s/2}else{if(B){E+=s}}for(U=0;U<G;U++){k=q[U];J=I[U];v=k.margins;E+=v.top;y=v.left+v.right;J.left=W+v.left;J.top=E;switch(this.align){case"stretch":e=M-y;J.width=e.constrain(k.minWidth||0,k.maxWidth||1000000);J.dirtySize=true;break;case"stretchmax":e=w-y;J.width=e.constrain(k.minWidth||0,k.maxWidth||1000000);J.dirtySize=true;break;case"center":var A=M-J.width-y;if(A>0){J.left=W+y+(A/2)}}E+=J.height+v.bottom}return{boxes:I,meta:{maxWidth:w,nonFlexHeight:m,desiredHeight:N,minimumHeight:o,shortfall:N-d,tooNarrow:n}}}});Ext.Container.LAYOUTS.vbox=Ext.layout.VBoxLayout;Ext.layout.ToolbarLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,type:"toolbar",triggerWidth:18,noItemsMenuText:'<div class="x-toolbar-no-items">(None)</div>',lastOverflow:false,tableHTML:['<table cellspacing="0" class="x-toolbar-ct">',"<tbody>","<tr>",'<td class="x-toolbar-left" align="{0}">','<table cellspacing="0">',"<tbody>",'<tr class="x-toolbar-left-row"></tr>',"</tbody>","</table>","</td>",'<td class="x-toolbar-right" align="right">','<table cellspacing="0" class="x-toolbar-right-ct">',"<tbody>","<tr>","<td>",'<table cellspacing="0">',"<tbody>",'<tr class="x-toolbar-right-row"></tr>',"</tbody>","</table>","</td>","<td>",'<table cellspacing="0">',"<tbody>",'<tr class="x-toolbar-extras-row"></tr>',"</tbody>","</table>","</td>","</tr>","</tbody>","</table>","</td>","</tr>","</tbody>","</table>"].join(""),onLayout:function(e,k){if(!this.leftTr){var h=e.buttonAlign=="center"?"center":"left";k.addClass("x-toolbar-layout-ct");k.insertHtml("beforeEnd",String.format(this.tableHTML,h));this.leftTr=k.child("tr.x-toolbar-left-row",true);this.rightTr=k.child("tr.x-toolbar-right-row",true);this.extrasTr=k.child("tr.x-toolbar-extras-row",true);if(this.hiddenItem==undefined){this.hiddenItems=[]}}var l=e.buttonAlign=="right"?this.rightTr:this.leftTr,m=e.items.items,d=0;for(var b=0,g=m.length,n;b<g;b++,d++){n=m[b];if(n.isFill){l=this.rightTr;d=-1}else{if(!n.rendered){n.render(this.insertCell(n,l,d));this.configureItem(n)}else{if(!n.xtbHidden&&!this.isValidParent(n,l.childNodes[d])){var a=this.insertCell(n,l,d);a.appendChild(n.getPositionEl().dom);n.container=Ext.get(a)}}}}this.cleanup(this.leftTr);this.cleanup(this.rightTr);this.cleanup(this.extrasTr);this.fitToSize(k)},cleanup:function(b){var e=b.childNodes,a,d;for(a=e.length-1;a>=0&&(d=e[a]);a--){if(!d.firstChild){b.removeChild(d)}}},insertCell:function(e,b,a){var d=document.createElement("td");d.className="x-toolbar-cell";b.insertBefore(d,b.childNodes[a]||null);return d},hideItem:function(a){this.hiddenItems.push(a);a.xtbHidden=true;a.xtbWidth=a.getPositionEl().dom.parentNode.offsetWidth;a.hide()},unhideItem:function(a){a.show();a.xtbHidden=false;this.hiddenItems.remove(a)},getItemWidth:function(a){return a.hidden?(a.xtbWidth||0):a.getPositionEl().dom.parentNode.offsetWidth},fitToSize:function(l){if(this.container.enableOverflow===false){return}var b=l.dom.clientWidth,k=l.dom.firstChild.offsetWidth,n=b-this.triggerWidth,a=this.lastWidth||0,c=this.hiddenItems,e=c.length!=0,o=b>=a;this.lastWidth=b;if(k>b||(e&&o)){var m=this.container.items.items,h=m.length,d=0,p;for(var g=0;g<h;g++){p=m[g];if(!p.isFill){d+=this.getItemWidth(p);if(d>n){if(!(p.hidden||p.xtbHidden)){this.hideItem(p)}}else{if(p.xtbHidden){this.unhideItem(p)}}}}}e=c.length!=0;if(e){this.initMore();if(!this.lastOverflow){this.container.fireEvent("overflowchange",this.container,true);this.lastOverflow=true}}else{if(this.more){this.clearMenu();this.more.destroy();delete this.more;if(this.lastOverflow){this.container.fireEvent("overflowchange",this.container,false);this.lastOverflow=false}}}},createMenuConfig:function(c,a){var b=Ext.apply({},c.initialConfig),d=c.toggleGroup;Ext.copyTo(b,c,["iconCls","icon","itemId","disabled","handler","scope","menu"]);Ext.apply(b,{text:c.overflowText||c.text,hideOnClick:a});if(d||c.enableToggle){Ext.apply(b,{group:d,checked:c.pressed,listeners:{checkchange:function(g,e){c.toggle(e)}}})}delete b.ownerCt;delete b.xtype;delete b.id;return b},addComponentToMenu:function(b,a){if(a instanceof Ext.Toolbar.Separator){b.add("-")}else{if(Ext.isFunction(a.isXType)){if(a.isXType("splitbutton")){b.add(this.createMenuConfig(a,true))}else{if(a.isXType("button")){b.add(this.createMenuConfig(a,!a.menu))}else{if(a.isXType("buttongroup")){a.items.each(function(c){this.addComponentToMenu(b,c)},this)}}}}}},clearMenu:function(){var a=this.moreMenu;if(a&&a.items){a.items.each(function(b){delete b.menu})}},beforeMoreShow:function(h){var b=this.container.items.items,a=b.length,g,e;var c=function(k,i){return k.isXType("buttongroup")&&!(i instanceof Ext.Toolbar.Separator)};this.clearMenu();h.removeAll();for(var d=0;d<a;d++){g=b[d];if(g.xtbHidden){if(e&&(c(g,e)||c(e,g))){h.add("-")}this.addComponentToMenu(h,g);e=g}}if(h.items.length<1){h.add(this.noItemsMenuText)}},initMore:function(){if(!this.more){this.moreMenu=new Ext.menu.Menu({ownerCt:this.container,listeners:{beforeshow:this.beforeMoreShow,scope:this}});this.more=new Ext.Button({iconCls:"x-toolbar-more-icon",cls:"x-toolbar-more",menu:this.moreMenu,ownerCt:this.container});var a=this.insertCell(this.more,this.extrasTr,100);this.more.render(a)}},destroy:function(){Ext.destroy(this.more,this.moreMenu);delete this.leftTr;delete this.rightTr;delete this.extrasTr;Ext.layout.ToolbarLayout.superclass.destroy.call(this)}});Ext.Container.LAYOUTS.toolbar=Ext.layout.ToolbarLayout;Ext.layout.MenuLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,type:"menu",setContainer:function(a){this.monitorResize=!a.floating;a.on("autosize",this.doAutoSize,this);Ext.layout.MenuLayout.superclass.setContainer.call(this,a)},renderItem:function(g,b,e){if(!this.itemTpl){this.itemTpl=Ext.layout.MenuLayout.prototype.itemTpl=new Ext.XTemplate('<li id="{itemId}" class="{itemCls}">','<tpl if="needsIcon">','<img alt="{altText}" src="{icon}" class="{iconCls}"/>',"</tpl>","</li>")}if(g&&!g.rendered){if(Ext.isNumber(b)){b=e.dom.childNodes[b]}var d=this.getItemArgs(g);g.render(g.positionEl=b?this.itemTpl.insertBefore(b,d,true):this.itemTpl.append(e,d,true));g.positionEl.menuItemId=g.getItemId();if(!d.isMenuItem&&d.needsIcon){g.positionEl.addClass("x-menu-list-item-indent")}this.configureItem(g)}else{if(g&&!this.isValidParent(g,e)){if(Ext.isNumber(b)){b=e.dom.childNodes[b]}e.dom.insertBefore(g.getActionEl().dom,b||null)}}},getItemArgs:function(d){var a=d instanceof Ext.menu.Item,b=!(a||d instanceof Ext.menu.Separator);return{isMenuItem:a,needsIcon:b&&(d.icon||d.iconCls),icon:d.icon||Ext.BLANK_IMAGE_URL,iconCls:"x-menu-item-icon "+(d.iconCls||""),itemId:"x-menu-el-"+d.id,itemCls:"x-menu-list-item ",altText:d.altText||""}},isValidParent:function(b,a){return b.el.up("li.x-menu-list-item",5).dom.parentNode===(a.dom||a)},onLayout:function(a,b){Ext.layout.MenuLayout.superclass.onLayout.call(this,a,b);this.doAutoSize()},doAutoSize:function(){var c=this.container,a=c.width;if(c.floating){if(a){c.setWidth(a)}else{if(Ext.isIE){c.setWidth(Ext.isStrict&&(Ext.isIE7||Ext.isIE8)?"auto":c.minWidth);var d=c.getEl(),b=d.dom.offsetWidth;c.setWidth(c.getLayoutTarget().getWidth()+d.getFrameWidth("lr"))}}}}});Ext.Container.LAYOUTS.menu=Ext.layout.MenuLayout;Ext.Viewport=Ext.extend(Ext.Container,{initComponent:function(){Ext.Viewport.superclass.initComponent.call(this);document.getElementsByTagName("html")[0].className+=" x-viewport";this.el=Ext.getBody();this.el.setHeight=Ext.emptyFn;this.el.setWidth=Ext.emptyFn;this.el.setSize=Ext.emptyFn;this.el.dom.scroll="no";this.allowDomMove=false;this.autoWidth=true;this.autoHeight=true;Ext.EventManager.onWindowResize(this.fireResize,this);this.renderTo=this.el},fireResize:function(a,b){this.fireEvent("resize",this,a,b,a,b)}});Ext.reg("viewport",Ext.Viewport);Ext.Panel=Ext.extend(Ext.Container,{baseCls:"x-panel",collapsedCls:"x-panel-collapsed",maskDisabled:true,animCollapse:Ext.enableFx,headerAsText:true,buttonAlign:"right",collapsed:false,collapseFirst:true,minButtonWidth:75,elements:"body",preventBodyReset:false,padding:undefined,resizeEvent:"bodyresize",toolTarget:"header",collapseEl:"bwrap",slideAnchor:"t",disabledClass:"",deferHeight:true,expandDefaults:{duration:0.25},collapseDefaults:{duration:0.25},initComponent:function(){Ext.Panel.superclass.initComponent.call(this);this.addEvents("bodyresize","titlechange","iconchange","collapse","expand","beforecollapse","beforeexpand","beforeclose","close","activate","deactivate");if(this.unstyled){this.baseCls="x-plain"}this.toolbars=[];if(this.tbar){this.elements+=",tbar";this.topToolbar=this.createToolbar(this.tbar);this.tbar=null}if(this.bbar){this.elements+=",bbar";this.bottomToolbar=this.createToolbar(this.bbar);this.bbar=null}if(this.header===true){this.elements+=",header";this.header=null}else{if(this.headerCfg||(this.title&&this.header!==false)){this.elements+=",header"}}if(this.footerCfg||this.footer===true){this.elements+=",footer";this.footer=null}if(this.buttons){this.fbar=this.buttons;this.buttons=null}if(this.fbar){this.createFbar(this.fbar)}if(this.autoLoad){this.on("render",this.doAutoLoad,this,{delay:10})}},createFbar:function(b){var a=this.minButtonWidth;this.elements+=",footer";this.fbar=this.createToolbar(b,{buttonAlign:this.buttonAlign,toolbarCls:"x-panel-fbar",enableOverflow:false,defaults:function(d){return{minWidth:d.minWidth||a}}});this.fbar.items.each(function(d){d.minWidth=d.minWidth||this.minButtonWidth},this);this.buttons=this.fbar.items.items},createToolbar:function(b,c){var a;if(Ext.isArray(b)){b={items:b}}a=b.events?Ext.apply(b,c):this.createComponent(Ext.apply({},b,c),"toolbar");this.toolbars.push(a);return a},createElement:function(a,c){if(this[a]){c.appendChild(this[a].dom);return}if(a==="bwrap"||this.elements.indexOf(a)!=-1){if(this[a+"Cfg"]){this[a]=Ext.fly(c).createChild(this[a+"Cfg"])}else{var b=document.createElement("div");b.className=this[a+"Cls"];this[a]=Ext.get(c.appendChild(b))}if(this[a+"CssClass"]){this[a].addClass(this[a+"CssClass"])}if(this[a+"Style"]){this[a].applyStyles(this[a+"Style"])}}},onRender:function(g,e){Ext.Panel.superclass.onRender.call(this,g,e);this.createClasses();var a=this.el,h=a.dom,l,i;if(this.collapsible&&!this.hideCollapseTool){this.tools=this.tools?this.tools.slice(0):[];this.tools[this.collapseFirst?"unshift":"push"]({id:"toggle",handler:this.toggleCollapse,scope:this})}if(this.tools){i=this.tools;this.elements+=(this.header!==false)?",header":""}this.tools={};a.addClass(this.baseCls);if(h.firstChild){this.header=a.down("."+this.headerCls);this.bwrap=a.down("."+this.bwrapCls);var k=this.bwrap?this.bwrap:a;this.tbar=k.down("."+this.tbarCls);this.body=k.down("."+this.bodyCls);this.bbar=k.down("."+this.bbarCls);this.footer=k.down("."+this.footerCls);this.fromMarkup=true}if(this.preventBodyReset===true){a.addClass("x-panel-reset")}if(this.cls){a.addClass(this.cls)}if(this.buttons){this.elements+=",footer"}if(this.frame){a.insertHtml("afterBegin",String.format(Ext.Element.boxMarkup,this.baseCls));this.createElement("header",h.firstChild.firstChild.firstChild);this.createElement("bwrap",h);l=this.bwrap.dom;var c=h.childNodes[1],b=h.childNodes[2];l.appendChild(c);l.appendChild(b);var m=l.firstChild.firstChild.firstChild;this.createElement("tbar",m);this.createElement("body",m);this.createElement("bbar",m);this.createElement("footer",l.lastChild.firstChild.firstChild);if(!this.footer){this.bwrap.dom.lastChild.className+=" x-panel-nofooter"}this.ft=Ext.get(this.bwrap.dom.lastChild);this.mc=Ext.get(m)}else{this.createElement("header",h);this.createElement("bwrap",h);l=this.bwrap.dom;this.createElement("tbar",l);this.createElement("body",l);this.createElement("bbar",l);this.createElement("footer",l);if(!this.header){this.body.addClass(this.bodyCls+"-noheader");if(this.tbar){this.tbar.addClass(this.tbarCls+"-noheader")}}}if(Ext.isDefined(this.padding)){this.body.setStyle("padding",this.body.addUnits(this.padding))}if(this.border===false){this.el.addClass(this.baseCls+"-noborder");this.body.addClass(this.bodyCls+"-noborder");if(this.header){this.header.addClass(this.headerCls+"-noborder")}if(this.footer){this.footer.addClass(this.footerCls+"-noborder")}if(this.tbar){this.tbar.addClass(this.tbarCls+"-noborder")}if(this.bbar){this.bbar.addClass(this.bbarCls+"-noborder")}}if(this.bodyBorder===false){this.body.addClass(this.bodyCls+"-noborder")}this.bwrap.enableDisplayMode("block");if(this.header){this.header.unselectable();if(this.headerAsText){this.header.dom.innerHTML='<span class="'+this.headerTextCls+'">'+this.header.dom.innerHTML+"</span>";if(this.iconCls){this.setIconClass(this.iconCls)}}}if(this.floating){this.makeFloating(this.floating)}if(this.collapsible&&this.titleCollapse&&this.header){this.mon(this.header,"click",this.toggleCollapse,this);this.header.setStyle("cursor","pointer")}if(i){this.addTool.apply(this,i)}if(this.fbar){this.footer.addClass("x-panel-btns");this.fbar.ownerCt=this;this.fbar.render(this.footer);this.footer.createChild({cls:"x-clear"})}if(this.tbar&&this.topToolbar){this.topToolbar.ownerCt=this;this.topToolbar.render(this.tbar)}if(this.bbar&&this.bottomToolbar){this.bottomToolbar.ownerCt=this;this.bottomToolbar.render(this.bbar)}},setIconClass:function(b){var a=this.iconCls;this.iconCls=b;if(this.rendered&&this.header){if(this.frame){this.header.addClass("x-panel-icon");this.header.replaceClass(a,this.iconCls)}else{var e=this.header,c=e.child("img.x-panel-inline-icon");if(c){Ext.fly(c).replaceClass(a,this.iconCls)}else{var d=e.child("span."+this.headerTextCls);if(d){Ext.DomHelper.insertBefore(d.dom,{tag:"img",alt:"",src:Ext.BLANK_IMAGE_URL,cls:"x-panel-inline-icon "+this.iconCls})}}}}this.fireEvent("iconchange",this,b,a)},makeFloating:function(a){this.floating=true;this.el=new Ext.Layer(Ext.apply({},a,{shadow:Ext.isDefined(this.shadow)?this.shadow:"sides",shadowOffset:this.shadowOffset,constrain:false,shim:this.shim===false?false:undefined}),this.el)},getTopToolbar:function(){return this.topToolbar},getBottomToolbar:function(){return this.bottomToolbar},getFooterToolbar:function(){return this.fbar},addButton:function(a,c,b){if(!this.fbar){this.createFbar([])}if(c){if(Ext.isString(a)){a={text:a}}a=Ext.apply({handler:c,scope:b},a)}return this.fbar.add(a)},addTool:function(){if(!this.rendered){if(!this.tools){this.tools=[]}Ext.each(arguments,function(a){this.tools.push(a)},this);return}if(!this[this.toolTarget]){return}if(!this.toolTemplate){var h=new Ext.Template('<div class="x-tool x-tool-{id}"> </div>');h.disableFormats=true;h.compile();Ext.Panel.prototype.toolTemplate=h}for(var g=0,d=arguments,c=d.length;g<c;g++){var b=d[g];if(!this.tools[b.id]){var k="x-tool-"+b.id+"-over";var e=this.toolTemplate.insertFirst(this[this.toolTarget],b,true);this.tools[b.id]=e;e.enableDisplayMode("block");this.mon(e,"click",this.createToolHandler(e,b,k,this));if(b.on){this.mon(e,b.on)}if(b.hidden){e.hide()}if(b.qtip){if(Ext.isObject(b.qtip)){Ext.QuickTips.register(Ext.apply({target:e.id},b.qtip))}else{e.dom.qtip=b.qtip}}e.addClassOnOver(k)}}},onLayout:function(b,a){Ext.Panel.superclass.onLayout.apply(this,arguments);if(this.hasLayout&&this.toolbars.length>0){Ext.each(this.toolbars,function(c){c.doLayout(undefined,a)});this.syncHeight()}},syncHeight:function(){var b=this.toolbarHeight,c=this.body,a=this.lastSize.height,d;if(this.autoHeight||!Ext.isDefined(a)||a=="auto"){return}if(b!=this.getToolbarHeight()){b=Math.max(0,a-this.getFrameHeight());c.setHeight(b);d=c.getSize();this.toolbarHeight=this.getToolbarHeight();this.onBodyResize(d.width,d.height)}},onShow:function(){if(this.floating){return this.el.show()}Ext.Panel.superclass.onShow.call(this)},onHide:function(){if(this.floating){return this.el.hide()}Ext.Panel.superclass.onHide.call(this)},createToolHandler:function(c,a,d,b){return function(g){c.removeClass(d);if(a.stopEvent!==false){g.stopEvent()}if(a.handler){a.handler.call(a.scope||c,g,c,b,a)}}},afterRender:function(){if(this.floating&&!this.hidden){this.el.show()}if(this.title){this.setTitle(this.title)}Ext.Panel.superclass.afterRender.call(this);if(this.collapsed){this.collapsed=false;this.collapse(false)}this.initEvents()},getKeyMap:function(){if(!this.keyMap){this.keyMap=new Ext.KeyMap(this.el,this.keys)}return this.keyMap},initEvents:function(){if(this.keys){this.getKeyMap()}if(this.draggable){this.initDraggable()}if(this.toolbars.length>0){Ext.each(this.toolbars,function(a){a.doLayout();a.on({scope:this,afterlayout:this.syncHeight,remove:this.syncHeight})},this);this.syncHeight()}},initDraggable:function(){this.dd=new Ext.Panel.DD(this,Ext.isBoolean(this.draggable)?null:this.draggable)},beforeEffect:function(a){if(this.floating){this.el.beforeAction()}if(a!==false){this.el.addClass("x-panel-animated")}},afterEffect:function(a){this.syncShadow();this.el.removeClass("x-panel-animated")},createEffect:function(c,b,d){var e={scope:d,block:true};if(c===true){e.callback=b;return e}else{if(!c.callback){e.callback=b}else{e.callback=function(){b.call(d);Ext.callback(c.callback,c.scope)}}}return Ext.applyIf(e,c)},collapse:function(b){if(this.collapsed||this.el.hasFxBlock()||this.fireEvent("beforecollapse",this,b)===false){return}var a=b===true||(b!==false&&this.animCollapse);this.beforeEffect(a);this.onCollapse(a,b);return this},onCollapse:function(a,b){if(a){this[this.collapseEl].slideOut(this.slideAnchor,Ext.apply(this.createEffect(b||true,this.afterCollapse,this),this.collapseDefaults))}else{this[this.collapseEl].hide(this.hideMode);this.afterCollapse(false)}},afterCollapse:function(a){this.collapsed=true;this.el.addClass(this.collapsedCls);if(a!==false){this[this.collapseEl].hide(this.hideMode)}this.afterEffect(a);this.cascade(function(b){if(b.lastSize){b.lastSize={width:undefined,height:undefined}}});this.fireEvent("collapse",this)},expand:function(b){if(!this.collapsed||this.el.hasFxBlock()||this.fireEvent("beforeexpand",this,b)===false){return}var a=b===true||(b!==false&&this.animCollapse);this.el.removeClass(this.collapsedCls);this.beforeEffect(a);this.onExpand(a,b);return this},onExpand:function(a,b){if(a){this[this.collapseEl].slideIn(this.slideAnchor,Ext.apply(this.createEffect(b||true,this.afterExpand,this),this.expandDefaults))}else{this[this.collapseEl].show(this.hideMode);this.afterExpand(false)}},afterExpand:function(a){this.collapsed=false;if(a!==false){this[this.collapseEl].show(this.hideMode)}this.afterEffect(a);if(this.deferLayout){delete this.deferLayout;this.doLayout(true)}this.fireEvent("expand",this)},toggleCollapse:function(a){this[this.collapsed?"expand":"collapse"](a);return this},onDisable:function(){if(this.rendered&&this.maskDisabled){this.el.mask()}Ext.Panel.superclass.onDisable.call(this)},onEnable:function(){if(this.rendered&&this.maskDisabled){this.el.unmask()}Ext.Panel.superclass.onEnable.call(this)},onResize:function(g,d,c,e){var a=g,b=d;if(Ext.isDefined(a)||Ext.isDefined(b)){if(!this.collapsed){if(Ext.isNumber(a)){this.body.setWidth(a=this.adjustBodyWidth(a-this.getFrameWidth()))}else{if(a=="auto"){a=this.body.setWidth("auto").dom.offsetWidth}else{a=this.body.dom.offsetWidth}}if(this.tbar){this.tbar.setWidth(a);if(this.topToolbar){this.topToolbar.setSize(a)}}if(this.bbar){this.bbar.setWidth(a);if(this.bottomToolbar){this.bottomToolbar.setSize(a);if(Ext.isIE){this.bbar.setStyle("position","static");this.bbar.setStyle("position","")}}}if(this.footer){this.footer.setWidth(a);if(this.fbar){this.fbar.setSize(Ext.isIE?(a-this.footer.getFrameWidth("lr")):"auto")}}if(Ext.isNumber(b)){b=Math.max(0,b-this.getFrameHeight());this.body.setHeight(b)}else{if(b=="auto"){this.body.setHeight(b)}}if(this.disabled&&this.el._mask){this.el._mask.setSize(this.el.dom.clientWidth,this.el.getHeight())}}else{this.queuedBodySize={width:a,height:b};if(!this.queuedExpand&&this.allowQueuedExpand!==false){this.queuedExpand=true;this.on("expand",function(){delete this.queuedExpand;this.onResize(this.queuedBodySize.width,this.queuedBodySize.height)},this,{single:true})}}this.onBodyResize(a,b)}this.syncShadow();Ext.Panel.superclass.onResize.call(this,g,d,c,e)},onBodyResize:function(a,b){this.fireEvent("bodyresize",this,a,b)},getToolbarHeight:function(){var a=0;if(this.rendered){Ext.each(this.toolbars,function(b){a+=b.getHeight()},this)}return a},adjustBodyHeight:function(a){return a},adjustBodyWidth:function(a){return a},onPosition:function(){this.syncShadow()},getFrameWidth:function(){var b=this.el.getFrameWidth("lr")+this.bwrap.getFrameWidth("lr");if(this.frame){var a=this.bwrap.dom.firstChild;b+=(Ext.fly(a).getFrameWidth("l")+Ext.fly(a.firstChild).getFrameWidth("r"));b+=this.mc.getFrameWidth("lr")}return b},getFrameHeight:function(){var a=this.el.getFrameWidth("tb")+this.bwrap.getFrameWidth("tb");a+=(this.tbar?this.tbar.getHeight():0)+(this.bbar?this.bbar.getHeight():0);if(this.frame){a+=this.el.dom.firstChild.offsetHeight+this.ft.dom.offsetHeight+this.mc.getFrameWidth("tb")}else{a+=(this.header?this.header.getHeight():0)+(this.footer?this.footer.getHeight():0)}return a},getInnerWidth:function(){return this.getSize().width-this.getFrameWidth()},getInnerHeight:function(){return this.body.getHeight()},syncShadow:function(){if(this.floating){this.el.sync(true)}},getLayoutTarget:function(){return this.body},getContentTarget:function(){return this.body},setTitle:function(b,a){this.title=b;if(this.header&&this.headerAsText){this.header.child("span").update(b)}if(a){this.setIconClass(a)}this.fireEvent("titlechange",this,b);return this},getUpdater:function(){return this.body.getUpdater()},load:function(){var a=this.body.getUpdater();a.update.apply(a,arguments);return this},beforeDestroy:function(){Ext.Panel.superclass.beforeDestroy.call(this);if(this.header){this.header.removeAllListeners()}if(this.tools){for(var a in this.tools){Ext.destroy(this.tools[a])}}if(this.toolbars.length>0){Ext.each(this.toolbars,function(b){b.un("afterlayout",this.syncHeight,this);b.un("remove",this.syncHeight,this)},this)}if(Ext.isArray(this.buttons)){while(this.buttons.length){Ext.destroy(this.buttons[0])}}if(this.rendered){Ext.destroy(this.ft,this.header,this.footer,this.tbar,this.bbar,this.body,this.mc,this.bwrap,this.dd);if(this.fbar){Ext.destroy(this.fbar,this.fbar.el)}}Ext.destroy(this.toolbars)},createClasses:function(){this.headerCls=this.baseCls+"-header";this.headerTextCls=this.baseCls+"-header-text";this.bwrapCls=this.baseCls+"-bwrap";this.tbarCls=this.baseCls+"-tbar";this.bodyCls=this.baseCls+"-body";this.bbarCls=this.baseCls+"-bbar";this.footerCls=this.baseCls+"-footer"},createGhost:function(a,e,b){var d=document.createElement("div");d.className="x-panel-ghost "+(a?a:"");if(this.header){d.appendChild(this.el.dom.firstChild.cloneNode(true))}Ext.fly(d.appendChild(document.createElement("ul"))).setHeight(this.bwrap.getHeight());d.style.width=this.el.dom.offsetWidth+"px";if(!b){this.container.dom.appendChild(d)}else{Ext.getDom(b).appendChild(d)}if(e!==false&&this.el.useShim!==false){var c=new Ext.Layer({shadow:false,useDisplay:true,constrain:false},d);c.show();return c}else{return new Ext.Element(d)}},doAutoLoad:function(){var a=this.body.getUpdater();if(this.renderer){a.setRenderer(this.renderer)}a.update(Ext.isObject(this.autoLoad)?this.autoLoad:{url:this.autoLoad})},getTool:function(a){return this.tools[a]}});Ext.reg("panel",Ext.Panel);Ext.Editor=function(b,a){if(b.field){this.field=Ext.create(b.field,"textfield");a=Ext.apply({},b);delete a.field}else{this.field=b}Ext.Editor.superclass.constructor.call(this,a)};Ext.extend(Ext.Editor,Ext.Component,{allowBlur:true,value:"",alignment:"c-c?",offsets:[0,0],shadow:"frame",constrain:false,swallowKeys:true,completeOnEnter:true,cancelOnEsc:true,updateEl:false,initComponent:function(){Ext.Editor.superclass.initComponent.call(this);this.addEvents("beforestartedit","startedit","beforecomplete","complete","canceledit","specialkey")},onRender:function(b,a){this.el=new Ext.Layer({shadow:this.shadow,cls:"x-editor",parentEl:b,shim:this.shim,shadowOffset:this.shadowOffset||4,id:this.id,constrain:this.constrain});if(this.zIndex){this.el.setZIndex(this.zIndex)}this.el.setStyle("overflow",Ext.isGecko?"auto":"hidden");if(this.field.msgTarget!="title"){this.field.msgTarget="qtip"}this.field.inEditor=true;this.mon(this.field,{scope:this,blur:this.onBlur,specialkey:this.onSpecialKey});if(this.field.grow){this.mon(this.field,"autosize",this.el.sync,this.el,{delay:1})}this.field.render(this.el).show();this.field.getEl().dom.name="";if(this.swallowKeys){this.field.el.swallowEvent(["keypress","keydown"])}},onSpecialKey:function(g,d){var b=d.getKey(),a=this.completeOnEnter&&b==d.ENTER,c=this.cancelOnEsc&&b==d.ESC;if(a||c){d.stopEvent();if(a){this.completeEdit()}else{this.cancelEdit()}if(g.triggerBlur){g.triggerBlur()}}this.fireEvent("specialkey",g,d)},startEdit:function(b,c){if(this.editing){this.completeEdit()}this.boundEl=Ext.get(b);var a=c!==undefined?c:this.boundEl.dom.innerHTML;if(!this.rendered){this.render(this.parentEl||document.body)}if(this.fireEvent("beforestartedit",this,this.boundEl,a)!==false){this.startValue=a;this.field.reset();this.field.setValue(a);this.realign(true);this.editing=true;this.show()}},doAutoSize:function(){if(this.autoSize){var b=this.boundEl.getSize(),a=this.field.getSize();switch(this.autoSize){case"width":this.setSize(b.width,a.height);break;case"height":this.setSize(a.width,b.height);break;case"none":this.setSize(a.width,a.height);break;default:this.setSize(b.width,b.height)}}},setSize:function(a,b){delete this.field.lastSize;this.field.setSize(a,b);if(this.el){if(Ext.isGecko2||Ext.isOpera||(Ext.isIE7&&Ext.isStrict)){this.el.setSize(a,b)}this.el.sync()}},realign:function(a){if(a===true){this.doAutoSize()}this.el.alignTo(this.boundEl,this.alignment,this.offsets)},completeEdit:function(a){if(!this.editing){return}if(this.field.assertValue){this.field.assertValue()}var b=this.getValue();if(!this.field.isValid()){if(this.revertInvalid!==false){this.cancelEdit(a)}return}if(String(b)===String(this.startValue)&&this.ignoreNoChange){this.hideEdit(a);return}if(this.fireEvent("beforecomplete",this,b,this.startValue)!==false){b=this.getValue();if(this.updateEl&&this.boundEl){this.boundEl.update(b)}this.hideEdit(a);this.fireEvent("complete",this,b,this.startValue)}},onShow:function(){this.el.show();if(this.hideEl!==false){this.boundEl.hide()}this.field.show().focus(false,true);this.fireEvent("startedit",this.boundEl,this.startValue)},cancelEdit:function(a){if(this.editing){var b=this.getValue();this.setValue(this.startValue);this.hideEdit(a);this.fireEvent("canceledit",this,b,this.startValue)}},hideEdit:function(a){if(a!==true){this.editing=false;this.hide()}},onBlur:function(){if(this.allowBlur===true&&this.editing&&this.selectSameEditor!==true){this.completeEdit()}},onHide:function(){if(this.editing){this.completeEdit();return}this.field.blur();if(this.field.collapse){this.field.collapse()}this.el.hide();if(this.hideEl!==false){this.boundEl.show()}},setValue:function(a){this.field.setValue(a)},getValue:function(){return this.field.getValue()},beforeDestroy:function(){Ext.destroyMembers(this,"field");delete this.parentEl;delete this.boundEl}});Ext.reg("editor",Ext.Editor);Ext.ColorPalette=Ext.extend(Ext.Component,{itemCls:"x-color-palette",value:null,clickEvent:"click",ctype:"Ext.ColorPalette",allowReselect:false,colors:["000000","993300","333300","003300","003366","000080","333399","333333","800000","FF6600","808000","008000","008080","0000FF","666699","808080","FF0000","FF9900","99CC00","339966","33CCCC","3366FF","800080","969696","FF00FF","FFCC00","FFFF00","00FF00","00FFFF","00CCFF","993366","C0C0C0","FF99CC","FFCC99","FFFF99","CCFFCC","CCFFFF","99CCFF","CC99FF","FFFFFF"],initComponent:function(){Ext.ColorPalette.superclass.initComponent.call(this);this.addEvents("select");if(this.handler){this.on("select",this.handler,this.scope,true)}},onRender:function(b,a){this.autoEl={tag:"div",cls:this.itemCls};Ext.ColorPalette.superclass.onRender.call(this,b,a);var c=this.tpl||new Ext.XTemplate('<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on"> </span></em></a></tpl>');c.overwrite(this.el,this.colors);this.mon(this.el,this.clickEvent,this.handleClick,this,{delegate:"a"});if(this.clickEvent!="click"){this.mon(this.el,"click",Ext.emptyFn,this,{delegate:"a",preventDefault:true})}},afterRender:function(){Ext.ColorPalette.superclass.afterRender.call(this);if(this.value){var a=this.value;this.value=null;this.select(a,true)}},handleClick:function(b,a){b.preventDefault();if(!this.disabled){var d=a.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];this.select(d.toUpperCase())}},select:function(b,a){b=b.replace("#","");if(b!=this.value||this.allowReselect){var c=this.el;if(this.value){c.child("a.color-"+this.value).removeClass("x-color-palette-sel")}c.child("a.color-"+b).addClass("x-color-palette-sel");this.value=b;if(a!==true){this.fireEvent("select",this,b)}}}});Ext.reg("colorpalette",Ext.ColorPalette);Ext.DatePicker=Ext.extend(Ext.BoxComponent,{todayText:"Today",okText:" OK ",cancelText:"Cancel",todayTip:"{0} (Spacebar)",minText:"This date is before the minimum date",maxText:"This date is after the maximum date",format:"m/d/y",disabledDaysText:"Disabled",disabledDatesText:"Disabled",monthNames:Date.monthNames,dayNames:Date.dayNames,nextText:"Next Month (Control+Right)",prevText:"Previous Month (Control+Left)",monthYearText:"Choose a month (Control+Up/Down to move years)",startDay:0,showToday:true,focusOnSelect:true,initHour:12,initComponent:function(){Ext.DatePicker.superclass.initComponent.call(this);this.value=this.value?this.value.clearTime(true):new Date().clearTime();this.addEvents("select");if(this.handler){this.on("select",this.handler,this.scope||this)}this.initDisabledDays()},initDisabledDays:function(){if(!this.disabledDatesRE&&this.disabledDates){var b=this.disabledDates,a=b.length-1,c="(?:";Ext.each(b,function(g,e){c+=Ext.isDate(g)?"^"+Ext.escapeRe(g.dateFormat(this.format))+"$":b[e];if(e!=a){c+="|"}},this);this.disabledDatesRE=new RegExp(c+")")}},setDisabledDates:function(a){if(Ext.isArray(a)){this.disabledDates=a;this.disabledDatesRE=null}else{this.disabledDatesRE=a}this.initDisabledDays();this.update(this.value,true)},setDisabledDays:function(a){this.disabledDays=a;this.update(this.value,true)},setMinDate:function(a){this.minDate=a;this.update(this.value,true)},setMaxDate:function(a){this.maxDate=a;this.update(this.value,true)},setValue:function(a){this.value=a.clearTime(true);this.update(this.value)},getValue:function(){return this.value},focus:function(){this.update(this.activeDate)},onEnable:function(a){Ext.DatePicker.superclass.onEnable.call(this);this.doDisabled(false);this.update(a?this.value:this.activeDate);if(Ext.isIE){this.el.repaint()}},onDisable:function(){Ext.DatePicker.superclass.onDisable.call(this);this.doDisabled(true);if(Ext.isIE&&!Ext.isIE8){Ext.each([].concat(this.textNodes,this.el.query("th span")),function(a){Ext.fly(a).repaint()})}},doDisabled:function(a){this.keyNav.setDisabled(a);this.prevRepeater.setDisabled(a);this.nextRepeater.setDisabled(a);if(this.showToday){this.todayKeyListener.setDisabled(a);this.todayBtn.setDisabled(a)}},onRender:function(e,b){var a=['<table cellspacing="0">','<tr><td class="x-date-left"><a href="#" title="',this.prevText,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="',this.nextText,'"> </a></td></tr>','<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'],c=this.dayNames,h;for(h=0;h<7;h++){var l=this.startDay+h;if(l>6){l=l-7}a.push("<th><span>",c[l].substr(0,1),"</span></th>")}a[a.length]="</tr></thead><tbody><tr>";for(h=0;h<42;h++){if(h%7===0&&h!==0){a[a.length]="</tr><tr>"}a[a.length]='<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>'}a.push("</tr></tbody></table></td></tr>",this.showToday?'<tr><td colspan="3" class="x-date-bottom" align="center"></td></tr>':"",'</table><div class="x-date-mp"></div>');var k=document.createElement("div");k.className="x-date-picker";k.innerHTML=a.join("");e.dom.insertBefore(k,b);this.el=Ext.get(k);this.eventEl=Ext.get(k.firstChild);this.prevRepeater=new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"),{handler:this.showPrevMonth,scope:this,preventDefault:true,stopDefault:true});this.nextRepeater=new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"),{handler:this.showNextMonth,scope:this,preventDefault:true,stopDefault:true});this.monthPicker=this.el.down("div.x-date-mp");this.monthPicker.enableDisplayMode("block");this.keyNav=new Ext.KeyNav(this.eventEl,{left:function(d){if(d.ctrlKey){this.showPrevMonth()}else{this.update(this.activeDate.add("d",-1))}},right:function(d){if(d.ctrlKey){this.showNextMonth()}else{this.update(this.activeDate.add("d",1))}},up:function(d){if(d.ctrlKey){this.showNextYear()}else{this.update(this.activeDate.add("d",-7))}},down:function(d){if(d.ctrlKey){this.showPrevYear()}else{this.update(this.activeDate.add("d",7))}},pageUp:function(d){this.showNextMonth()},pageDown:function(d){this.showPrevMonth()},enter:function(d){d.stopPropagation();return true},scope:this});this.el.unselectable();this.cells=this.el.select("table.x-date-inner tbody td");this.textNodes=this.el.query("table.x-date-inner tbody span");this.mbtn=new Ext.Button({text:" ",tooltip:this.monthYearText,renderTo:this.el.child("td.x-date-middle",true)});this.mbtn.el.child("em").addClass("x-btn-arrow");if(this.showToday){this.todayKeyListener=this.eventEl.addKeyListener(Ext.EventObject.SPACE,this.selectToday,this);var g=(new Date()).dateFormat(this.format);this.todayBtn=new Ext.Button({renderTo:this.el.child("td.x-date-bottom",true),text:String.format(this.todayText,g),tooltip:String.format(this.todayTip,g),handler:this.selectToday,scope:this})}this.mon(this.eventEl,"mousewheel",this.handleMouseWheel,this);this.mon(this.eventEl,"click",this.handleDateClick,this,{delegate:"a.x-date-date"});this.mon(this.mbtn,"click",this.showMonthPicker,this);this.onEnable(true)},createMonthPicker:function(){if(!this.monthPicker.dom.firstChild){var a=['<table border="0" cellspacing="0">'];for(var b=0;b<6;b++){a.push('<tr><td class="x-date-mp-month"><a href="#">',Date.getShortMonthName(b),"</a></td>",'<td class="x-date-mp-month x-date-mp-sep"><a href="#">',Date.getShortMonthName(b+6),"</a></td>",b===0?'<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>':'<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>')}a.push('<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',this.okText,'</button><button type="button" class="x-date-mp-cancel">',this.cancelText,"</button></td></tr>","</table>");this.monthPicker.update(a.join(""));this.mon(this.monthPicker,"click",this.onMonthClick,this);this.mon(this.monthPicker,"dblclick",this.onMonthDblClick,this);this.mpMonths=this.monthPicker.select("td.x-date-mp-month");this.mpYears=this.monthPicker.select("td.x-date-mp-year");this.mpMonths.each(function(c,d,e){e+=1;if((e%2)===0){c.dom.xmonth=5+Math.round(e*0.5)}else{c.dom.xmonth=Math.round((e-1)*0.5)}})}},showMonthPicker:function(){if(!this.disabled){this.createMonthPicker();var a=this.el.getSize();this.monthPicker.setSize(a);this.monthPicker.child("table").setSize(a);this.mpSelMonth=(this.activeDate||this.value).getMonth();this.updateMPMonth(this.mpSelMonth);this.mpSelYear=(this.activeDate||this.value).getFullYear();this.updateMPYear(this.mpSelYear);this.monthPicker.slideIn("t",{duration:0.2})}},updateMPYear:function(e){this.mpyear=e;var c=this.mpYears.elements;for(var b=1;b<=10;b++){var d=c[b-1],a;if((b%2)===0){a=e+Math.round(b*0.5);d.firstChild.innerHTML=a;d.xyear=a}else{a=e-(5-Math.round(b*0.5));d.firstChild.innerHTML=a;d.xyear=a}this.mpYears.item(b-1)[a==this.mpSelYear?"addClass":"removeClass"]("x-date-mp-sel")}},updateMPMonth:function(a){this.mpMonths.each(function(b,c,d){b[b.dom.xmonth==a?"addClass":"removeClass"]("x-date-mp-sel")})},selectMPMonth:function(a){},onMonthClick:function(g,b){g.stopEvent();var c=new Ext.Element(b),a;if(c.is("button.x-date-mp-cancel")){this.hideMonthPicker()}else{if(c.is("button.x-date-mp-ok")){var h=new Date(this.mpSelYear,this.mpSelMonth,(this.activeDate||this.value).getDate());if(h.getMonth()!=this.mpSelMonth){h=new Date(this.mpSelYear,this.mpSelMonth,1).getLastDateOfMonth()}this.update(h);this.hideMonthPicker()}else{if((a=c.up("td.x-date-mp-month",2))){this.mpMonths.removeClass("x-date-mp-sel");a.addClass("x-date-mp-sel");this.mpSelMonth=a.dom.xmonth}else{if((a=c.up("td.x-date-mp-year",2))){this.mpYears.removeClass("x-date-mp-sel");a.addClass("x-date-mp-sel");this.mpSelYear=a.dom.xyear}else{if(c.is("a.x-date-mp-prev")){this.updateMPYear(this.mpyear-10)}else{if(c.is("a.x-date-mp-next")){this.updateMPYear(this.mpyear+10)}}}}}}},onMonthDblClick:function(d,b){d.stopEvent();var c=new Ext.Element(b),a;if((a=c.up("td.x-date-mp-month",2))){this.update(new Date(this.mpSelYear,a.dom.xmonth,(this.activeDate||this.value).getDate()));this.hideMonthPicker()}else{if((a=c.up("td.x-date-mp-year",2))){this.update(new Date(a.dom.xyear,this.mpSelMonth,(this.activeDate||this.value).getDate()));this.hideMonthPicker()}}},hideMonthPicker:function(a){if(this.monthPicker){if(a===true){this.monthPicker.hide()}else{this.monthPicker.slideOut("t",{duration:0.2})}}},showPrevMonth:function(a){this.update(this.activeDate.add("mo",-1))},showNextMonth:function(a){this.update(this.activeDate.add("mo",1))},showPrevYear:function(){this.update(this.activeDate.add("y",-1))},showNextYear:function(){this.update(this.activeDate.add("y",1))},handleMouseWheel:function(a){a.stopEvent();if(!this.disabled){var b=a.getWheelDelta();if(b>0){this.showPrevMonth()}else{if(b<0){this.showNextMonth()}}}},handleDateClick:function(b,a){b.stopEvent();if(!this.disabled&&a.dateValue&&!Ext.fly(a.parentNode).hasClass("x-date-disabled")){this.cancelFocus=this.focusOnSelect===false;this.setValue(new Date(a.dateValue));delete this.cancelFocus;this.fireEvent("select",this,this.value)}},selectToday:function(){if(this.todayBtn&&!this.todayBtn.disabled){this.setValue(new Date().clearTime());this.fireEvent("select",this,this.value)}},update:function(H,B){if(this.rendered){var a=this.activeDate,q=this.isVisible();this.activeDate=H;if(!B&&a&&this.el){var p=H.getTime();if(a.getMonth()==H.getMonth()&&a.getFullYear()==H.getFullYear()){this.cells.removeClass("x-date-selected");this.cells.each(function(d){if(d.dom.firstChild.dateValue==p){d.addClass("x-date-selected");if(q&&!this.cancelFocus){Ext.fly(d.dom.firstChild).focus(50)}return false}},this);return}}var l=H.getDaysInMonth(),r=H.getFirstDateOfMonth(),g=r.getDay()-this.startDay;if(g<0){g+=7}l+=g;var C=H.add("mo",-1),h=C.getDaysInMonth()-g,e=this.cells.elements,s=this.textNodes,E=(new Date(C.getFullYear(),C.getMonth(),h,this.initHour)),D=new Date().clearTime().getTime(),x=H.clearTime(true).getTime(),v=this.minDate?this.minDate.clearTime(true):Number.NEGATIVE_INFINITY,z=this.maxDate?this.maxDate.clearTime(true):Number.POSITIVE_INFINITY,G=this.disabledDatesRE,u=this.disabledDatesText,J=this.disabledDays?this.disabledDays.join(""):false,F=this.disabledDaysText,A=this.format;if(this.showToday){var n=new Date().clearTime(),c=(n<v||n>z||(G&&A&&G.test(n.dateFormat(A)))||(J&&J.indexOf(n.getDay())!=-1));if(!this.disabled){this.todayBtn.setDisabled(c);this.todayKeyListener[c?"disable":"enable"]()}}var m=function(K,d){d.title="";var i=E.clearTime(true).getTime();d.firstChild.dateValue=i;if(i==D){d.className+=" x-date-today";d.title=K.todayText}if(i==x){d.className+=" x-date-selected";if(q){Ext.fly(d.firstChild).focus(50)}}if(i<v){d.className=" x-date-disabled";d.title=K.minText;return}if(i>z){d.className=" x-date-disabled";d.title=K.maxText;return}if(J){if(J.indexOf(E.getDay())!=-1){d.title=F;d.className=" x-date-disabled"}}if(G&&A){var w=E.dateFormat(A);if(G.test(w)){d.title=u.replace("%0",w);d.className=" x-date-disabled"}}};var y=0;for(;y<g;y++){s[y].innerHTML=(++h);E.setDate(E.getDate()+1);e[y].className="x-date-prevday";m(this,e[y])}for(;y<l;y++){var b=y-g+1;s[y].innerHTML=(b);E.setDate(E.getDate()+1);e[y].className="x-date-active";m(this,e[y])}var I=0;for(;y<42;y++){s[y].innerHTML=(++I);E.setDate(E.getDate()+1);e[y].className="x-date-nextday";m(this,e[y])}this.mbtn.setText(this.monthNames[H.getMonth()]+" "+H.getFullYear());if(!this.internalRender){var k=this.el.dom.firstChild,o=k.offsetWidth;this.el.setWidth(o+this.el.getBorderWidth("lr"));Ext.fly(k).setWidth(o);this.internalRender=true;if(Ext.isOpera&&!this.secondPass){k.rows[0].cells[1].style.width=(o-(k.rows[0].cells[0].offsetWidth+k.rows[0].cells[2].offsetWidth))+"px";this.secondPass=true;this.update.defer(10,this,[H])}}}},beforeDestroy:function(){if(this.rendered){Ext.destroy(this.keyNav,this.monthPicker,this.eventEl,this.mbtn,this.nextRepeater,this.prevRepeater,this.cells.el,this.todayBtn);delete this.textNodes;delete this.cells.elements}}});Ext.reg("datepicker",Ext.DatePicker);Ext.LoadMask=function(c,b){this.el=Ext.get(c);Ext.apply(this,b);if(this.store){this.store.on({scope:this,beforeload:this.onBeforeLoad,load:this.onLoad,exception:this.onLoad});this.removeMask=Ext.value(this.removeMask,false)}else{var a=this.el.getUpdater();a.showLoadIndicator=false;a.on({scope:this,beforeupdate:this.onBeforeLoad,update:this.onLoad,failure:this.onLoad});this.removeMask=Ext.value(this.removeMask,true)}};Ext.LoadMask.prototype={msg:"Loading...",msgCls:"x-mask-loading",disabled:false,disable:function(){this.disabled=true},enable:function(){this.disabled=false},onLoad:function(){this.el.unmask(this.removeMask)},onBeforeLoad:function(){if(!this.disabled){this.el.mask(this.msg,this.msgCls)}},show:function(){this.onBeforeLoad()},hide:function(){this.onLoad()},destroy:function(){if(this.store){this.store.un("beforeload",this.onBeforeLoad,this);this.store.un("load",this.onLoad,this);this.store.un("exception",this.onLoad,this)}else{var a=this.el.getUpdater();a.un("beforeupdate",this.onBeforeLoad,this);a.un("update",this.onLoad,this);a.un("failure",this.onLoad,this)}}};Ext.ns("Ext.slider");Ext.slider.Thumb=Ext.extend(Object,{dragging:false,constructor:function(a){Ext.apply(this,a||{},{cls:"x-slider-thumb",constrain:false});Ext.slider.Thumb.superclass.constructor.call(this,a);if(this.slider.vertical){Ext.apply(this,Ext.slider.Thumb.Vertical)}},render:function(){this.el=this.slider.innerEl.insertFirst({cls:this.cls});this.initEvents()},enable:function(){this.disabled=false;this.el.removeClass(this.slider.disabledClass)},disable:function(){this.disabled=true;this.el.addClass(this.slider.disabledClass)},initEvents:function(){var a=this.el;a.addClassOnOver("x-slider-thumb-over");this.tracker=new Ext.dd.DragTracker({onBeforeStart:this.onBeforeDragStart.createDelegate(this),onStart:this.onDragStart.createDelegate(this),onDrag:this.onDrag.createDelegate(this),onEnd:this.onDragEnd.createDelegate(this),tolerance:3,autoStart:300});this.tracker.initEl(a)},onBeforeDragStart:function(a){if(this.disabled){return false}else{this.slider.promoteThumb(this);return true}},onDragStart:function(a){this.el.addClass("x-slider-thumb-drag");this.dragging=true;this.dragStartValue=this.value;this.slider.fireEvent("dragstart",this.slider,a,this)},onDrag:function(g){var c=this.slider,b=this.index,d=this.getNewValue();if(this.constrain){var a=c.thumbs[b+1],h=c.thumbs[b-1];if(h!=undefined&&d<=h.value){d=h.value}if(a!=undefined&&d>=a.value){d=a.value}}c.setValue(b,d,false);c.fireEvent("drag",c,g,this)},getNewValue:function(){var a=this.slider,b=a.innerEl.translatePoints(this.tracker.getXY());return Ext.util.Format.round(a.reverseValue(b.left),a.decimalPrecision)},onDragEnd:function(c){var a=this.slider,b=this.value;this.el.removeClass("x-slider-thumb-drag");this.dragging=false;a.fireEvent("dragend",a,c);if(this.dragStartValue!=b){a.fireEvent("changecomplete",a,b,this)}},destroy:function(){Ext.destroyMembers(this,"tracker","el")}});Ext.slider.MultiSlider=Ext.extend(Ext.BoxComponent,{vertical:false,minValue:0,maxValue:100,decimalPrecision:0,keyIncrement:1,increment:0,clickRange:[5,15],clickToChange:true,animate:true,constrainThumbs:true,topThumbZIndex:10000,initComponent:function(){if(!Ext.isDefined(this.value)){this.value=this.minValue}this.thumbs=[];Ext.slider.MultiSlider.superclass.initComponent.call(this);this.keyIncrement=Math.max(this.increment,this.keyIncrement);this.addEvents("beforechange","change","changecomplete","dragstart","drag","dragend");if(this.values==undefined||Ext.isEmpty(this.values)){this.values=[0]}var a=this.values;for(var b=0;b<a.length;b++){this.addThumb(a[b])}if(this.vertical){Ext.apply(this,Ext.slider.Vertical)}},addThumb:function(b){var a=new Ext.slider.Thumb({value:b,slider:this,index:this.thumbs.length,constrain:this.constrainThumbs});this.thumbs.push(a);if(this.rendered){a.render()}},promoteThumb:function(d){var a=this.thumbs,g,b;for(var e=0,c=a.length;e<c;e++){b=a[e];if(b==d){g=this.topThumbZIndex}else{g=""}b.el.setStyle("zIndex",g)}},onRender:function(){this.autoEl={cls:"x-slider "+(this.vertical?"x-slider-vert":"x-slider-horz"),cn:{cls:"x-slider-end",cn:{cls:"x-slider-inner",cn:[{tag:"a",cls:"x-slider-focus",href:"#",tabIndex:"-1",hidefocus:"on"}]}}};Ext.slider.MultiSlider.superclass.onRender.apply(this,arguments);this.endEl=this.el.first();this.innerEl=this.endEl.first();this.focusEl=this.innerEl.child(".x-slider-focus");for(var b=0;b<this.thumbs.length;b++){this.thumbs[b].render()}var a=this.innerEl.child(".x-slider-thumb");this.halfThumb=(this.vertical?a.getHeight():a.getWidth())/2;this.initEvents()},initEvents:function(){this.mon(this.el,{scope:this,mousedown:this.onMouseDown,keydown:this.onKeyDown});this.focusEl.swallowEvent("click",true)},onMouseDown:function(d){if(this.disabled){return}var c=false;for(var b=0;b<this.thumbs.length;b++){c=c||d.target==this.thumbs[b].el.dom}if(this.clickToChange&&!c){var a=this.innerEl.translatePoints(d.getXY());this.onClickChange(a)}this.focus()},onClickChange:function(c){if(c.top>this.clickRange[0]&&c.top<this.clickRange[1]){var a=this.getNearest(c,"left"),b=a.index;this.setValue(b,Ext.util.Format.round(this.reverseValue(c.left),this.decimalPrecision),undefined,true)}},getNearest:function(l,b){var n=b=="top"?this.innerEl.getHeight()-l[b]:l[b],g=this.reverseValue(n),k=(this.maxValue-this.minValue)+5,e=0,c=null;for(var d=0;d<this.thumbs.length;d++){var a=this.thumbs[d],m=a.value,h=Math.abs(m-g);if(Math.abs(h<=k)){c=a;e=d;k=h}}return c},onKeyDown:function(b){if(this.disabled||this.thumbs.length!==1){b.preventDefault();return}var a=b.getKey(),c;switch(a){case b.UP:case b.RIGHT:b.stopEvent();c=b.ctrlKey?this.maxValue:this.getValue(0)+this.keyIncrement;this.setValue(0,c,undefined,true);break;case b.DOWN:case b.LEFT:b.stopEvent();c=b.ctrlKey?this.minValue:this.getValue(0)-this.keyIncrement;this.setValue(0,c,undefined,true);break;default:b.preventDefault()}},doSnap:function(b){if(!(this.increment&&b)){return b}var d=b,c=this.increment,a=b%c;if(a!=0){d-=a;if(a*2>=c){d+=c}else{if(a*2<-c){d-=c}}}return d.constrain(this.minValue,this.maxValue)},afterRender:function(){Ext.slider.MultiSlider.superclass.afterRender.apply(this,arguments);for(var c=0;c<this.thumbs.length;c++){var b=this.thumbs[c];if(b.value!==undefined){var a=this.normalizeValue(b.value);if(a!==b.value){this.setValue(c,a,false)}else{this.moveThumb(c,this.translateValue(a),false)}}}},getRatio:function(){var a=this.innerEl.getWidth(),b=this.maxValue-this.minValue;return b==0?a:(a/b)},normalizeValue:function(a){a=this.doSnap(a);a=Ext.util.Format.round(a,this.decimalPrecision);a=a.constrain(this.minValue,this.maxValue);return a},setMinValue:function(e){this.minValue=e;var d=0,b=this.thumbs,a=b.length,c;for(;d<a;++d){c=b[d];c.value=c.value<e?e:c.value}this.syncThumb()},setMaxValue:function(e){this.maxValue=e;var d=0,b=this.thumbs,a=b.length,c;for(;d<a;++d){c=b[d];c.value=c.value>e?e:c.value}this.syncThumb()},setValue:function(d,c,b,g){var a=this.thumbs[d],e=a.el;c=this.normalizeValue(c);if(c!==a.value&&this.fireEvent("beforechange",this,c,a.value,a)!==false){a.value=c;if(this.rendered){this.moveThumb(d,this.translateValue(c),b!==false);this.fireEvent("change",this,c,a);if(g){this.fireEvent("changecomplete",this,c,a)}}}},translateValue:function(a){var b=this.getRatio();return(a*b)-(this.minValue*b)-this.halfThumb},reverseValue:function(b){var a=this.getRatio();return(b+(this.minValue*a))/a},moveThumb:function(d,c,b){var a=this.thumbs[d].el;if(!b||this.animate===false){a.setLeft(c)}else{a.shift({left:c,stopFx:true,duration:0.35})}},focus:function(){this.focusEl.focus(10)},onResize:function(c,e){var b=this.thumbs,a=b.length,d=0;for(;d<a;++d){b[d].el.stopFx()}if(Ext.isNumber(c)){this.innerEl.setWidth(c-(this.el.getPadding("l")+this.endEl.getPadding("r")))}this.syncThumb();Ext.slider.MultiSlider.superclass.onResize.apply(this,arguments)},onDisable:function(){Ext.slider.MultiSlider.superclass.onDisable.call(this);for(var b=0;b<this.thumbs.length;b++){var a=this.thumbs[b],c=a.el;a.disable();if(Ext.isIE){var d=c.getXY();c.hide();this.innerEl.addClass(this.disabledClass).dom.disabled=true;if(!this.thumbHolder){this.thumbHolder=this.endEl.createChild({cls:"x-slider-thumb "+this.disabledClass})}this.thumbHolder.show().setXY(d)}}},onEnable:function(){Ext.slider.MultiSlider.superclass.onEnable.call(this);for(var b=0;b<this.thumbs.length;b++){var a=this.thumbs[b],c=a.el;a.enable();if(Ext.isIE){this.innerEl.removeClass(this.disabledClass).dom.disabled=false;if(this.thumbHolder){this.thumbHolder.hide()}c.show();this.syncThumb()}}},syncThumb:function(){if(this.rendered){for(var a=0;a<this.thumbs.length;a++){this.moveThumb(a,this.translateValue(this.thumbs[a].value))}}},getValue:function(a){return this.thumbs[a].value},getValues:function(){var a=[];for(var b=0;b<this.thumbs.length;b++){a.push(this.thumbs[b].value)}return a},beforeDestroy:function(){var b=this.thumbs;for(var c=0,a=b.length;c<a;++c){b[c].destroy();b[c]=null}Ext.destroyMembers(this,"endEl","innerEl","focusEl","thumbHolder");Ext.slider.MultiSlider.superclass.beforeDestroy.call(this)}});Ext.reg("multislider",Ext.slider.MultiSlider);Ext.slider.SingleSlider=Ext.extend(Ext.slider.MultiSlider,{constructor:function(a){a=a||{};Ext.applyIf(a,{values:[a.value||0]});Ext.slider.SingleSlider.superclass.constructor.call(this,a)},getValue:function(){return Ext.slider.SingleSlider.superclass.getValue.call(this,0)},setValue:function(d,b){var c=Ext.toArray(arguments),a=c.length;if(a==1||(a<=3&&typeof arguments[1]!="number")){c.unshift(0)}return Ext.slider.SingleSlider.superclass.setValue.apply(this,c)},syncThumb:function(){return Ext.slider.SingleSlider.superclass.syncThumb.apply(this,[0].concat(arguments))},getNearest:function(){return this.thumbs[0]}});Ext.Slider=Ext.slider.SingleSlider;Ext.reg("slider",Ext.slider.SingleSlider);Ext.slider.Vertical={onResize:function(a,b){this.innerEl.setHeight(b-(this.el.getPadding("t")+this.endEl.getPadding("b")));this.syncThumb()},getRatio:function(){var b=this.innerEl.getHeight(),a=this.maxValue-this.minValue;return b/a},moveThumb:function(d,c,b){var a=this.thumbs[d],e=a.el;if(!b||this.animate===false){e.setBottom(c)}else{e.shift({bottom:c,stopFx:true,duration:0.35})}},onClickChange:function(c){if(c.left>this.clickRange[0]&&c.left<this.clickRange[1]){var a=this.getNearest(c,"top"),b=a.index,d=this.minValue+this.reverseValue(this.innerEl.getHeight()-c.top);this.setValue(b,Ext.util.Format.round(d,this.decimalPrecision),undefined,true)}}};Ext.slider.Thumb.Vertical={getNewValue:function(){var b=this.slider,c=b.innerEl,d=c.translatePoints(this.tracker.getXY()),a=c.getHeight()-d.top;return b.minValue+Ext.util.Format.round(a/b.getRatio(),b.decimalPrecision)}};Ext.ProgressBar=Ext.extend(Ext.BoxComponent,{baseCls:"x-progress",animate:false,waitTimer:null,initComponent:function(){Ext.ProgressBar.superclass.initComponent.call(this);this.addEvents("update")},onRender:function(d,a){var c=new Ext.Template('<div class="{cls}-wrap">','<div class="{cls}-inner">','<div class="{cls}-bar">','<div class="{cls}-text">',"<div> </div>","</div>","</div>",'<div class="{cls}-text {cls}-text-back">',"<div> </div>","</div>","</div>","</div>");this.el=a?c.insertBefore(a,{cls:this.baseCls},true):c.append(d,{cls:this.baseCls},true);if(this.id){this.el.dom.id=this.id}var b=this.el.dom.firstChild;this.progressBar=Ext.get(b.firstChild);if(this.textEl){this.textEl=Ext.get(this.textEl);delete this.textTopEl}else{this.textTopEl=Ext.get(this.progressBar.dom.firstChild);var e=Ext.get(b.childNodes[1]);this.textTopEl.setStyle("z-index",99).addClass("x-hidden");this.textEl=new Ext.CompositeElement([this.textTopEl.dom.firstChild,e.dom.firstChild]);this.textEl.setWidth(b.offsetWidth)}this.progressBar.setHeight(b.offsetHeight)},afterRender:function(){Ext.ProgressBar.superclass.afterRender.call(this);if(this.value){this.updateProgress(this.value,this.text)}else{this.updateText(this.text)}},updateProgress:function(c,d,b){this.value=c||0;if(d){this.updateText(d)}if(this.rendered&&!this.isDestroyed){var a=Math.floor(c*this.el.dom.firstChild.offsetWidth);this.progressBar.setWidth(a,b===true||(b!==false&&this.animate));if(this.textTopEl){this.textTopEl.removeClass("x-hidden").setWidth(a)}}this.fireEvent("update",this,c,d);return this},wait:function(b){if(!this.waitTimer){var a=this;b=b||{};this.updateText(b.text);this.waitTimer=Ext.TaskMgr.start({run:function(c){var d=b.increment||10;c-=1;this.updateProgress(((((c+d)%d)+1)*(100/d))*0.01,null,b.animate)},interval:b.interval||1000,duration:b.duration,onStop:function(){if(b.fn){b.fn.apply(b.scope||this)}this.reset()},scope:a})}return this},isWaiting:function(){return this.waitTimer!==null},updateText:function(a){this.text=a||" ";if(this.rendered){this.textEl.update(this.text)}return this},syncProgressBar:function(){if(this.value){this.updateProgress(this.value,this.text)}return this},setSize:function(a,c){Ext.ProgressBar.superclass.setSize.call(this,a,c);if(this.textTopEl){var b=this.el.dom.firstChild;this.textEl.setSize(b.offsetWidth,b.offsetHeight)}this.syncProgressBar();return this},reset:function(a){this.updateProgress(0);if(this.textTopEl){this.textTopEl.addClass("x-hidden")}this.clearTimer();if(a===true){this.hide()}return this},clearTimer:function(){if(this.waitTimer){this.waitTimer.onStop=null;Ext.TaskMgr.stop(this.waitTimer);this.waitTimer=null}},onDestroy:function(){this.clearTimer();if(this.rendered){if(this.textEl.isComposite){this.textEl.clear()}Ext.destroyMembers(this,"textEl","progressBar","textTopEl")}Ext.ProgressBar.superclass.onDestroy.call(this)}});Ext.reg("progress",Ext.ProgressBar);(function(){var a=Ext.EventManager;var b=Ext.lib.Dom;Ext.dd.DragDrop=function(e,c,d){if(e){this.init(e,c,d)}};Ext.dd.DragDrop.prototype={id:null,config:null,dragElId:null,handleElId:null,invalidHandleTypes:null,invalidHandleIds:null,invalidHandleClasses:null,startPageX:0,startPageY:0,groups:null,locked:false,lock:function(){this.locked=true},moveOnly:false,unlock:function(){this.locked=false},isTarget:true,padding:null,_domRef:null,__ygDragDrop:true,constrainX:false,constrainY:false,minX:0,maxX:0,minY:0,maxY:0,maintainOffset:false,xTicks:null,yTicks:null,primaryButtonOnly:true,available:false,hasOuterHandles:false,b4StartDrag:function(c,d){},startDrag:function(c,d){},b4Drag:function(c){},onDrag:function(c){},onDragEnter:function(c,d){},b4DragOver:function(c){},onDragOver:function(c,d){},b4DragOut:function(c){},onDragOut:function(c,d){},b4DragDrop:function(c){},onDragDrop:function(c,d){},onInvalidDrop:function(c){},b4EndDrag:function(c){},endDrag:function(c){},b4MouseDown:function(c){},onMouseDown:function(c){},onMouseUp:function(c){},onAvailable:function(){},defaultPadding:{left:0,right:0,top:0,bottom:0},constrainTo:function(k,h,p){if(Ext.isNumber(h)){h={left:h,right:h,top:h,bottom:h}}h=h||this.defaultPadding;var m=Ext.get(this.getEl()).getBox(),d=Ext.get(k),o=d.getScroll(),l,e=d.dom;if(e==document.body){l={x:o.left,y:o.top,width:Ext.lib.Dom.getViewWidth(),height:Ext.lib.Dom.getViewHeight()}}else{var n=d.getXY();l={x:n[0],y:n[1],width:e.clientWidth,height:e.clientHeight}}var i=m.y-l.y,g=m.x-l.x;this.resetConstraints();this.setXConstraint(g-(h.left||0),l.width-g-m.width-(h.right||0),this.xTickSize);this.setYConstraint(i-(h.top||0),l.height-i-m.height-(h.bottom||0),this.yTickSize)},getEl:function(){if(!this._domRef){this._domRef=Ext.getDom(this.id)}return this._domRef},getDragEl:function(){return Ext.getDom(this.dragElId)},init:function(e,c,d){this.initTarget(e,c,d);a.on(this.id,"mousedown",this.handleMouseDown,this)},initTarget:function(e,c,d){this.config=d||{};this.DDM=Ext.dd.DDM;this.groups={};if(typeof e!=="string"){e=Ext.id(e)}this.id=e;this.addToGroup((c)?c:"default");this.handleElId=e;this.setDragElId(e);this.invalidHandleTypes={A:"A"};this.invalidHandleIds={};this.invalidHandleClasses=[];this.applyConfig();this.handleOnAvailable()},applyConfig:function(){this.padding=this.config.padding||[0,0,0,0];this.isTarget=(this.config.isTarget!==false);this.maintainOffset=(this.config.maintainOffset);this.primaryButtonOnly=(this.config.primaryButtonOnly!==false)},handleOnAvailable:function(){this.available=true;this.resetConstraints();this.onAvailable()},setPadding:function(e,c,g,d){if(!c&&0!==c){this.padding=[e,e,e,e]}else{if(!g&&0!==g){this.padding=[e,c,e,c]}else{this.padding=[e,c,g,d]}}},setInitPosition:function(g,e){var h=this.getEl();if(!this.DDM.verifyEl(h)){return}var d=g||0;var c=e||0;var i=b.getXY(h);this.initPageX=i[0]-d;this.initPageY=i[1]-c;this.lastPageX=i[0];this.lastPageY=i[1];this.setStartPosition(i)},setStartPosition:function(d){var c=d||b.getXY(this.getEl());this.deltaSetXY=null;this.startPageX=c[0];this.startPageY=c[1]},addToGroup:function(c){this.groups[c]=true;this.DDM.regDragDrop(this,c)},removeFromGroup:function(c){if(this.groups[c]){delete this.groups[c]}this.DDM.removeDDFromGroup(this,c)},setDragElId:function(c){this.dragElId=c},setHandleElId:function(c){if(typeof c!=="string"){c=Ext.id(c)}this.handleElId=c;this.DDM.regHandle(this.id,c)},setOuterHandleElId:function(c){if(typeof c!=="string"){c=Ext.id(c)}a.on(c,"mousedown",this.handleMouseDown,this);this.setHandleElId(c);this.hasOuterHandles=true},unreg:function(){a.un(this.id,"mousedown",this.handleMouseDown);this._domRef=null;this.DDM._remove(this)},destroy:function(){this.unreg()},isLocked:function(){return(this.DDM.isLocked()||this.locked)},handleMouseDown:function(g,d){if(this.primaryButtonOnly&&g.button!=0){return}if(this.isLocked()){return}this.DDM.refreshCache(this.groups);var c=new Ext.lib.Point(Ext.lib.Event.getPageX(g),Ext.lib.Event.getPageY(g));if(!this.hasOuterHandles&&!this.DDM.isOverTarget(c,this)){}else{if(this.clickValidator(g)){this.setStartPosition();this.b4MouseDown(g);this.onMouseDown(g);this.DDM.handleMouseDown(g,this);this.DDM.stopEvent(g)}else{}}},clickValidator:function(d){var c=d.getTarget();return(this.isValidHandleChild(c)&&(this.id==this.handleElId||this.DDM.handleWasClicked(c,this.id)))},addInvalidHandleType:function(c){var d=c.toUpperCase();this.invalidHandleTypes[d]=d},addInvalidHandleId:function(c){if(typeof c!=="string"){c=Ext.id(c)}this.invalidHandleIds[c]=c},addInvalidHandleClass:function(c){this.invalidHandleClasses.push(c)},removeInvalidHandleType:function(c){var d=c.toUpperCase();delete this.invalidHandleTypes[d]},removeInvalidHandleId:function(c){if(typeof c!=="string"){c=Ext.id(c)}delete this.invalidHandleIds[c]},removeInvalidHandleClass:function(d){for(var e=0,c=this.invalidHandleClasses.length;e<c;++e){if(this.invalidHandleClasses[e]==d){delete this.invalidHandleClasses[e]}}},isValidHandleChild:function(h){var g=true;var l;try{l=h.nodeName.toUpperCase()}catch(k){l=h.nodeName}g=g&&!this.invalidHandleTypes[l];g=g&&!this.invalidHandleIds[h.id];for(var d=0,c=this.invalidHandleClasses.length;g&&d<c;++d){g=!Ext.fly(h).hasClass(this.invalidHandleClasses[d])}return g},setXTicks:function(g,c){this.xTicks=[];this.xTickSize=c;var e={};for(var d=this.initPageX;d>=this.minX;d=d-c){if(!e[d]){this.xTicks[this.xTicks.length]=d;e[d]=true}}for(d=this.initPageX;d<=this.maxX;d=d+c){if(!e[d]){this.xTicks[this.xTicks.length]=d;e[d]=true}}this.xTicks.sort(this.DDM.numericSort)},setYTicks:function(g,c){this.yTicks=[];this.yTickSize=c;var e={};for(var d=this.initPageY;d>=this.minY;d=d-c){if(!e[d]){this.yTicks[this.yTicks.length]=d;e[d]=true}}for(d=this.initPageY;d<=this.maxY;d=d+c){if(!e[d]){this.yTicks[this.yTicks.length]=d;e[d]=true}}this.yTicks.sort(this.DDM.numericSort)},setXConstraint:function(e,d,c){this.leftConstraint=e;this.rightConstraint=d;this.minX=this.initPageX-e;this.maxX=this.initPageX+d;if(c){this.setXTicks(this.initPageX,c)}this.constrainX=true},clearConstraints:function(){this.constrainX=false;this.constrainY=false;this.clearTicks()},clearTicks:function(){this.xTicks=null;this.yTicks=null;this.xTickSize=0;this.yTickSize=0},setYConstraint:function(c,e,d){this.topConstraint=c;this.bottomConstraint=e;this.minY=this.initPageY-c;this.maxY=this.initPageY+e;if(d){this.setYTicks(this.initPageY,d)}this.constrainY=true},resetConstraints:function(){if(this.initPageX||this.initPageX===0){var d=(this.maintainOffset)?this.lastPageX-this.initPageX:0;var c=(this.maintainOffset)?this.lastPageY-this.initPageY:0;this.setInitPosition(d,c)}else{this.setInitPosition()}if(this.constrainX){this.setXConstraint(this.leftConstraint,this.rightConstraint,this.xTickSize)}if(this.constrainY){this.setYConstraint(this.topConstraint,this.bottomConstraint,this.yTickSize)}},getTick:function(l,g){if(!g){return l}else{if(g[0]>=l){return g[0]}else{for(var d=0,c=g.length;d<c;++d){var e=d+1;if(g[e]&&g[e]>=l){var k=l-g[d];var h=g[e]-l;return(h>k)?g[d]:g[e]}}return g[g.length-1]}}},toString:function(){return("DragDrop "+this.id)}}})();if(!Ext.dd.DragDropMgr){Ext.dd.DragDropMgr=function(){var a=Ext.EventManager;return{ids:{},handleIds:{},dragCurrent:null,dragOvers:{},deltaX:0,deltaY:0,preventDefault:true,stopPropagation:true,initialized:false,locked:false,init:function(){this.initialized=true},POINT:0,INTERSECT:1,mode:0,_execOnAll:function(d,c){for(var e in this.ids){for(var b in this.ids[e]){var g=this.ids[e][b];if(!this.isTypeOfDD(g)){continue}g[d].apply(g,c)}}},_onLoad:function(){this.init();a.on(document,"mouseup",this.handleMouseUp,this,true);a.on(document,"mousemove",this.handleMouseMove,this,true);a.on(window,"unload",this._onUnload,this,true);a.on(window,"resize",this._onResize,this,true)},_onResize:function(b){this._execOnAll("resetConstraints",[])},lock:function(){this.locked=true},unlock:function(){this.locked=false},isLocked:function(){return this.locked},locationCache:{},useCache:true,clickPixelThresh:3,clickTimeThresh:350,dragThreshMet:false,clickTimeout:null,startX:0,startY:0,regDragDrop:function(c,b){if(!this.initialized){this.init()}if(!this.ids[b]){this.ids[b]={}}this.ids[b][c.id]=c},removeDDFromGroup:function(d,b){if(!this.ids[b]){this.ids[b]={}}var c=this.ids[b];if(c&&c[d.id]){delete c[d.id]}},_remove:function(c){for(var b in c.groups){if(b&&this.ids[b]&&this.ids[b][c.id]){delete this.ids[b][c.id]}}delete this.handleIds[c.id]},regHandle:function(c,b){if(!this.handleIds[c]){this.handleIds[c]={}}this.handleIds[c][b]=b},isDragDrop:function(b){return(this.getDDById(b))?true:false},getRelated:function(h,c){var g=[];for(var e in h.groups){for(var d in this.ids[e]){var b=this.ids[e][d];if(!this.isTypeOfDD(b)){continue}if(!c||b.isTarget){g[g.length]=b}}}return g},isLegalTarget:function(g,e){var c=this.getRelated(g,true);for(var d=0,b=c.length;d<b;++d){if(c[d].id==e.id){return true}}return false},isTypeOfDD:function(b){return(b&&b.__ygDragDrop)},isHandle:function(c,b){return(this.handleIds[c]&&this.handleIds[c][b])},getDDById:function(c){for(var b in this.ids){if(this.ids[b][c]){return this.ids[b][c]}}return null},handleMouseDown:function(d,c){if(Ext.QuickTips){Ext.QuickTips.ddDisable()}if(this.dragCurrent){this.handleMouseUp(d)}this.currentTarget=d.getTarget();this.dragCurrent=c;var b=c.getEl();this.startX=d.getPageX();this.startY=d.getPageY();this.deltaX=this.startX-b.offsetLeft;this.deltaY=this.startY-b.offsetTop;this.dragThreshMet=false;this.clickTimeout=setTimeout(function(){var e=Ext.dd.DDM;e.startDrag(e.startX,e.startY)},this.clickTimeThresh)},startDrag:function(b,c){clearTimeout(this.clickTimeout);if(this.dragCurrent){this.dragCurrent.b4StartDrag(b,c);this.dragCurrent.startDrag(b,c)}this.dragThreshMet=true},handleMouseUp:function(b){if(Ext.QuickTips){Ext.QuickTips.ddEnable()}if(!this.dragCurrent){return}clearTimeout(this.clickTimeout);if(this.dragThreshMet){this.fireEvents(b,true)}else{}this.stopDrag(b);this.stopEvent(b)},stopEvent:function(b){if(this.stopPropagation){b.stopPropagation()}if(this.preventDefault){b.preventDefault()}},stopDrag:function(b){if(this.dragCurrent){if(this.dragThreshMet){this.dragCurrent.b4EndDrag(b);this.dragCurrent.endDrag(b)}this.dragCurrent.onMouseUp(b)}this.dragCurrent=null;this.dragOvers={}},handleMouseMove:function(d){if(!this.dragCurrent){return true}if(Ext.isIE&&(d.button!==0&&d.button!==1&&d.button!==2)){this.stopEvent(d);return this.handleMouseUp(d)}if(!this.dragThreshMet){var c=Math.abs(this.startX-d.getPageX());var b=Math.abs(this.startY-d.getPageY());if(c>this.clickPixelThresh||b>this.clickPixelThresh){this.startDrag(this.startX,this.startY)}}if(this.dragThreshMet){this.dragCurrent.b4Drag(d);this.dragCurrent.onDrag(d);if(!this.dragCurrent.moveOnly){this.fireEvents(d,false)}}this.stopEvent(d);return true},fireEvents:function(o,p){var r=this.dragCurrent;if(!r||r.isLocked()){return}var s=o.getPoint();var b=[];var g=[];var m=[];var k=[];var d=[];for(var h in this.dragOvers){var c=this.dragOvers[h];if(!this.isTypeOfDD(c)){continue}if(!this.isOverTarget(s,c,this.mode)){g.push(c)}b[h]=true;delete this.dragOvers[h]}for(var q in r.groups){if("string"!=typeof q){continue}for(h in this.ids[q]){var l=this.ids[q][h];if(!this.isTypeOfDD(l)){continue}if(l.isTarget&&!l.isLocked()&&((l!=r)||(r.ignoreSelf===false))){if(this.isOverTarget(s,l,this.mode)){if(p){k.push(l)}else{if(!b[l.id]){d.push(l)}else{m.push(l)}this.dragOvers[l.id]=l}}}}}if(this.mode){if(g.length){r.b4DragOut(o,g);r.onDragOut(o,g)}if(d.length){r.onDragEnter(o,d)}if(m.length){r.b4DragOver(o,m);r.onDragOver(o,m)}if(k.length){r.b4DragDrop(o,k);r.onDragDrop(o,k)}}else{var n=0;for(h=0,n=g.length;h<n;++h){r.b4DragOut(o,g[h].id);r.onDragOut(o,g[h].id)}for(h=0,n=d.length;h<n;++h){r.onDragEnter(o,d[h].id)}for(h=0,n=m.length;h<n;++h){r.b4DragOver(o,m[h].id);r.onDragOver(o,m[h].id)}for(h=0,n=k.length;h<n;++h){r.b4DragDrop(o,k[h].id);r.onDragDrop(o,k[h].id)}}if(p&&!k.length){r.onInvalidDrop(o)}},getBestMatch:function(d){var g=null;var c=d.length;if(c==1){g=d[0]}else{for(var e=0;e<c;++e){var b=d[e];if(b.cursorIsOver){g=b;break}else{if(!g||g.overlap.getArea()<b.overlap.getArea()){g=b}}}}return g},refreshCache:function(c){for(var b in c){if("string"!=typeof b){continue}for(var d in this.ids[b]){var e=this.ids[b][d];if(this.isTypeOfDD(e)){var g=this.getLocation(e);if(g){this.locationCache[e.id]=g}else{delete this.locationCache[e.id]}}}}},verifyEl:function(c){if(c){var b;if(Ext.isIE){try{b=c.offsetParent}catch(d){}}else{b=c.offsetParent}if(b){return true}}return false},getLocation:function(k){if(!this.isTypeOfDD(k)){return null}var h=k.getEl(),o,g,d,q,p,s,c,n,i;try{o=Ext.lib.Dom.getXY(h)}catch(m){}if(!o){return null}g=o[0];d=g+h.offsetWidth;q=o[1];p=q+h.offsetHeight;s=q-k.padding[0];c=d+k.padding[1];n=p+k.padding[2];i=g-k.padding[3];return new Ext.lib.Region(s,c,n,i)},isOverTarget:function(l,b,d){var g=this.locationCache[b.id];if(!g||!this.useCache){g=this.getLocation(b);this.locationCache[b.id]=g}if(!g){return false}b.cursorIsOver=g.contains(l);var k=this.dragCurrent;if(!k||!k.getTargetCoord||(!d&&!k.constrainX&&!k.constrainY)){return b.cursorIsOver}b.overlap=null;var h=k.getTargetCoord(l.x,l.y);var c=k.getDragEl();var e=new Ext.lib.Region(h.y,h.x+c.offsetWidth,h.y+c.offsetHeight,h.x);var i=e.intersect(g);if(i){b.overlap=i;return(d)?true:b.cursorIsOver}else{return false}},_onUnload:function(c,b){Ext.dd.DragDropMgr.unregAll()},unregAll:function(){if(this.dragCurrent){this.stopDrag();this.dragCurrent=null}this._execOnAll("unreg",[]);for(var b in this.elementCache){delete this.elementCache[b]}this.elementCache={};this.ids={}},elementCache:{},getElWrapper:function(c){var b=this.elementCache[c];if(!b||!b.el){b=this.elementCache[c]=new this.ElementWrapper(Ext.getDom(c))}return b},getElement:function(b){return Ext.getDom(b)},getCss:function(c){var b=Ext.getDom(c);return(b)?b.style:null},ElementWrapper:function(b){this.el=b||null;this.id=this.el&&b.id;this.css=this.el&&b.style},getPosX:function(b){return Ext.lib.Dom.getX(b)},getPosY:function(b){return Ext.lib.Dom.getY(b)},swapNode:function(d,b){if(d.swapNode){d.swapNode(b)}else{var e=b.parentNode;var c=b.nextSibling;if(c==d){e.insertBefore(d,b)}else{if(b==d.nextSibling){e.insertBefore(b,d)}else{d.parentNode.replaceChild(b,d);e.insertBefore(d,c)}}}},getScroll:function(){var d,b,e=document.documentElement,c=document.body;if(e&&(e.scrollTop||e.scrollLeft)){d=e.scrollTop;b=e.scrollLeft}else{if(c){d=c.scrollTop;b=c.scrollLeft}else{}}return{top:d,left:b}},getStyle:function(c,b){return Ext.fly(c).getStyle(b)},getScrollTop:function(){return this.getScroll().top},getScrollLeft:function(){return this.getScroll().left},moveToEl:function(b,d){var c=Ext.lib.Dom.getXY(d);Ext.lib.Dom.setXY(b,c)},numericSort:function(d,c){return(d-c)},_timeoutCount:0,_addListeners:function(){var b=Ext.dd.DDM;if(Ext.lib.Event&&document){b._onLoad()}else{if(b._timeoutCount>2000){}else{setTimeout(b._addListeners,10);if(document&&document.body){b._timeoutCount+=1}}}},handleWasClicked:function(b,d){if(this.isHandle(d,b.id)){return true}else{var c=b.parentNode;while(c){if(this.isHandle(d,c.id)){return true}else{c=c.parentNode}}}return false}}}();Ext.dd.DDM=Ext.dd.DragDropMgr;Ext.dd.DDM._addListeners()}Ext.dd.DD=function(c,a,b){if(c){this.init(c,a,b)}};Ext.extend(Ext.dd.DD,Ext.dd.DragDrop,{scroll:true,autoOffset:function(c,b){var a=c-this.startPageX;var d=b-this.startPageY;this.setDelta(a,d)},setDelta:function(b,a){this.deltaX=b;this.deltaY=a},setDragElPos:function(c,b){var a=this.getDragEl();this.alignElWithMouse(a,c,b)},alignElWithMouse:function(c,h,g){var e=this.getTargetCoord(h,g);var b=c.dom?c:Ext.fly(c,"_dd");if(!this.deltaSetXY){var i=[e.x,e.y];b.setXY(i);var d=b.getLeft(true);var a=b.getTop(true);this.deltaSetXY=[d-e.x,a-e.y]}else{b.setLeftTop(e.x+this.deltaSetXY[0],e.y+this.deltaSetXY[1])}this.cachePosition(e.x,e.y);this.autoScroll(e.x,e.y,c.offsetHeight,c.offsetWidth);return e},cachePosition:function(b,a){if(b){this.lastPageX=b;this.lastPageY=a}else{var c=Ext.lib.Dom.getXY(this.getEl());this.lastPageX=c[0];this.lastPageY=c[1]}},autoScroll:function(m,l,e,n){if(this.scroll){var o=Ext.lib.Dom.getViewHeight();var b=Ext.lib.Dom.getViewWidth();var q=this.DDM.getScrollTop();var d=this.DDM.getScrollLeft();var k=e+l;var p=n+m;var i=(o+q-l-this.deltaY);var g=(b+d-m-this.deltaX);var c=40;var a=(document.all)?80:30;if(k>o&&i<c){window.scrollTo(d,q+a)}if(l<q&&q>0&&l-q<c){window.scrollTo(d,q-a)}if(p>b&&g<c){window.scrollTo(d+a,q)}if(m<d&&d>0&&m-d<c){window.scrollTo(d-a,q)}}},getTargetCoord:function(c,b){var a=c-this.deltaX;var d=b-this.deltaY;if(this.constrainX){if(a<this.minX){a=this.minX}if(a>this.maxX){a=this.maxX}}if(this.constrainY){if(d<this.minY){d=this.minY}if(d>this.maxY){d=this.maxY}}a=this.getTick(a,this.xTicks);d=this.getTick(d,this.yTicks);return{x:a,y:d}},applyConfig:function(){Ext.dd.DD.superclass.applyConfig.call(this);this.scroll=(this.config.scroll!==false)},b4MouseDown:function(a){this.autoOffset(a.getPageX(),a.getPageY())},b4Drag:function(a){this.setDragElPos(a.getPageX(),a.getPageY())},toString:function(){return("DD "+this.id)}});Ext.dd.DDProxy=function(c,a,b){if(c){this.init(c,a,b);this.initFrame()}};Ext.dd.DDProxy.dragElId="ygddfdiv";Ext.extend(Ext.dd.DDProxy,Ext.dd.DD,{resizeFrame:true,centerFrame:false,createFrame:function(){var b=this;var a=document.body;if(!a||!a.firstChild){setTimeout(function(){b.createFrame()},50);return}var d=this.getDragEl();if(!d){d=document.createElement("div");d.id=this.dragElId;var c=d.style;c.position="absolute";c.visibility="hidden";c.cursor="move";c.border="2px solid #aaa";c.zIndex=999;a.insertBefore(d,a.firstChild)}},initFrame:function(){this.createFrame()},applyConfig:function(){Ext.dd.DDProxy.superclass.applyConfig.call(this);this.resizeFrame=(this.config.resizeFrame!==false);this.centerFrame=(this.config.centerFrame);this.setDragElId(this.config.dragElId||Ext.dd.DDProxy.dragElId)},showFrame:function(e,d){var c=this.getEl();var a=this.getDragEl();var b=a.style;this._resizeProxy();if(this.centerFrame){this.setDelta(Math.round(parseInt(b.width,10)/2),Math.round(parseInt(b.height,10)/2))}this.setDragElPos(e,d);Ext.fly(a).show()},_resizeProxy:function(){if(this.resizeFrame){var a=this.getEl();Ext.fly(this.getDragEl()).setSize(a.offsetWidth,a.offsetHeight)}},b4MouseDown:function(b){var a=b.getPageX();var c=b.getPageY();this.autoOffset(a,c);this.setDragElPos(a,c)},b4StartDrag:function(a,b){this.showFrame(a,b)},b4EndDrag:function(a){Ext.fly(this.getDragEl()).hide()},endDrag:function(c){var b=this.getEl();var a=this.getDragEl();a.style.visibility="";this.beforeMove();b.style.visibility="hidden";Ext.dd.DDM.moveToEl(b,a);a.style.visibility="hidden";b.style.visibility="";this.afterDrag()},beforeMove:function(){},afterDrag:function(){},toString:function(){return("DDProxy "+this.id)}});Ext.dd.DDTarget=function(c,a,b){if(c){this.initTarget(c,a,b)}};Ext.extend(Ext.dd.DDTarget,Ext.dd.DragDrop,{getDragEl:Ext.emptyFn,isValidHandleChild:Ext.emptyFn,startDrag:Ext.emptyFn,endDrag:Ext.emptyFn,onDrag:Ext.emptyFn,onDragDrop:Ext.emptyFn,onDragEnter:Ext.emptyFn,onDragOut:Ext.emptyFn,onDragOver:Ext.emptyFn,onInvalidDrop:Ext.emptyFn,onMouseDown:Ext.emptyFn,onMouseUp:Ext.emptyFn,setXConstraint:Ext.emptyFn,setYConstraint:Ext.emptyFn,resetConstraints:Ext.emptyFn,clearConstraints:Ext.emptyFn,clearTicks:Ext.emptyFn,setInitPosition:Ext.emptyFn,setDragElId:Ext.emptyFn,setHandleElId:Ext.emptyFn,setOuterHandleElId:Ext.emptyFn,addInvalidHandleClass:Ext.emptyFn,addInvalidHandleId:Ext.emptyFn,addInvalidHandleType:Ext.emptyFn,removeInvalidHandleClass:Ext.emptyFn,removeInvalidHandleId:Ext.emptyFn,removeInvalidHandleType:Ext.emptyFn,toString:function(){return("DDTarget "+this.id)}});Ext.dd.DragTracker=Ext.extend(Ext.util.Observable,{active:false,tolerance:5,autoStart:false,constructor:function(a){Ext.apply(this,a);this.addEvents("mousedown","mouseup","mousemove","dragstart","dragend","drag");this.dragRegion=new Ext.lib.Region(0,0,0,0);if(this.el){this.initEl(this.el)}Ext.dd.DragTracker.superclass.constructor.call(this,a)},initEl:function(a){this.el=Ext.get(a);a.on("mousedown",this.onMouseDown,this,this.delegate?{delegate:this.delegate}:undefined)},destroy:function(){this.el.un("mousedown",this.onMouseDown,this);delete this.el},onMouseDown:function(b,a){if(this.fireEvent("mousedown",this,b)!==false&&this.onBeforeStart(b)!==false){this.startXY=this.lastXY=b.getXY();this.dragTarget=this.delegate?a:this.el.dom;if(this.preventDefault!==false){b.preventDefault()}Ext.getDoc().on({scope:this,mouseup:this.onMouseUp,mousemove:this.onMouseMove,selectstart:this.stopSelect});if(this.autoStart){this.timer=this.triggerStart.defer(this.autoStart===true?1000:this.autoStart,this,[b])}}},onMouseMove:function(d,c){if(this.active&&Ext.isIE&&!d.browserEvent.button){d.preventDefault();this.onMouseUp(d);return}d.preventDefault();var b=d.getXY(),a=this.startXY;this.lastXY=b;if(!this.active){if(Math.abs(a[0]-b[0])>this.tolerance||Math.abs(a[1]-b[1])>this.tolerance){this.triggerStart(d)}else{return}}this.fireEvent("mousemove",this,d);this.onDrag(d);this.fireEvent("drag",this,d)},onMouseUp:function(c){var b=Ext.getDoc(),a=this.active;b.un("mousemove",this.onMouseMove,this);b.un("mouseup",this.onMouseUp,this);b.un("selectstart",this.stopSelect,this);c.preventDefault();this.clearStart();this.active=false;delete this.elRegion;this.fireEvent("mouseup",this,c);if(a){this.onEnd(c);this.fireEvent("dragend",this,c)}},triggerStart:function(a){this.clearStart();this.active=true;this.onStart(a);this.fireEvent("dragstart",this,a)},clearStart:function(){if(this.timer){clearTimeout(this.timer);delete this.timer}},stopSelect:function(a){a.stopEvent();return false},onBeforeStart:function(a){},onStart:function(a){},onDrag:function(a){},onEnd:function(a){},getDragTarget:function(){return this.dragTarget},getDragCt:function(){return this.el},getXY:function(a){return a?this.constrainModes[a].call(this,this.lastXY):this.lastXY},getOffset:function(c){var b=this.getXY(c),a=this.startXY;return[a[0]-b[0],a[1]-b[1]]},constrainModes:{point:function(b){if(!this.elRegion){this.elRegion=this.getDragCt().getRegion()}var a=this.dragRegion;a.left=b[0];a.top=b[1];a.right=b[0];a.bottom=b[1];a.constrainTo(this.elRegion);return[a.left,a.top]}}});Ext.dd.ScrollManager=function(){var c=Ext.dd.DragDropMgr;var e={};var b=null;var i={};var h=function(m){b=null;a()};var k=function(){if(c.dragCurrent){c.refreshCache(c.dragCurrent.groups)}};var d=function(){if(c.dragCurrent){var m=Ext.dd.ScrollManager;var n=i.el.ddScrollConfig?i.el.ddScrollConfig.increment:m.increment;if(!m.animate){if(i.el.scroll(i.dir,n)){k()}}else{i.el.scroll(i.dir,n,true,m.animDuration,k)}}};var a=function(){if(i.id){clearInterval(i.id)}i.id=0;i.el=null;i.dir=""};var g=function(n,m){a();i.el=n;i.dir=m;var p=n.ddScrollConfig?n.ddScrollConfig.ddGroup:undefined,o=(n.ddScrollConfig&&n.ddScrollConfig.frequency)?n.ddScrollConfig.frequency:Ext.dd.ScrollManager.frequency;if(p===undefined||c.dragCurrent.ddGroup==p){i.id=setInterval(d,o)}};var l=function(p,s){if(s||!c.dragCurrent){return}var t=Ext.dd.ScrollManager;if(!b||b!=c.dragCurrent){b=c.dragCurrent;t.refreshCache()}var u=Ext.lib.Event.getXY(p);var v=new Ext.lib.Point(u[0],u[1]);for(var n in e){var o=e[n],m=o._region;var q=o.ddScrollConfig?o.ddScrollConfig:t;if(m&&m.contains(v)&&o.isScrollable()){if(m.bottom-v.y<=q.vthresh){if(i.el!=o){g(o,"down")}return}else{if(m.right-v.x<=q.hthresh){if(i.el!=o){g(o,"left")}return}else{if(v.y-m.top<=q.vthresh){if(i.el!=o){g(o,"up")}return}else{if(v.x-m.left<=q.hthresh){if(i.el!=o){g(o,"right")}return}}}}}}a()};c.fireEvents=c.fireEvents.createSequence(l,c);c.stopDrag=c.stopDrag.createSequence(h,c);return{register:function(o){if(Ext.isArray(o)){for(var n=0,m=o.length;n<m;n++){this.register(o[n])}}else{o=Ext.get(o);e[o.id]=o}},unregister:function(o){if(Ext.isArray(o)){for(var n=0,m=o.length;n<m;n++){this.unregister(o[n])}}else{o=Ext.get(o);delete e[o.id]}},vthresh:25,hthresh:25,increment:100,frequency:500,animate:true,animDuration:0.4,ddGroup:undefined,refreshCache:function(){for(var m in e){if(typeof e[m]=="object"){e[m]._region=e[m].getRegion()}}}}}();Ext.dd.Registry=function(){var d={};var b={};var a=0;var c=function(g,e){if(typeof g=="string"){return g}var h=g.id;if(!h&&e!==false){h="extdd-"+(++a);g.id=h}return h};return{register:function(k,l){l=l||{};if(typeof k=="string"){k=document.getElementById(k)}l.ddel=k;d[c(k)]=l;if(l.isHandle!==false){b[l.ddel.id]=l}if(l.handles){var h=l.handles;for(var g=0,e=h.length;g<e;g++){b[c(h[g])]=l}}},unregister:function(k){var m=c(k,false);var l=d[m];if(l){delete d[m];if(l.handles){var h=l.handles;for(var g=0,e=h.length;g<e;g++){delete b[c(h[g],false)]}}}},getHandle:function(e){if(typeof e!="string"){e=e.id}return b[e]},getHandleFromEvent:function(h){var g=Ext.lib.Event.getTarget(h);return g?b[g.id]:null},getTarget:function(e){if(typeof e!="string"){e=e.id}return d[e]},getTargetFromEvent:function(h){var g=Ext.lib.Event.getTarget(h);return g?d[g.id]||b[g.id]:null}}}();Ext.dd.StatusProxy=function(a){Ext.apply(this,a);this.id=this.id||Ext.id();this.el=new Ext.Layer({dh:{id:this.id,tag:"div",cls:"x-dd-drag-proxy "+this.dropNotAllowed,children:[{tag:"div",cls:"x-dd-drop-icon"},{tag:"div",cls:"x-dd-drag-ghost"}]},shadow:!a||a.shadow!==false});this.ghost=Ext.get(this.el.dom.childNodes[1]);this.dropStatus=this.dropNotAllowed};Ext.dd.StatusProxy.prototype={dropAllowed:"x-dd-drop-ok",dropNotAllowed:"x-dd-drop-nodrop",setStatus:function(a){a=a||this.dropNotAllowed;if(this.dropStatus!=a){this.el.replaceClass(this.dropStatus,a);this.dropStatus=a}},reset:function(a){this.el.dom.className="x-dd-drag-proxy "+this.dropNotAllowed;this.dropStatus=this.dropNotAllowed;if(a){this.ghost.update("")}},update:function(a){if(typeof a=="string"){this.ghost.update(a)}else{this.ghost.update("");a.style.margin="0";this.ghost.dom.appendChild(a)}var b=this.ghost.dom.firstChild;if(b){Ext.fly(b).setStyle("float","none")}},getEl:function(){return this.el},getGhost:function(){return this.ghost},hide:function(a){this.el.hide();if(a){this.reset(true)}},stop:function(){if(this.anim&&this.anim.isAnimated&&this.anim.isAnimated()){this.anim.stop()}},show:function(){this.el.show()},sync:function(){this.el.sync()},repair:function(b,c,a){this.callback=c;this.scope=a;if(b&&this.animRepair!==false){this.el.addClass("x-dd-drag-repair");this.el.hideUnders(true);this.anim=this.el.shift({duration:this.repairDuration||0.5,easing:"easeOut",xy:b,stopFx:true,callback:this.afterRepair,scope:this})}else{this.afterRepair()}},afterRepair:function(){this.hide(true);if(typeof this.callback=="function"){this.callback.call(this.scope||this)}this.callback=null;this.scope=null},destroy:function(){Ext.destroy(this.ghost,this.el)}};Ext.dd.DragSource=function(b,a){this.el=Ext.get(b);if(!this.dragData){this.dragData={}}Ext.apply(this,a);if(!this.proxy){this.proxy=new Ext.dd.StatusProxy()}Ext.dd.DragSource.superclass.constructor.call(this,this.el.dom,this.ddGroup||this.group,{dragElId:this.proxy.id,resizeFrame:false,isTarget:false,scroll:this.scroll===true});this.dragging=false};Ext.extend(Ext.dd.DragSource,Ext.dd.DDProxy,{dropAllowed:"x-dd-drop-ok",dropNotAllowed:"x-dd-drop-nodrop",getDragData:function(a){return this.dragData},onDragEnter:function(c,d){var b=Ext.dd.DragDropMgr.getDDById(d);this.cachedTarget=b;if(this.beforeDragEnter(b,c,d)!==false){if(b.isNotifyTarget){var a=b.notifyEnter(this,c,this.dragData);this.proxy.setStatus(a)}else{this.proxy.setStatus(this.dropAllowed)}if(this.afterDragEnter){this.afterDragEnter(b,c,d)}}},beforeDragEnter:function(b,a,c){return true},alignElWithMouse:function(){Ext.dd.DragSource.superclass.alignElWithMouse.apply(this,arguments);this.proxy.sync()},onDragOver:function(c,d){var b=this.cachedTarget||Ext.dd.DragDropMgr.getDDById(d);if(this.beforeDragOver(b,c,d)!==false){if(b.isNotifyTarget){var a=b.notifyOver(this,c,this.dragData);this.proxy.setStatus(a)}if(this.afterDragOver){this.afterDragOver(b,c,d)}}},beforeDragOver:function(b,a,c){return true},onDragOut:function(b,c){var a=this.cachedTarget||Ext.dd.DragDropMgr.getDDById(c);if(this.beforeDragOut(a,b,c)!==false){if(a.isNotifyTarget){a.notifyOut(this,b,this.dragData)}this.proxy.reset();if(this.afterDragOut){this.afterDragOut(a,b,c)}}this.cachedTarget=null},beforeDragOut:function(b,a,c){return true},onDragDrop:function(b,c){var a=this.cachedTarget||Ext.dd.DragDropMgr.getDDById(c);if(this.beforeDragDrop(a,b,c)!==false){if(a.isNotifyTarget){if(a.notifyDrop(this,b,this.dragData)){this.onValidDrop(a,b,c)}else{this.onInvalidDrop(a,b,c)}}else{this.onValidDrop(a,b,c)}if(this.afterDragDrop){this.afterDragDrop(a,b,c)}}delete this.cachedTarget},beforeDragDrop:function(b,a,c){return true},onValidDrop:function(b,a,c){this.hideProxy();if(this.afterValidDrop){this.afterValidDrop(b,a,c)}},getRepairXY:function(b,a){return this.el.getXY()},onInvalidDrop:function(b,a,c){this.beforeInvalidDrop(b,a,c);if(this.cachedTarget){if(this.cachedTarget.isNotifyTarget){this.cachedTarget.notifyOut(this,a,this.dragData)}this.cacheTarget=null}this.proxy.repair(this.getRepairXY(a,this.dragData),this.afterRepair,this);if(this.afterInvalidDrop){this.afterInvalidDrop(a,c)}},afterRepair:function(){if(Ext.enableFx){this.el.highlight(this.hlColor||"c3daf9")}this.dragging=false},beforeInvalidDrop:function(b,a,c){return true},handleMouseDown:function(b){if(this.dragging){return}var a=this.getDragData(b);if(a&&this.onBeforeDrag(a,b)!==false){this.dragData=a;this.proxy.stop();Ext.dd.DragSource.superclass.handleMouseDown.apply(this,arguments)}},onBeforeDrag:function(a,b){return true},onStartDrag:Ext.emptyFn,startDrag:function(a,b){this.proxy.reset();this.dragging=true;this.proxy.update("");this.onInitDrag(a,b);this.proxy.show()},onInitDrag:function(a,c){var b=this.el.dom.cloneNode(true);b.id=Ext.id();this.proxy.update(b);this.onStartDrag(a,c);return true},getProxy:function(){return this.proxy},hideProxy:function(){this.proxy.hide();this.proxy.reset(true);this.dragging=false},triggerCacheRefresh:function(){Ext.dd.DDM.refreshCache(this.groups)},b4EndDrag:function(a){},endDrag:function(a){this.onEndDrag(this.dragData,a)},onEndDrag:function(a,b){},autoOffset:function(a,b){this.setDelta(-12,-20)},destroy:function(){Ext.dd.DragSource.superclass.destroy.call(this);Ext.destroy(this.proxy)}});Ext.dd.DropTarget=Ext.extend(Ext.dd.DDTarget,{constructor:function(b,a){this.el=Ext.get(b);Ext.apply(this,a);if(this.containerScroll){Ext.dd.ScrollManager.register(this.el)}Ext.dd.DropTarget.superclass.constructor.call(this,this.el.dom,this.ddGroup||this.group,{isTarget:true})},dropAllowed:"x-dd-drop-ok",dropNotAllowed:"x-dd-drop-nodrop",isTarget:true,isNotifyTarget:true,notifyEnter:function(a,c,b){if(this.overClass){this.el.addClass(this.overClass)}return this.dropAllowed},notifyOver:function(a,c,b){return this.dropAllowed},notifyOut:function(a,c,b){if(this.overClass){this.el.removeClass(this.overClass)}},notifyDrop:function(a,c,b){return false},destroy:function(){Ext.dd.DropTarget.superclass.destroy.call(this);if(this.containerScroll){Ext.dd.ScrollManager.unregister(this.el)}}});Ext.dd.DragZone=Ext.extend(Ext.dd.DragSource,{constructor:function(b,a){Ext.dd.DragZone.superclass.constructor.call(this,b,a);if(this.containerScroll){Ext.dd.ScrollManager.register(this.el)}},getDragData:function(a){return Ext.dd.Registry.getHandleFromEvent(a)},onInitDrag:function(a,b){this.proxy.update(this.dragData.ddel.cloneNode(true));this.onStartDrag(a,b);return true},afterRepair:function(){if(Ext.enableFx){Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor||"c3daf9")}this.dragging=false},getRepairXY:function(a){return Ext.Element.fly(this.dragData.ddel).getXY()},destroy:function(){Ext.dd.DragZone.superclass.destroy.call(this);if(this.containerScroll){Ext.dd.ScrollManager.unregister(this.el)}}});Ext.dd.DropZone=function(b,a){Ext.dd.DropZone.superclass.constructor.call(this,b,a)};Ext.extend(Ext.dd.DropZone,Ext.dd.DropTarget,{getTargetFromEvent:function(a){return Ext.dd.Registry.getTargetFromEvent(a)},onNodeEnter:function(d,a,c,b){},onNodeOver:function(d,a,c,b){return this.dropAllowed},onNodeOut:function(d,a,c,b){},onNodeDrop:function(d,a,c,b){return false},onContainerOver:function(a,c,b){return this.dropNotAllowed},onContainerDrop:function(a,c,b){return false},notifyEnter:function(a,c,b){return this.dropNotAllowed},notifyOver:function(a,c,b){var d=this.getTargetFromEvent(c);if(!d){if(this.lastOverNode){this.onNodeOut(this.lastOverNode,a,c,b);this.lastOverNode=null}return this.onContainerOver(a,c,b)}if(this.lastOverNode!=d){if(this.lastOverNode){this.onNodeOut(this.lastOverNode,a,c,b)}this.onNodeEnter(d,a,c,b);this.lastOverNode=d}return this.onNodeOver(d,a,c,b)},notifyOut:function(a,c,b){if(this.lastOverNode){this.onNodeOut(this.lastOverNode,a,c,b);this.lastOverNode=null}},notifyDrop:function(a,c,b){if(this.lastOverNode){this.onNodeOut(this.lastOverNode,a,c,b);this.lastOverNode=null}var d=this.getTargetFromEvent(c);return d?this.onNodeDrop(d,a,c,b):this.onContainerDrop(a,c,b)},triggerCacheRefresh:function(){Ext.dd.DDM.refreshCache(this.groups)}});Ext.Element.addMethods({initDD:function(c,b,d){var a=new Ext.dd.DD(Ext.id(this.dom),c,b);return Ext.apply(a,d)},initDDProxy:function(c,b,d){var a=new Ext.dd.DDProxy(Ext.id(this.dom),c,b);return Ext.apply(a,d)},initDDTarget:function(c,b,d){var a=new Ext.dd.DDTarget(Ext.id(this.dom),c,b);return Ext.apply(a,d)}});Ext.data.Api=(function(){var a={};return{actions:{create:"create",read:"read",update:"update",destroy:"destroy"},restActions:{create:"POST",read:"GET",update:"PUT",destroy:"DELETE"},isAction:function(b){return(Ext.data.Api.actions[b])?true:false},getVerb:function(b){if(a[b]){return a[b]}for(var c in this.actions){if(this.actions[c]===b){a[b]=c;break}}return(a[b]!==undefined)?a[b]:null},isValid:function(b){var e=[];var d=this.actions;for(var c in b){if(!(c in d)){e.push(c)}}return(!e.length)?true:e},hasUniqueUrl:function(c,g){var b=(c.api[g])?c.api[g].url:null;var e=true;for(var d in c.api){if((e=(d===g)?true:(c.api[d].url!=b)?true:false)===false){break}}return e},prepare:function(b){if(!b.api){b.api={}}for(var d in this.actions){var c=this.actions[d];b.api[c]=b.api[c]||b.url||b.directFn;if(typeof(b.api[c])=="string"){b.api[c]={url:b.api[c],method:(b.restful===true)?Ext.data.Api.restActions[c]:undefined}}}},restify:function(b){b.restful=true;for(var c in this.restActions){b.api[this.actions[c]].method||(b.api[this.actions[c]].method=this.restActions[c])}b.onWrite=b.onWrite.createInterceptor(function(i,k,g,e){var d=k.reader;var h=new Ext.data.Response({action:i,raw:g});switch(g.status){case 200:return true;break;case 201:if(Ext.isEmpty(h.raw.responseText)){h.success=true}else{return true}break;case 204:h.success=true;h.data=null;break;default:return true;break}if(h.success===true){this.fireEvent("write",this,i,h.data,h,e,k.request.arg)}else{this.fireEvent("exception",this,"remote",i,k,h,e)}k.request.callback.call(k.request.scope,h.data,h,h.success);return false},b)}}})();Ext.data.Response=function(b,a){Ext.apply(this,b,{raw:a})};Ext.data.Response.prototype={message:null,success:false,status:null,root:null,raw:null,getMessage:function(){return this.message},getSuccess:function(){return this.success},getStatus:function(){return this.status},getRoot:function(){return this.root},getRawResponse:function(){return this.raw}};Ext.data.Api.Error=Ext.extend(Ext.Error,{constructor:function(b,a){this.arg=a;Ext.Error.call(this,b)},name:"Ext.data.Api"});Ext.apply(Ext.data.Api.Error.prototype,{lang:{"action-url-undefined":"No fallback url defined for this action. When defining a DataProxy api, please be sure to define an url for each CRUD action in Ext.data.Api.actions or define a default url in addition to your api-configuration.",invalid:"received an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions","invalid-url":"Invalid url. Please review your proxy configuration.",execute:'Attempted to execute an unknown action. Valid API actions are defined in Ext.data.Api.actions"'}});Ext.data.SortTypes={none:function(a){return a},stripTagsRE:/<\/?[^>]+>/gi,asText:function(a){return String(a).replace(this.stripTagsRE,"")},asUCText:function(a){return String(a).toUpperCase().replace(this.stripTagsRE,"")},asUCString:function(a){return String(a).toUpperCase()},asDate:function(a){if(!a){return 0}if(Ext.isDate(a)){return a.getTime()}return Date.parse(String(a))},asFloat:function(a){var b=parseFloat(String(a).replace(/,/g,""));return isNaN(b)?0:b},asInt:function(a){var b=parseInt(String(a).replace(/,/g,""),10);return isNaN(b)?0:b}};Ext.data.Record=function(a,b){this.id=(b||b===0)?b:Ext.data.Record.id(this);this.data=a||{}};Ext.data.Record.create=function(e){var c=Ext.extend(Ext.data.Record,{});var d=c.prototype;d.fields=new Ext.util.MixedCollection(false,function(g){return g.name});for(var b=0,a=e.length;b<a;b++){d.fields.add(new Ext.data.Field(e[b]))}c.getField=function(g){return d.fields.get(g)};return c};Ext.data.Record.PREFIX="ext-record";Ext.data.Record.AUTO_ID=1;Ext.data.Record.EDIT="edit";Ext.data.Record.REJECT="reject";Ext.data.Record.COMMIT="commit";Ext.data.Record.id=function(a){a.phantom=true;return[Ext.data.Record.PREFIX,"-",Ext.data.Record.AUTO_ID++].join("")};Ext.data.Record.prototype={dirty:false,editing:false,error:null,modified:null,phantom:false,join:function(a){this.store=a},set:function(a,c){var b=Ext.isPrimitive(c)?String:Ext.encode;if(b(this.data[a])==b(c)){return}this.dirty=true;if(!this.modified){this.modified={}}if(this.modified[a]===undefined){this.modified[a]=this.data[a]}this.data[a]=c;if(!this.editing){this.afterEdit()}},afterEdit:function(){if(this.store!=undefined&&typeof this.store.afterEdit=="function"){this.store.afterEdit(this)}},afterReject:function(){if(this.store){this.store.afterReject(this)}},afterCommit:function(){if(this.store){this.store.afterCommit(this)}},get:function(a){return this.data[a]},beginEdit:function(){this.editing=true;this.modified=this.modified||{}},cancelEdit:function(){this.editing=false;delete this.modified},endEdit:function(){this.editing=false;if(this.dirty){this.afterEdit()}},reject:function(b){var a=this.modified;for(var c in a){if(typeof a[c]!="function"){this.data[c]=a[c]}}this.dirty=false;delete this.modified;this.editing=false;if(b!==true){this.afterReject()}},commit:function(a){this.dirty=false;delete this.modified;this.editing=false;if(a!==true){this.afterCommit()}},getChanges:function(){var a=this.modified,b={};for(var c in a){if(a.hasOwnProperty(c)){b[c]=this.data[c]}}return b},hasError:function(){return this.error!==null},clearError:function(){this.error=null},copy:function(a){return new this.constructor(Ext.apply({},this.data),a||this.id)},isModified:function(a){return !!(this.modified&&this.modified.hasOwnProperty(a))},isValid:function(){return this.fields.find(function(a){return(a.allowBlank===false&&Ext.isEmpty(this.data[a.name]))?true:false},this)?false:true},markDirty:function(){this.dirty=true;if(!this.modified){this.modified={}}this.fields.each(function(a){this.modified[a.name]=this.data[a.name]},this)}};Ext.StoreMgr=Ext.apply(new Ext.util.MixedCollection(),{register:function(){for(var a=0,b;(b=arguments[a]);a++){this.add(b)}},unregister:function(){for(var a=0,b;(b=arguments[a]);a++){this.remove(this.lookup(b))}},lookup:function(e){if(Ext.isArray(e)){var b=["field1"],d=!Ext.isArray(e[0]);if(!d){for(var c=2,a=e[0].length;c<=a;++c){b.push("field"+c)}}return new Ext.data.ArrayStore({fields:b,data:e,expandData:d,autoDestroy:true,autoCreated:true})}return Ext.isObject(e)?(e.events?e:Ext.create(e,"store")):this.get(e)},getKey:function(a){return a.storeId}});Ext.data.Store=Ext.extend(Ext.util.Observable,{writer:undefined,remoteSort:false,autoDestroy:false,pruneModifiedRecords:false,lastOptions:null,autoSave:true,batch:true,restful:false,paramNames:undefined,defaultParamNames:{start:"start",limit:"limit",sort:"sort",dir:"dir"},isDestroyed:false,hasMultiSort:false,batchKey:"_ext_batch_",constructor:function(a){this.data=new Ext.util.MixedCollection(false);this.data.getKey=function(b){return b.id};this.removed=[];if(a&&a.data){this.inlineData=a.data;delete a.data}Ext.apply(this,a);this.baseParams=Ext.isObject(this.baseParams)?this.baseParams:{};this.paramNames=Ext.applyIf(this.paramNames||{},this.defaultParamNames);if((this.url||this.api)&&!this.proxy){this.proxy=new Ext.data.HttpProxy({url:this.url,api:this.api})}if(this.restful===true&&this.proxy){this.batch=false;Ext.data.Api.restify(this.proxy)}if(this.reader){if(!this.recordType){this.recordType=this.reader.recordType}if(this.reader.onMetaChange){this.reader.onMetaChange=this.reader.onMetaChange.createSequence(this.onMetaChange,this)}if(this.writer){if(this.writer instanceof (Ext.data.DataWriter)===false){this.writer=this.buildWriter(this.writer)}this.writer.meta=this.reader.meta;this.pruneModifiedRecords=true}}if(this.recordType){this.fields=this.recordType.prototype.fields}this.modified=[];this.addEvents("datachanged","metachange","add","remove","update","clear","exception","beforeload","load","loadexception","beforewrite","write","beforesave","save");if(this.proxy){this.relayEvents(this.proxy,["loadexception","exception"])}if(this.writer){this.on({scope:this,add:this.createRecords,remove:this.destroyRecord,update:this.updateRecord,clear:this.onClear})}this.sortToggle={};if(this.sortField){this.setDefaultSort(this.sortField,this.sortDir)}else{if(this.sortInfo){this.setDefaultSort(this.sortInfo.field,this.sortInfo.direction)}}Ext.data.Store.superclass.constructor.call(this);if(this.id){this.storeId=this.id;delete this.id}if(this.storeId){Ext.StoreMgr.register(this)}if(this.inlineData){this.loadData(this.inlineData);delete this.inlineData}else{if(this.autoLoad){this.load.defer(10,this,[typeof this.autoLoad=="object"?this.autoLoad:undefined])}}this.batchCounter=0;this.batches={}},buildWriter:function(b){var a=undefined,c=(b.format||"json").toLowerCase();switch(c){case"json":a=Ext.data.JsonWriter;break;case"xml":a=Ext.data.XmlWriter;break;default:a=Ext.data.JsonWriter}return new a(b)},destroy:function(){if(!this.isDestroyed){if(this.storeId){Ext.StoreMgr.unregister(this)}this.clearData();this.data=null;Ext.destroy(this.proxy);this.reader=this.writer=null;this.purgeListeners();this.isDestroyed=true}},add:function(c){var e,a,b,d;c=[].concat(c);if(c.length<1){return}for(e=0,a=c.length;e<a;e++){b=c[e];b.join(this);if(b.dirty||b.phantom){this.modified.push(b)}}d=this.data.length;this.data.addAll(c);if(this.snapshot){this.snapshot.addAll(c)}this.fireEvent("add",this,c,d)},addSorted:function(a){var b=this.findInsertIndex(a);this.insert(b,a)},doUpdate:function(a){this.data.replace(a.id,a);if(this.snapshot){this.snapshot.replace(a.id,a)}this.fireEvent("update",this,a,Ext.data.Record.COMMIT)},remove:function(a){if(Ext.isArray(a)){Ext.each(a,function(c){this.remove(c)},this);return}var b=this.data.indexOf(a);if(b>-1){a.join(null);this.data.removeAt(b)}if(this.pruneModifiedRecords){this.modified.remove(a)}if(this.snapshot){this.snapshot.remove(a)}if(b>-1){this.fireEvent("remove",this,a,b)}},removeAt:function(a){this.remove(this.getAt(a))},removeAll:function(b){var a=[];this.each(function(c){a.push(c)});this.clearData();if(this.snapshot){this.snapshot.clear()}if(this.pruneModifiedRecords){this.modified=[]}if(b!==true){this.fireEvent("clear",this,a)}},onClear:function(b,a){Ext.each(a,function(d,c){this.destroyRecord(this,d,c)},this)},insert:function(d,c){var e,a,b;c=[].concat(c);for(e=0,a=c.length;e<a;e++){b=c[e];this.data.insert(d+e,b);b.join(this);if(b.dirty||b.phantom){this.modified.push(b)}}if(this.snapshot){this.snapshot.addAll(c)}this.fireEvent("add",this,c,d)},indexOf:function(a){return this.data.indexOf(a)},indexOfId:function(a){return this.data.indexOfKey(a)},getById:function(a){return(this.snapshot||this.data).key(a)},getAt:function(a){return this.data.itemAt(a)},getRange:function(b,a){return this.data.getRange(b,a)},storeOptions:function(a){a=Ext.apply({},a);delete a.callback;delete a.scope;this.lastOptions=a},clearData:function(){this.data.each(function(a){a.join(null)});this.data.clear()},load:function(b){b=Ext.apply({},b);this.storeOptions(b);if(this.sortInfo&&this.remoteSort){var a=this.paramNames;b.params=Ext.apply({},b.params);b.params[a.sort]=this.sortInfo.field;b.params[a.dir]=this.sortInfo.direction}try{return this.execute("read",null,b)}catch(c){this.handleException(c);return false}},updateRecord:function(b,a,c){if(c==Ext.data.Record.EDIT&&this.autoSave===true&&(!a.phantom||(a.phantom&&a.isValid()))){this.save()}},createRecords:function(c,b,e){var d=this.modified,h=b.length,a,g;for(g=0;g<h;g++){a=b[g];if(a.phantom&&a.isValid()){a.markDirty();if(d.indexOf(a)==-1){d.push(a)}}}if(this.autoSave===true){this.save()}},destroyRecord:function(b,a,c){if(this.modified.indexOf(a)!=-1){this.modified.remove(a)}if(!a.phantom){this.removed.push(a);a.lastIndex=c;if(this.autoSave===true){this.save()}}},execute:function(e,a,c,b){if(!Ext.data.Api.isAction(e)){throw new Ext.data.Api.Error("execute",e)}c=Ext.applyIf(c||{},{params:{}});if(b!==undefined){this.addToBatch(b)}var d=true;if(e==="read"){d=this.fireEvent("beforeload",this,c);Ext.applyIf(c.params,this.baseParams)}else{if(this.writer.listful===true&&this.restful!==true){a=(Ext.isArray(a))?a:[a]}else{if(Ext.isArray(a)&&a.length==1){a=a.shift()}}if((d=this.fireEvent("beforewrite",this,e,a,c))!==false){this.writer.apply(c.params,this.baseParams,e,a)}}if(d!==false){if(this.writer&&this.proxy.url&&!this.proxy.restful&&!Ext.data.Api.hasUniqueUrl(this.proxy,e)){c.params.xaction=e}this.proxy.request(Ext.data.Api.actions[e],a,c.params,this.reader,this.createCallback(e,a,b),this,c)}return d},save:function(){if(!this.writer){throw new Ext.data.Store.Error("writer-undefined")}var h=[],k,l,e,c={},d;if(this.removed.length){h.push(["destroy",this.removed])}var b=[].concat(this.getModifiedRecords());if(b.length){var g=[];for(d=b.length-1;d>=0;d--){if(b[d].phantom===true){var a=b.splice(d,1).shift();if(a.isValid()){g.push(a)}}else{if(!b[d].isValid()){b.splice(d,1)}}}if(g.length){h.push(["create",g])}if(b.length){h.push(["update",b])}}k=h.length;if(k){e=++this.batchCounter;for(d=0;d<k;++d){l=h[d];c[l[0]]=l[1]}if(this.fireEvent("beforesave",this,c)!==false){for(d=0;d<k;++d){l=h[d];this.doTransaction(l[0],l[1],e)}return e}}return -1},doTransaction:function(e,b,c){function g(h){try{this.execute(e,h,undefined,c)}catch(i){this.handleException(i)}}if(this.batch===false){for(var d=0,a=b.length;d<a;d++){g.call(this,b[d])}}else{g.call(this,b)}},addToBatch:function(c){var a=this.batches,d=this.batchKey+c,e=a[d];if(!e){a[d]=e={id:c,count:0,data:{}}}++e.count},removeFromBatch:function(d,h,g){var c=this.batches,e=this.batchKey+d,i=c[e],a;if(i){a=i.data[h]||[];i.data[h]=a.concat(g);if(i.count===1){g=i.data;delete c[e];this.fireEvent("save",this,d,g)}else{--i.count}}},createCallback:function(c,a,b){var d=Ext.data.Api.actions;return(c=="read")?this.loadRecords:function(g,e,h){this["on"+Ext.util.Format.capitalize(c)+"Records"](h,a,[].concat(g));if(h===true){this.fireEvent("write",this,c,g,e,a)}this.removeFromBatch(b,c,g)}},clearModified:function(a){if(Ext.isArray(a)){for(var b=a.length-1;b>=0;b--){this.modified.splice(this.modified.indexOf(a[b]),1)}}else{this.modified.splice(this.modified.indexOf(a),1)}},reMap:function(b){if(Ext.isArray(b)){for(var d=0,a=b.length;d<a;d++){this.reMap(b[d])}}else{delete this.data.map[b._phid];this.data.map[b.id]=b;var c=this.data.keys.indexOf(b._phid);this.data.keys.splice(c,1,b.id);delete b._phid}},onCreateRecords:function(d,a,b){if(d===true){try{this.reader.realize(a,b);this.reMap(a)}catch(c){this.handleException(c);if(Ext.isArray(a)){this.onCreateRecords(d,a,b)}}}},onUpdateRecords:function(d,a,b){if(d===true){try{this.reader.update(a,b)}catch(c){this.handleException(c);if(Ext.isArray(a)){this.onUpdateRecords(d,a,b)}}}},onDestroyRecords:function(e,b,d){b=(b instanceof Ext.data.Record)?[b]:[].concat(b);for(var c=0,a=b.length;c<a;c++){this.removed.splice(this.removed.indexOf(b[c]),1)}if(e===false){for(c=b.length-1;c>=0;c--){this.insert(b[c].lastIndex,b[c])}}},handleException:function(a){Ext.handleError(a)},reload:function(a){this.load(Ext.applyIf(a||{},this.lastOptions))},loadRecords:function(b,m,h){var e,g;if(this.isDestroyed===true){return}if(!b||h===false){if(h!==false){this.fireEvent("load",this,[],m)}if(m.callback){m.callback.call(m.scope||this,[],m,false,b)}return}var a=b.records,k=b.totalRecords||a.length;if(!m||m.add!==true){if(this.pruneModifiedRecords){this.modified=[]}for(e=0,g=a.length;e<g;e++){a[e].join(this)}if(this.snapshot){this.data=this.snapshot;delete this.snapshot}this.clearData();this.data.addAll(a);this.totalLength=k;this.applySort();this.fireEvent("datachanged",this)}else{var l=[],d,c=0;for(e=0,g=a.length;e<g;++e){d=a[e];if(this.indexOfId(d.id)>-1){this.doUpdate(d)}else{l.push(d);++c}}this.totalLength=Math.max(k,this.data.length+c);this.add(l)}this.fireEvent("load",this,a,m);if(m.callback){m.callback.call(m.scope||this,a,m,true)}},loadData:function(c,a){var b=this.reader.readRecords(c);this.loadRecords(b,{add:a},true)},getCount:function(){return this.data.length||0},getTotalCount:function(){return this.totalLength||0},getSortState:function(){return this.sortInfo},applySort:function(){if((this.sortInfo||this.multiSortInfo)&&!this.remoteSort){this.sortData()}},sortData:function(){var a=this.hasMultiSort?this.multiSortInfo:this.sortInfo,k=a.direction||"ASC",h=a.sorters,c=[];if(!this.hasMultiSort){h=[{direction:k,field:a.field}]}for(var d=0,b=h.length;d<b;d++){c.push(this.createSortFunction(h[d].field,h[d].direction))}if(c.length==0){return}var g=k.toUpperCase()=="DESC"?-1:1;var e=function(n,m){var l=c[0].call(this,n,m);if(c.length>1){for(var p=1,o=c.length;p<o;p++){l=l||c[p].call(this,n,m)}}return g*l};this.data.sort(k,e);if(this.snapshot&&this.snapshot!=this.data){this.snapshot.sort(k,e)}},createSortFunction:function(c,b){b=b||"ASC";var a=b.toUpperCase()=="DESC"?-1:1;var d=this.fields.get(c).sortType;return function(g,e){var i=d(g.data[c]),h=d(e.data[c]);return a*(i>h?1:(i<h?-1:0))}},setDefaultSort:function(b,a){a=a?a.toUpperCase():"ASC";this.sortInfo={field:b,direction:a};this.sortToggle[b]=a},sort:function(b,a){if(Ext.isArray(arguments[0])){return this.multiSort.call(this,b,a)}else{return this.singleSort(b,a)}},singleSort:function(g,c){var e=this.fields.get(g);if(!e){return false}var b=e.name,a=this.sortInfo||null,d=this.sortToggle?this.sortToggle[b]:null;if(!c){if(a&&a.field==b){c=(this.sortToggle[b]||"ASC").toggle("ASC","DESC")}else{c=e.sortDir}}this.sortToggle[b]=c;this.sortInfo={field:b,direction:c};this.hasMultiSort=false;if(this.remoteSort){if(!this.load(this.lastOptions)){if(d){this.sortToggle[b]=d}if(a){this.sortInfo=a}}}else{this.applySort();this.fireEvent("datachanged",this)}return true},multiSort:function(b,a){this.hasMultiSort=true;a=a||"ASC";if(this.multiSortInfo&&a==this.multiSortInfo.direction){a=a.toggle("ASC","DESC")}this.multiSortInfo={sorters:b,direction:a};if(this.remoteSort){this.singleSort(b[0].field,b[0].direction)}else{this.applySort();this.fireEvent("datachanged",this)}},each:function(b,a){this.data.each(b,a)},getModifiedRecords:function(){return this.modified},sum:function(e,g,a){var c=this.data.items,b=0;g=g||0;a=(a||a===0)?a:c.length-1;for(var d=g;d<=a;d++){b+=(c[d].data[e]||0)}return b},createFilterFn:function(d,c,e,a,b){if(Ext.isEmpty(c,false)){return false}c=this.data.createValueMatcher(c,e,a,b);return function(g){return c.test(g.data[d])}},createMultipleFilterFn:function(a){return function(b){var k=true;for(var d=0,c=a.length;d<c;d++){var h=a[d],g=h.fn,e=h.scope;k=k&&g.call(e,b)}return k}},filter:function(n,m,h,k,e){var l;if(Ext.isObject(n)){n=[n]}if(Ext.isArray(n)){var b=[];for(var g=0,d=n.length;g<d;g++){var a=n[g],c=a.fn,o=a.scope||this;if(!Ext.isFunction(c)){c=this.createFilterFn(a.property,a.value,a.anyMatch,a.caseSensitive,a.exactMatch)}b.push({fn:c,scope:o})}l=this.createMultipleFilterFn(b)}else{l=this.createFilterFn(n,m,h,k,e)}return l?this.filterBy(l):this.clearFilter()},filterBy:function(b,a){this.snapshot=this.snapshot||this.data;this.data=this.queryBy(b,a||this);this.fireEvent("datachanged",this)},clearFilter:function(a){if(this.isFiltered()){this.data=this.snapshot;delete this.snapshot;if(a!==true){this.fireEvent("datachanged",this)}}},isFiltered:function(){return !!this.snapshot&&this.snapshot!=this.data},query:function(d,c,e,a){var b=this.createFilterFn(d,c,e,a);return b?this.queryBy(b):this.data.clone()},queryBy:function(b,a){var c=this.snapshot||this.data;return c.filterBy(b,a||this)},find:function(d,c,g,e,a){var b=this.createFilterFn(d,c,e,a);return b?this.data.findIndexBy(b,null,g):-1},findExact:function(b,a,c){return this.data.findIndexBy(function(d){return d.get(b)===a},this,c)},findBy:function(b,a,c){return this.data.findIndexBy(b,a,c)},collect:function(k,m,b){var h=(b===true&&this.snapshot)?this.snapshot.items:this.data.items;var n,o,a=[],c={};for(var e=0,g=h.length;e<g;e++){n=h[e].data[k];o=String(n);if((m||!Ext.isEmpty(n))&&!c[o]){c[o]=true;a[a.length]=n}}return a},afterEdit:function(a){if(this.modified.indexOf(a)==-1){this.modified.push(a)}this.fireEvent("update",this,a,Ext.data.Record.EDIT)},afterReject:function(a){this.modified.remove(a);this.fireEvent("update",this,a,Ext.data.Record.REJECT)},afterCommit:function(a){this.modified.remove(a);this.fireEvent("update",this,a,Ext.data.Record.COMMIT)},commitChanges:function(){var a=this.modified.slice(0),c=a.length,b;for(b=0;b<c;b++){a[b].commit()}this.modified=[];this.removed=[]},rejectChanges:function(){var a=this.modified.slice(0),e=this.removed.slice(0).reverse(),c=a.length,d=e.length,b;for(b=0;b<c;b++){a[b].reject()}for(b=0;b<d;b++){this.insert(e[b].lastIndex||0,e[b]);e[b].reject()}this.modified=[];this.removed=[]},onMetaChange:function(a){this.recordType=this.reader.recordType;this.fields=this.recordType.prototype.fields;delete this.snapshot;if(this.reader.meta.sortInfo){this.sortInfo=this.reader.meta.sortInfo}else{if(this.sortInfo&&!this.fields.get(this.sortInfo.field)){delete this.sortInfo}}if(this.writer){this.writer.meta=this.reader.meta}this.modified=[];this.fireEvent("metachange",this,this.reader.meta)},findInsertIndex:function(a){this.suspendEvents();var c=this.data.clone();this.data.add(a);this.applySort();var b=this.data.indexOf(a);this.data=c;this.resumeEvents();return b},setBaseParam:function(a,b){this.baseParams=this.baseParams||{};this.baseParams[a]=b}});Ext.reg("store",Ext.data.Store);Ext.data.Store.Error=Ext.extend(Ext.Error,{name:"Ext.data.Store"});Ext.apply(Ext.data.Store.Error.prototype,{lang:{"writer-undefined":"Attempted to execute a write-action without a DataWriter installed."}});Ext.data.Field=Ext.extend(Object,{constructor:function(b){if(Ext.isString(b)){b={name:b}}Ext.apply(this,b);var d=Ext.data.Types,a=this.sortType,c;if(this.type){if(Ext.isString(this.type)){this.type=Ext.data.Types[this.type.toUpperCase()]||d.AUTO}}else{this.type=d.AUTO}if(Ext.isString(a)){this.sortType=Ext.data.SortTypes[a]}else{if(Ext.isEmpty(a)){this.sortType=this.type.sortType}}if(!this.convert){this.convert=this.type.convert}},dateFormat:null,useNull:false,defaultValue:"",mapping:null,sortType:null,sortDir:"ASC",allowBlank:true});Ext.data.DataReader=function(a,b){this.meta=a;this.recordType=Ext.isArray(b)?Ext.data.Record.create(b):b;if(this.recordType){this.buildExtractors()}};Ext.data.DataReader.prototype={getTotal:Ext.emptyFn,getRoot:Ext.emptyFn,getMessage:Ext.emptyFn,getSuccess:Ext.emptyFn,getId:Ext.emptyFn,buildExtractors:Ext.emptyFn,extractValues:Ext.emptyFn,realize:function(a,c){if(Ext.isArray(a)){for(var b=a.length-1;b>=0;b--){if(Ext.isArray(c)){this.realize(a.splice(b,1).shift(),c.splice(b,1).shift())}else{this.realize(a.splice(b,1).shift(),c)}}}else{if(Ext.isArray(c)&&c.length==1){c=c.shift()}if(!this.isData(c)){throw new Ext.data.DataReader.Error("realize",a)}a.phantom=false;a._phid=a.id;a.id=this.getId(c);a.data=c;a.commit()}},update:function(a,c){if(Ext.isArray(a)){for(var b=a.length-1;b>=0;b--){if(Ext.isArray(c)){this.update(a.splice(b,1).shift(),c.splice(b,1).shift())}else{this.update(a.splice(b,1).shift(),c)}}}else{if(Ext.isArray(c)&&c.length==1){c=c.shift()}if(this.isData(c)){a.data=Ext.apply(a.data,c)}a.commit()}},extractData:function(l,a){var k=(this instanceof Ext.data.JsonReader)?"json":"node";var c=[];if(this.isData(l)&&!(this instanceof Ext.data.XmlReader)){l=[l]}var h=this.recordType.prototype.fields,p=h.items,o=h.length,c=[];if(a===true){var m=this.recordType;for(var e=0;e<l.length;e++){var b=l[e];var g=new m(this.extractValues(b,p,o),this.getId(b));g[k]=b;c.push(g)}}else{for(var e=0;e<l.length;e++){var d=this.extractValues(l[e],p,o);d[this.meta.idProperty]=this.getId(l[e]);c.push(d)}}return c},isData:function(a){return(a&&Ext.isObject(a)&&!Ext.isEmpty(this.getId(a)))?true:false},onMetaChange:function(a){delete this.ef;this.meta=a;this.recordType=Ext.data.Record.create(a.fields);this.buildExtractors()}};Ext.data.DataReader.Error=Ext.extend(Ext.Error,{constructor:function(b,a){this.arg=a;Ext.Error.call(this,b)},name:"Ext.data.DataReader"});Ext.apply(Ext.data.DataReader.Error.prototype,{lang:{update:"#update received invalid data from server. Please see docs for DataReader#update and review your DataReader configuration.",realize:"#realize was called with invalid remote-data. Please see the docs for DataReader#realize and review your DataReader configuration.","invalid-response":"#readResponse received an invalid response from the server."}});Ext.data.DataWriter=function(a){Ext.apply(this,a)};Ext.data.DataWriter.prototype={writeAllFields:false,listful:false,apply:function(e,g,d,a){var c=[],b=d+"Record";if(Ext.isArray(a)){Ext.each(a,function(h){c.push(this[b](h))},this)}else{if(a instanceof Ext.data.Record){c=this[b](a)}}this.render(e,g,c)},render:Ext.emptyFn,updateRecord:Ext.emptyFn,createRecord:Ext.emptyFn,destroyRecord:Ext.emptyFn,toHash:function(g,c){var e=g.fields.map,d={},b=(this.writeAllFields===false&&g.phantom===false)?g.getChanges():g.data,a;Ext.iterate(b,function(i,h){if((a=e[i])){d[a.mapping?a.mapping:a.name]=h}});if(g.phantom){if(g.fields.containsKey(this.meta.idProperty)&&Ext.isEmpty(g.data[this.meta.idProperty])){delete d[this.meta.idProperty]}}else{d[this.meta.idProperty]=g.id}return d},toArray:function(b){var a=[];Ext.iterate(b,function(d,c){a.push({name:d,value:c})},this);return a}};Ext.data.DataProxy=function(a){a=a||{};this.api=a.api;this.url=a.url;this.restful=a.restful;this.listeners=a.listeners;this.prettyUrls=a.prettyUrls;this.addEvents("exception","beforeload","load","loadexception","beforewrite","write");Ext.data.DataProxy.superclass.constructor.call(this);try{Ext.data.Api.prepare(this)}catch(b){if(b instanceof Ext.data.Api.Error){b.toConsole()}}Ext.data.DataProxy.relayEvents(this,["beforewrite","write","exception"])};Ext.extend(Ext.data.DataProxy,Ext.util.Observable,{restful:false,setApi:function(){if(arguments.length==1){var a=Ext.data.Api.isValid(arguments[0]);if(a===true){this.api=arguments[0]}else{throw new Ext.data.Api.Error("invalid",a)}}else{if(arguments.length==2){if(!Ext.data.Api.isAction(arguments[0])){throw new Ext.data.Api.Error("invalid",arguments[0])}this.api[arguments[0]]=arguments[1]}}Ext.data.Api.prepare(this)},isApiAction:function(a){return(this.api[a])?true:false},request:function(e,b,g,a,h,d,c){if(!this.api[e]&&!this.load){throw new Ext.data.DataProxy.Error("action-undefined",e)}g=g||{};if((e===Ext.data.Api.actions.read)?this.fireEvent("beforeload",this,g):this.fireEvent("beforewrite",this,e,b,g)!==false){this.doRequest.apply(this,arguments)}else{h.call(d||this,null,c,false)}},load:null,doRequest:function(e,b,g,a,h,d,c){this.load(g,a,h,d,c)},onRead:Ext.emptyFn,onWrite:Ext.emptyFn,buildUrl:function(d,b){b=b||null;var c=(this.conn&&this.conn.url)?this.conn.url:(this.api[d])?this.api[d].url:this.url;if(!c){throw new Ext.data.Api.Error("invalid-url",d)}var e=null;var a=c.match(/(.*)(\.json|\.xml|\.html)$/);if(a){e=a[2];c=a[1]}if((this.restful===true||this.prettyUrls===true)&&b instanceof Ext.data.Record&&!b.phantom){c+="/"+b.id}return(e===null)?c:c+e},destroy:function(){this.purgeListeners()}});Ext.apply(Ext.data.DataProxy,Ext.util.Observable.prototype);Ext.util.Observable.call(Ext.data.DataProxy);Ext.data.DataProxy.Error=Ext.extend(Ext.Error,{constructor:function(b,a){this.arg=a;Ext.Error.call(this,b)},name:"Ext.data.DataProxy"});Ext.apply(Ext.data.DataProxy.Error.prototype,{lang:{"action-undefined":"DataProxy attempted to execute an API-action but found an undefined url / function. Please review your Proxy url/api-configuration.","api-invalid":"Recieved an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions."}});Ext.data.Request=function(a){Ext.apply(this,a)};Ext.data.Request.prototype={action:undefined,rs:undefined,params:undefined,callback:Ext.emptyFn,scope:undefined,reader:undefined};Ext.data.Response=function(a){Ext.apply(this,a)};Ext.data.Response.prototype={action:undefined,success:undefined,message:undefined,data:undefined,raw:undefined,records:undefined};Ext.data.ScriptTagProxy=function(a){Ext.apply(this,a);Ext.data.ScriptTagProxy.superclass.constructor.call(this,a);this.head=document.getElementsByTagName("head")[0]};Ext.data.ScriptTagProxy.TRANS_ID=1000;Ext.extend(Ext.data.ScriptTagProxy,Ext.data.DataProxy,{timeout:30000,callbackParam:"callback",nocache:true,doRequest:function(e,g,d,h,k,l,m){var c=Ext.urlEncode(Ext.apply(d,this.extraParams));var b=this.buildUrl(e,g);if(!b){throw new Ext.data.Api.Error("invalid-url",b)}b=Ext.urlAppend(b,c);if(this.nocache){b=Ext.urlAppend(b,"_dc="+(new Date().getTime()))}var a=++Ext.data.ScriptTagProxy.TRANS_ID;var n={id:a,action:e,cb:"stcCallback"+a,scriptId:"stcScript"+a,params:d,arg:m,url:b,callback:k,scope:l,reader:h};window[n.cb]=this.createCallback(e,g,n);b+=String.format("&{0}={1}",this.callbackParam,n.cb);if(this.autoAbort!==false){this.abort()}n.timeoutId=this.handleFailure.defer(this.timeout,this,[n]);var i=document.createElement("script");i.setAttribute("src",b);i.setAttribute("type","text/javascript");i.setAttribute("id",n.scriptId);this.head.appendChild(i);this.trans=n},createCallback:function(d,b,c){var a=this;return function(e){a.trans=false;a.destroyTrans(c,true);if(d===Ext.data.Api.actions.read){a.onRead.call(a,d,c,e)}else{a.onWrite.call(a,d,c,e,b)}}},onRead:function(d,c,b){var a;try{a=c.reader.readRecords(b)}catch(g){this.fireEvent("loadexception",this,c,b,g);this.fireEvent("exception",this,"response",d,c,b,g);c.callback.call(c.scope||window,null,c.arg,false);return}if(a.success===false){this.fireEvent("loadexception",this,c,b);this.fireEvent("exception",this,"remote",d,c,b,null)}else{this.fireEvent("load",this,b,c.arg)}c.callback.call(c.scope||window,a,c.arg,a.success)},onWrite:function(h,g,c,b){var a=g.reader;try{var d=a.readResponse(h,c)}catch(i){this.fireEvent("exception",this,"response",h,g,d,i);g.callback.call(g.scope||window,null,d,false);return}if(!d.success===true){this.fireEvent("exception",this,"remote",h,g,d,b);g.callback.call(g.scope||window,null,d,false);return}this.fireEvent("write",this,h,d.data,d,b,g.arg);g.callback.call(g.scope||window,d.data,d,true)},isLoading:function(){return this.trans?true:false},abort:function(){if(this.isLoading()){this.destroyTrans(this.trans)}},destroyTrans:function(b,a){this.head.removeChild(document.getElementById(b.scriptId));clearTimeout(b.timeoutId);if(a){window[b.cb]=undefined;try{delete window[b.cb]}catch(c){}}else{window[b.cb]=function(){window[b.cb]=undefined;try{delete window[b.cb]}catch(d){}}}},handleFailure:function(a){this.trans=false;this.destroyTrans(a,false);if(a.action===Ext.data.Api.actions.read){this.fireEvent("loadexception",this,null,a.arg)}this.fireEvent("exception",this,"response",a.action,{response:null,options:a.arg});a.callback.call(a.scope||window,null,a.arg,false)},destroy:function(){this.abort();Ext.data.ScriptTagProxy.superclass.destroy.call(this)}});Ext.data.HttpProxy=function(a){Ext.data.HttpProxy.superclass.constructor.call(this,a);this.conn=a;this.conn.url=null;this.useAjax=!a||!a.events;var c=Ext.data.Api.actions;this.activeRequest={};for(var b in c){this.activeRequest[c[b]]=undefined}};Ext.extend(Ext.data.HttpProxy,Ext.data.DataProxy,{getConnection:function(){return this.useAjax?Ext.Ajax:this.conn},setUrl:function(a,b){this.conn.url=a;if(b===true){this.url=a;this.api=null;Ext.data.Api.prepare(this)}},doRequest:function(g,d,i,c,b,e,a){var h={method:(this.api[g])?this.api[g]["method"]:undefined,request:{callback:b,scope:e,arg:a},reader:c,callback:this.createCallback(g,d),scope:this};if(i.jsonData){h.jsonData=i.jsonData}else{if(i.xmlData){h.xmlData=i.xmlData}else{h.params=i||{}}}this.conn.url=this.buildUrl(g,d);if(this.useAjax){Ext.applyIf(h,this.conn);if(this.activeRequest[g]){}this.activeRequest[g]=Ext.Ajax.request(h)}else{this.conn.request(h)}this.conn.url=null},createCallback:function(b,a){return function(e,d,c){this.activeRequest[b]=undefined;if(!d){if(b===Ext.data.Api.actions.read){this.fireEvent("loadexception",this,e,c)}this.fireEvent("exception",this,"response",b,e,c);e.request.callback.call(e.request.scope,null,e.request.arg,false);return}if(b===Ext.data.Api.actions.read){this.onRead(b,e,c)}else{this.onWrite(b,e,c,a)}}},onRead:function(d,h,b){var a;try{a=h.reader.read(b)}catch(g){this.fireEvent("loadexception",this,h,b,g);this.fireEvent("exception",this,"response",d,h,b,g);h.request.callback.call(h.request.scope,null,h.request.arg,false);return}if(a.success===false){this.fireEvent("loadexception",this,h,b);var c=h.reader.readResponse(d,b);this.fireEvent("exception",this,"remote",d,h,c,null)}else{this.fireEvent("load",this,h,h.request.arg)}h.request.callback.call(h.request.scope,a,h.request.arg,a.success)},onWrite:function(g,i,c,b){var a=i.reader;var d;try{d=a.readResponse(g,c)}catch(h){this.fireEvent("exception",this,"response",g,i,c,h);i.request.callback.call(i.request.scope,null,i.request.arg,false);return}if(d.success===true){this.fireEvent("write",this,g,d.data,d,b,i.request.arg)}else{this.fireEvent("exception",this,"remote",g,i,d,b)}i.request.callback.call(i.request.scope,d.data,d,d.success)},destroy:function(){if(!this.useAjax){this.conn.abort()}else{if(this.activeRequest){var b=Ext.data.Api.actions;for(var a in b){if(this.activeRequest[b[a]]){Ext.Ajax.abort(this.activeRequest[b[a]])}}}}Ext.data.HttpProxy.superclass.destroy.call(this)}});Ext.data.MemoryProxy=function(b){var a={};a[Ext.data.Api.actions.read]=true;Ext.data.MemoryProxy.superclass.constructor.call(this,{api:a});this.data=b};Ext.extend(Ext.data.MemoryProxy,Ext.data.DataProxy,{doRequest:function(b,c,a,d,h,i,k){a=a||{};var l;try{l=d.readRecords(this.data)}catch(g){this.fireEvent("loadexception",this,null,k,g);this.fireEvent("exception",this,"response",b,k,null,g);h.call(i,null,k,false);return}h.call(i,l,k,true)}});Ext.data.Types=new function(){var a=Ext.data.SortTypes;Ext.apply(this,{stripRe:/[\$,%]/g,AUTO:{convert:function(b){return b},sortType:a.none,type:"auto"},STRING:{convert:function(b){return(b===undefined||b===null)?"":String(b)},sortType:a.asUCString,type:"string"},INT:{convert:function(b){return b!==undefined&&b!==null&&b!==""?parseInt(String(b).replace(Ext.data.Types.stripRe,""),10):(this.useNull?null:0)},sortType:a.none,type:"int"},FLOAT:{convert:function(b){return b!==undefined&&b!==null&&b!==""?parseFloat(String(b).replace(Ext.data.Types.stripRe,""),10):(this.useNull?null:0)},sortType:a.none,type:"float"},BOOL:{convert:function(b){return b===true||b==="true"||b==1},sortType:a.none,type:"bool"},DATE:{convert:function(c){var d=this.dateFormat;if(!c){return null}if(Ext.isDate(c)){return c}if(d){if(d=="timestamp"){return new Date(c*1000)}if(d=="time"){return new Date(parseInt(c,10))}return Date.parseDate(c,d)}var b=Date.parse(c);return b?new Date(b):null},sortType:a.asDate,type:"date"}});Ext.apply(this,{BOOLEAN:this.BOOL,INTEGER:this.INT,NUMBER:this.FLOAT})};Ext.data.JsonWriter=Ext.extend(Ext.data.DataWriter,{encode:true,encodeDelete:false,constructor:function(a){Ext.data.JsonWriter.superclass.constructor.call(this,a)},render:function(c,d,b){if(this.encode===true){Ext.apply(c,d);c[this.meta.root]=Ext.encode(b)}else{var a=Ext.apply({},d);a[this.meta.root]=b;c.jsonData=a}},createRecord:function(a){return this.toHash(a)},updateRecord:function(a){return this.toHash(a)},destroyRecord:function(b){if(this.encodeDelete){var a={};a[this.meta.idProperty]=b.id;return a}else{return b.id}}});Ext.data.JsonReader=function(a,b){a=a||{};Ext.applyIf(a,{idProperty:"id",successProperty:"success",totalProperty:"total"});Ext.data.JsonReader.superclass.constructor.call(this,a,b||a.fields)};Ext.extend(Ext.data.JsonReader,Ext.data.DataReader,{read:function(a){var b=a.responseText;var c=Ext.decode(b);if(!c){throw {message:"JsonReader.read: Json object not found"}}return this.readRecords(c)},readResponse:function(e,b){var g=(b.responseText!==undefined)?Ext.decode(b.responseText):b;if(!g){throw new Ext.data.JsonReader.Error("response")}var a=this.getRoot(g);if(e===Ext.data.Api.actions.create){var d=Ext.isDefined(a);if(d&&Ext.isEmpty(a)){throw new Ext.data.JsonReader.Error("root-empty",this.meta.root)}else{if(!d){throw new Ext.data.JsonReader.Error("root-undefined-response",this.meta.root)}}}var c=new Ext.data.Response({action:e,success:this.getSuccess(g),data:(a)?this.extractData(a,false):[],message:this.getMessage(g),raw:g});if(Ext.isEmpty(c.success)){throw new Ext.data.JsonReader.Error("successProperty-response",this.meta.successProperty)}return c},readRecords:function(a){this.jsonData=a;if(a.metaData){this.onMetaChange(a.metaData)}var n=this.meta,h=this.recordType,b=h.prototype.fields,m=b.items,i=b.length,k;var g=this.getRoot(a),e=g.length,d=e,l=true;if(n.totalProperty){k=parseInt(this.getTotal(a),10);if(!isNaN(k)){d=k}}if(n.successProperty){k=this.getSuccess(a);if(k===false||k==="false"){l=false}}return{success:l,records:this.extractData(g,true),totalRecords:d}},buildExtractors:function(){if(this.ef){return}var m=this.meta,h=this.recordType,e=h.prototype.fields,l=e.items,k=e.length;if(m.totalProperty){this.getTotal=this.createAccessor(m.totalProperty)}if(m.successProperty){this.getSuccess=this.createAccessor(m.successProperty)}if(m.messageProperty){this.getMessage=this.createAccessor(m.messageProperty)}this.getRoot=m.root?this.createAccessor(m.root):function(g){return g};if(m.id||m.idProperty){var d=this.createAccessor(m.id||m.idProperty);this.getId=function(i){var g=d(i);return(g===undefined||g==="")?null:g}}else{this.getId=function(){return null}}var c=[];for(var b=0;b<k;b++){e=l[b];var a=(e.mapping!==undefined&&e.mapping!==null)?e.mapping:e.name;c.push(this.createAccessor(a))}this.ef=c},simpleAccess:function(b,a){return b[a]},createAccessor:function(){var a=/[\[\.]/;return function(c){if(Ext.isEmpty(c)){return Ext.emptyFn}if(Ext.isFunction(c)){return c}var b=String(c).search(a);if(b>=0){return new Function("obj","return obj"+(b>0?".":"")+c)}return function(d){return d[c]}}}(),extractValues:function(h,d,a){var g,c={};for(var e=0;e<a;e++){g=d[e];var b=this.ef[e](h);c[g.name]=g.convert((b!==undefined)?b:g.defaultValue,h)}return c}});Ext.data.JsonReader.Error=Ext.extend(Ext.Error,{constructor:function(b,a){this.arg=a;Ext.Error.call(this,b)},name:"Ext.data.JsonReader"});Ext.apply(Ext.data.JsonReader.Error.prototype,{lang:{response:"An error occurred while json-decoding your server response","successProperty-response":'Could not locate your "successProperty" in your server response. Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response. See the JsonReader docs.',"root-undefined-config":'Your JsonReader was configured without a "root" property. Please review your JsonReader config and make sure to define the root property. See the JsonReader docs.',"idProperty-undefined":'Your JsonReader was configured without an "idProperty" Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id"). See the JsonReader docs.',"root-empty":'Data was expected to be returned by the server in the "root" property of the response. Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response. See JsonReader docs.'}});Ext.data.ArrayReader=Ext.extend(Ext.data.JsonReader,{readRecords:function(r){this.arrayData=r;var l=this.meta,d=l?Ext.num(l.idIndex,l.id):null,b=this.recordType,q=b.prototype.fields,z=[],e=true,g;var u=this.getRoot(r);for(var y=0,A=u.length;y<A;y++){var t=u[y],a={},p=((d||d===0)&&t[d]!==undefined&&t[d]!==""?t[d]:null);for(var x=0,m=q.length;x<m;x++){var B=q.items[x],w=B.mapping!==undefined&&B.mapping!==null?B.mapping:x;g=t[w]!==undefined?t[w]:B.defaultValue;g=B.convert(g,t);a[B.name]=g}var c=new b(a,p);c.json=t;z[z.length]=c}var h=z.length;if(l.totalProperty){g=parseInt(this.getTotal(r),10);if(!isNaN(g)){h=g}}if(l.successProperty){g=this.getSuccess(r);if(g===false||g==="false"){e=false}}return{success:e,records:z,totalRecords:h}}});Ext.data.ArrayStore=Ext.extend(Ext.data.Store,{constructor:function(a){Ext.data.ArrayStore.superclass.constructor.call(this,Ext.apply(a,{reader:new Ext.data.ArrayReader(a)}))},loadData:function(e,b){if(this.expandData===true){var d=[];for(var c=0,a=e.length;c<a;c++){d[d.length]=[e[c]]}e=d}Ext.data.ArrayStore.superclass.loadData.call(this,e,b)}});Ext.reg("arraystore",Ext.data.ArrayStore);Ext.data.SimpleStore=Ext.data.ArrayStore;Ext.reg("simplestore",Ext.data.SimpleStore);Ext.data.JsonStore=Ext.extend(Ext.data.Store,{constructor:function(a){Ext.data.JsonStore.superclass.constructor.call(this,Ext.apply(a,{reader:new Ext.data.JsonReader(a)}))}});Ext.reg("jsonstore",Ext.data.JsonStore);Ext.data.XmlWriter=function(a){Ext.data.XmlWriter.superclass.constructor.apply(this,arguments);this.tpl=(typeof(this.tpl)==="string")?new Ext.XTemplate(this.tpl).compile():this.tpl.compile()};Ext.extend(Ext.data.XmlWriter,Ext.data.DataWriter,{documentRoot:"xrequest",forceDocumentRoot:false,root:"records",xmlVersion:"1.0",xmlEncoding:"ISO-8859-15",tpl:'<tpl for="."><\u003fxml version="{version}" encoding="{encoding}"\u003f><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}></tpl></tpl></tpl><tpl if="records.length>1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length>1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',render:function(b,c,a){c=this.toArray(c);b.xmlData=this.tpl.applyTemplate({version:this.xmlVersion,encoding:this.xmlEncoding,documentRoot:(c.length>0||this.forceDocumentRoot===true)?this.documentRoot:false,record:this.meta.record,root:this.root,baseParams:c,records:(Ext.isArray(a[0]))?a:[a]})},createRecord:function(a){return this.toArray(this.toHash(a))},updateRecord:function(a){return this.toArray(this.toHash(a))},destroyRecord:function(b){var a={};a[this.meta.idProperty]=b.id;return this.toArray(a)}});Ext.data.XmlReader=function(a,b){a=a||{};Ext.applyIf(a,{idProperty:a.idProperty||a.idPath||a.id,successProperty:a.successProperty||a.success});Ext.data.XmlReader.superclass.constructor.call(this,a,b||a.fields)};Ext.extend(Ext.data.XmlReader,Ext.data.DataReader,{read:function(a){var b=a.responseXML;if(!b){throw {message:"XmlReader.read: XML Document not available"}}return this.readRecords(b)},readRecords:function(d){this.xmlData=d;var a=d.documentElement||d,c=Ext.DomQuery,g=0,e=true;if(this.meta.totalProperty){g=this.getTotal(a,0)}if(this.meta.successProperty){e=this.getSuccess(a)}var b=this.extractData(c.select(this.meta.record,a),true);return{success:e,records:b,totalRecords:g||b.length}},readResponse:function(g,b){var e=Ext.DomQuery,h=b.responseXML,a=h.documentElement||h;var c=new Ext.data.Response({action:g,success:this.getSuccess(a),message:this.getMessage(a),data:this.extractData(e.select(this.meta.record,a)||e.select(this.meta.root,a),false),raw:h});if(Ext.isEmpty(c.success)){throw new Ext.data.DataReader.Error("successProperty-response",this.meta.successProperty)}if(g===Ext.data.Api.actions.create){var d=Ext.isDefined(c.data);if(d&&Ext.isEmpty(c.data)){throw new Ext.data.JsonReader.Error("root-empty",this.meta.root)}else{if(!d){throw new Ext.data.JsonReader.Error("root-undefined-response",this.meta.root)}}}return c},getSuccess:function(){return true},buildExtractors:function(){if(this.ef){return}var m=this.meta,h=this.recordType,e=h.prototype.fields,l=e.items,k=e.length;if(m.totalProperty){this.getTotal=this.createAccessor(m.totalProperty)}if(m.successProperty){this.getSuccess=this.createAccessor(m.successProperty)}if(m.messageProperty){this.getMessage=this.createAccessor(m.messageProperty)}this.getRoot=function(g){return(!Ext.isEmpty(g[this.meta.record]))?g[this.meta.record]:g[this.meta.root]};if(m.idPath||m.idProperty){var d=this.createAccessor(m.idPath||m.idProperty);this.getId=function(g){var i=d(g)||g.id;return(i===undefined||i==="")?null:i}}else{this.getId=function(){return null}}var c=[];for(var b=0;b<k;b++){e=l[b];var a=(e.mapping!==undefined&&e.mapping!==null)?e.mapping:e.name;c.push(this.createAccessor(a))}this.ef=c},createAccessor:function(){var a=Ext.DomQuery;return function(b){if(Ext.isFunction(b)){return b}switch(b){case this.meta.totalProperty:return function(c,d){return a.selectNumber(b,c,d)};break;case this.meta.successProperty:return function(d,e){var c=a.selectValue(b,d,true);var g=c!==false&&c!=="false";return g};break;default:return function(c,d){return a.selectValue(b,c,d)};break}}}(),extractValues:function(h,d,a){var g,c={};for(var e=0;e<a;e++){g=d[e];var b=this.ef[e](h);c[g.name]=g.convert((b!==undefined)?b:g.defaultValue,h)}return c}});Ext.data.XmlStore=Ext.extend(Ext.data.Store,{constructor:function(a){Ext.data.XmlStore.superclass.constructor.call(this,Ext.apply(a,{reader:new Ext.data.XmlReader(a)}))}});Ext.reg("xmlstore",Ext.data.XmlStore);Ext.data.GroupingStore=Ext.extend(Ext.data.Store,{constructor:function(d){d=d||{};this.hasMultiSort=true;this.multiSortInfo=this.multiSortInfo||{sorters:[]};var e=this.multiSortInfo.sorters,c=d.groupField||this.groupField,b=d.sortInfo||this.sortInfo,a=d.groupDir||this.groupDir;if(c){e.push({field:c,direction:a})}if(b){e.push(b)}Ext.data.GroupingStore.superclass.constructor.call(this,d);this.addEvents("groupchange");this.applyGroupField()},remoteGroup:false,groupOnSort:false,groupDir:"ASC",clearGrouping:function(){this.groupField=false;if(this.remoteGroup){if(this.baseParams){delete this.baseParams.groupBy;delete this.baseParams.groupDir}var a=this.lastOptions;if(a&&a.params){delete a.params.groupBy;delete a.params.groupDir}this.reload()}else{this.sort();this.fireEvent("datachanged",this)}},groupBy:function(e,a,d){d=d?(String(d).toUpperCase()=="DESC"?"DESC":"ASC"):this.groupDir;if(this.groupField==e&&this.groupDir==d&&!a){return}var c=this.multiSortInfo.sorters;if(c.length>0&&c[0].field==this.groupField){c.shift()}this.groupField=e;this.groupDir=d;this.applyGroupField();var b=function(){this.fireEvent("groupchange",this,this.getGroupState())};if(this.groupOnSort){this.sort(e,d);b.call(this);return}if(this.remoteGroup){this.on("load",b,this,{single:true});this.reload()}else{this.sort(c);b.call(this)}},sort:function(h,c){if(this.remoteSort){return Ext.data.GroupingStore.superclass.sort.call(this,h,c)}var g=[];if(Ext.isArray(arguments[0])){g=arguments[0]}else{if(h==undefined){g=this.sortInfo?[this.sortInfo]:[]}else{var e=this.fields.get(h);if(!e){return false}var b=e.name,a=this.sortInfo||null,d=this.sortToggle?this.sortToggle[b]:null;if(!c){if(a&&a.field==b){c=(this.sortToggle[b]||"ASC").toggle("ASC","DESC")}else{c=e.sortDir}}this.sortToggle[b]=c;this.sortInfo={field:b,direction:c};g=[this.sortInfo]}}if(this.groupField){g.unshift({direction:this.groupDir,field:this.groupField})}return this.multiSort.call(this,g,c)},applyGroupField:function(){if(this.remoteGroup){if(!this.baseParams){this.baseParams={}}Ext.apply(this.baseParams,{groupBy:this.groupField,groupDir:this.groupDir});var a=this.lastOptions;if(a&&a.params){a.params.groupDir=this.groupDir;delete a.params.groupBy}}},applyGrouping:function(a){if(this.groupField!==false){this.groupBy(this.groupField,true,this.groupDir);return true}else{if(a===true){this.fireEvent("datachanged",this)}return false}},getGroupState:function(){return this.groupOnSort&&this.groupField!==false?(this.sortInfo?this.sortInfo.field:undefined):this.groupField}});Ext.reg("groupingstore",Ext.data.GroupingStore);Ext.data.DirectProxy=function(a){Ext.apply(this,a);if(typeof this.paramOrder=="string"){this.paramOrder=this.paramOrder.split(/[\s,|]/)}Ext.data.DirectProxy.superclass.constructor.call(this,a)};Ext.extend(Ext.data.DirectProxy,Ext.data.DataProxy,{paramOrder:undefined,paramsAsHash:true,directFn:undefined,doRequest:function(b,c,a,e,l,m,o){var k=[],h=this.api[b]||this.directFn;switch(b){case Ext.data.Api.actions.create:k.push(a.jsonData);break;case Ext.data.Api.actions.read:if(h.directCfg.method.len>0){if(this.paramOrder){for(var d=0,g=this.paramOrder.length;d<g;d++){k.push(a[this.paramOrder[d]])}}else{if(this.paramsAsHash){k.push(a)}}}break;case Ext.data.Api.actions.update:k.push(a.jsonData);break;case Ext.data.Api.actions.destroy:k.push(a.jsonData);break}var n={params:a||{},request:{callback:l,scope:m,arg:o},reader:e};k.push(this.createCallback(b,c,n),this);h.apply(window,k)},createCallback:function(d,a,b){var c=this;return function(e,g){if(!g.status){if(d===Ext.data.Api.actions.read){c.fireEvent("loadexception",c,b,g,null)}c.fireEvent("exception",c,"remote",d,b,g,null);b.request.callback.call(b.request.scope,null,b.request.arg,false);return}if(d===Ext.data.Api.actions.read){c.onRead(d,b,e,g)}else{c.onWrite(d,b,e,g,a)}}},onRead:function(g,e,a,d){var b;try{b=e.reader.readRecords(a)}catch(c){this.fireEvent("loadexception",this,e,d,c);this.fireEvent("exception",this,"response",g,e,d,c);e.request.callback.call(e.request.scope,null,e.request.arg,false);return}this.fireEvent("load",this,d,e.request.arg);e.request.callback.call(e.request.scope,b,e.request.arg,true)},onWrite:function(g,d,a,c,b){var e=d.reader.extractData(d.reader.getRoot(a),false);var h=d.reader.getSuccess(a);h=(h!==false);if(h){this.fireEvent("write",this,g,e,c,b,d.request.arg)}else{this.fireEvent("exception",this,"remote",g,d,a,b)}d.request.callback.call(d.request.scope,e,c,h)}});Ext.data.DirectStore=Ext.extend(Ext.data.Store,{constructor:function(a){var b=Ext.apply({},{batchTransactions:false},a);Ext.data.DirectStore.superclass.constructor.call(this,Ext.apply(b,{proxy:Ext.isDefined(b.proxy)?b.proxy:new Ext.data.DirectProxy(Ext.copyTo({},b,"paramOrder,paramsAsHash,directFn,api")),reader:(!Ext.isDefined(b.reader)&&b.fields)?new Ext.data.JsonReader(Ext.copyTo({},b,"totalProperty,root,idProperty"),b.fields):b.reader}))}});Ext.reg("directstore",Ext.data.DirectStore);Ext.Direct=Ext.extend(Ext.util.Observable,{exceptions:{TRANSPORT:"xhr",PARSE:"parse",LOGIN:"login",SERVER:"exception"},constructor:function(){this.addEvents("event","exception");this.transactions={};this.providers={}},addProvider:function(e){var c=arguments;if(c.length>1){for(var d=0,b=c.length;d<b;d++){this.addProvider(c[d])}return}if(!e.events){e=new Ext.Direct.PROVIDERS[e.type](e)}e.id=e.id||Ext.id();this.providers[e.id]=e;e.on("data",this.onProviderData,this);e.on("exception",this.onProviderException,this);if(!e.isConnected()){e.connect()}return e},getProvider:function(a){return this.providers[a]},removeProvider:function(b){var a=b.id?b:this.providers[b];a.un("data",this.onProviderData,this);a.un("exception",this.onProviderException,this);delete this.providers[a.id];return a},addTransaction:function(a){this.transactions[a.tid]=a;return a},removeTransaction:function(a){delete this.transactions[a.tid||a];return a},getTransaction:function(a){return this.transactions[a.tid||a]},onProviderData:function(d,c){if(Ext.isArray(c)){for(var b=0,a=c.length;b<a;b++){this.onProviderData(d,c[b])}return}if(c.name&&c.name!="event"&&c.name!="exception"){this.fireEvent(c.name,c)}else{if(c.type=="exception"){this.fireEvent("exception",c)}}this.fireEvent("event",c,d)},createEvent:function(a,b){return new Ext.Direct.eventTypes[a.type](Ext.apply(a,b))}});Ext.Direct=new Ext.Direct();Ext.Direct.TID=1;Ext.Direct.PROVIDERS={};Ext.Direct.Transaction=function(a){Ext.apply(this,a);this.tid=++Ext.Direct.TID;this.retryCount=0};Ext.Direct.Transaction.prototype={send:function(){this.provider.queueTransaction(this)},retry:function(){this.retryCount++;this.send()},getProvider:function(){return this.provider}};Ext.Direct.Event=function(a){Ext.apply(this,a)};Ext.Direct.Event.prototype={status:true,getData:function(){return this.data}};Ext.Direct.RemotingEvent=Ext.extend(Ext.Direct.Event,{type:"rpc",getTransaction:function(){return this.transaction||Ext.Direct.getTransaction(this.tid)}});Ext.Direct.ExceptionEvent=Ext.extend(Ext.Direct.RemotingEvent,{status:false,type:"exception"});Ext.Direct.eventTypes={rpc:Ext.Direct.RemotingEvent,event:Ext.Direct.Event,exception:Ext.Direct.ExceptionEvent};Ext.direct.Provider=Ext.extend(Ext.util.Observable,{priority:1,constructor:function(a){Ext.apply(this,a);this.addEvents("connect","disconnect","data","exception");Ext.direct.Provider.superclass.constructor.call(this,a)},isConnected:function(){return false},connect:Ext.emptyFn,disconnect:Ext.emptyFn});Ext.direct.JsonProvider=Ext.extend(Ext.direct.Provider,{parseResponse:function(a){if(!Ext.isEmpty(a.responseText)){if(typeof a.responseText=="object"){return a.responseText}return Ext.decode(a.responseText)}return null},getEvents:function(k){var g=null;try{g=this.parseResponse(k)}catch(h){var d=new Ext.Direct.ExceptionEvent({data:h,xhr:k,code:Ext.Direct.exceptions.PARSE,message:"Error parsing json response: \n\n "+g});return[d]}var c=[];if(Ext.isArray(g)){for(var b=0,a=g.length;b<a;b++){c.push(Ext.Direct.createEvent(g[b]))}}else{c.push(Ext.Direct.createEvent(g))}return c}});Ext.direct.PollingProvider=Ext.extend(Ext.direct.JsonProvider,{priority:3,interval:3000,constructor:function(a){Ext.direct.PollingProvider.superclass.constructor.call(this,a);this.addEvents("beforepoll","poll")},isConnected:function(){return !!this.pollTask},connect:function(){if(this.url&&!this.pollTask){this.pollTask=Ext.TaskMgr.start({run:function(){if(this.fireEvent("beforepoll",this)!==false){if(typeof this.url=="function"){this.url(this.baseParams)}else{Ext.Ajax.request({url:this.url,callback:this.onData,scope:this,params:this.baseParams})}}},interval:this.interval,scope:this});this.fireEvent("connect",this)}else{if(!this.url){throw"Error initializing PollingProvider, no url configured."}}},disconnect:function(){if(this.pollTask){Ext.TaskMgr.stop(this.pollTask);delete this.pollTask;this.fireEvent("disconnect",this)}},onData:function(d,k,h){if(k){var c=this.getEvents(h);for(var b=0,a=c.length;b<a;b++){var g=c[b];this.fireEvent("data",this,g)}}else{var g=new Ext.Direct.ExceptionEvent({data:g,code:Ext.Direct.exceptions.TRANSPORT,message:"Unable to connect to the server.",xhr:h});this.fireEvent("data",this,g)}}});Ext.Direct.PROVIDERS.polling=Ext.direct.PollingProvider;Ext.direct.RemotingProvider=Ext.extend(Ext.direct.JsonProvider,{enableBuffer:10,maxRetries:1,timeout:undefined,constructor:function(a){Ext.direct.RemotingProvider.superclass.constructor.call(this,a);this.addEvents("beforecall","call");this.namespace=(Ext.isString(this.namespace))?Ext.ns(this.namespace):this.namespace||window;this.transactions={};this.callBuffer=[]},initAPI:function(){var h=this.actions;for(var k in h){var d=this.namespace[k]||(this.namespace[k]={}),e=h[k];for(var g=0,b=e.length;g<b;g++){var a=e[g];d[a.name]=this.createMethod(k,a)}}},isConnected:function(){return !!this.connected},connect:function(){if(this.url){this.initAPI();this.connected=true;this.fireEvent("connect",this)}else{if(!this.url){throw"Error initializing RemotingProvider, no url configured."}}},disconnect:function(){if(this.connected){this.connected=false;this.fireEvent("disconnect",this)}},onData:function(a,h,k){if(h){var l=this.getEvents(k);for(var b=0,c=l.length;b<c;b++){var d=l[b],m=this.getTransaction(d);this.fireEvent("data",this,d);if(m){this.doCallback(m,d,true);Ext.Direct.removeTransaction(m)}}}else{var g=[].concat(a.ts);for(var b=0,c=g.length;b<c;b++){var m=this.getTransaction(g[b]);if(m&&m.retryCount<this.maxRetries){m.retry()}else{var d=new Ext.Direct.ExceptionEvent({data:d,transaction:m,code:Ext.Direct.exceptions.TRANSPORT,message:"Unable to connect to the server.",xhr:k});this.fireEvent("data",this,d);if(m){this.doCallback(m,d,false);Ext.Direct.removeTransaction(m)}}}}},getCallData:function(a){return{action:a.action,method:a.method,data:a.data,type:"rpc",tid:a.tid}},doSend:function(d){var g={url:this.url,callback:this.onData,scope:this,ts:d,timeout:this.timeout},b;if(Ext.isArray(d)){b=[];for(var c=0,a=d.length;c<a;c++){b.push(this.getCallData(d[c]))}}else{b=this.getCallData(d)}if(this.enableUrlEncode){var e={};e[Ext.isString(this.enableUrlEncode)?this.enableUrlEncode:"data"]=Ext.encode(b);g.params=e}else{g.jsonData=b}Ext.Ajax.request(g)},combineAndSend:function(){var a=this.callBuffer.length;if(a>0){this.doSend(a==1?this.callBuffer[0]:this.callBuffer);this.callBuffer=[]}},queueTransaction:function(a){if(a.form){this.processForm(a);return}this.callBuffer.push(a);if(this.enableBuffer){if(!this.callTask){this.callTask=new Ext.util.DelayedTask(this.combineAndSend,this)}this.callTask.delay(Ext.isNumber(this.enableBuffer)?this.enableBuffer:10)}else{this.combineAndSend()}},doCall:function(i,a,b){var h=null,e=b[a.len],g=b[a.len+1];if(a.len!==0){h=b.slice(0,a.len)}var d=new Ext.Direct.Transaction({provider:this,args:b,action:i,method:a.name,data:h,cb:g&&Ext.isFunction(e)?e.createDelegate(g):e});if(this.fireEvent("beforecall",this,d,a)!==false){Ext.Direct.addTransaction(d);this.queueTransaction(d);this.fireEvent("call",this,d,a)}},doForm:function(k,b,g,i,e){var d=new Ext.Direct.Transaction({provider:this,action:k,method:b.name,args:[g,i,e],cb:e&&Ext.isFunction(i)?i.createDelegate(e):i,isForm:true});if(this.fireEvent("beforecall",this,d,b)!==false){Ext.Direct.addTransaction(d);var a=String(g.getAttribute("enctype")).toLowerCase()=="multipart/form-data",h={extTID:d.tid,extAction:k,extMethod:b.name,extType:"rpc",extUpload:String(a)};Ext.apply(d,{form:Ext.getDom(g),isUpload:a,params:i&&Ext.isObject(i.params)?Ext.apply(h,i.params):h});this.fireEvent("call",this,d,b);this.processForm(d)}},processForm:function(a){Ext.Ajax.request({url:this.url,params:a.params,callback:this.onData,scope:this,form:a.form,isUpload:a.isUpload,ts:a})},createMethod:function(d,a){var b;if(!a.formHandler){b=function(){this.doCall(d,a,Array.prototype.slice.call(arguments,0))}.createDelegate(this)}else{b=function(e,g,c){this.doForm(d,a,e,g,c)}.createDelegate(this)}b.directCfg={action:d,method:a};return b},getTransaction:function(a){return a&&a.tid?Ext.Direct.getTransaction(a.tid):null},doCallback:function(c,g){var d=g.status?"success":"failure";if(c&&c.cb){var b=c.cb,a=Ext.isDefined(g.result)?g.result:g.data;if(Ext.isFunction(b)){b(a,g)}else{Ext.callback(b[d],b.scope,[a,g]);Ext.callback(b.callback,b.scope,[a,g])}}}});Ext.Direct.PROVIDERS.remoting=Ext.direct.RemotingProvider;Ext.Resizable=Ext.extend(Ext.util.Observable,{constructor:function(d,e){this.el=Ext.get(d);if(e&&e.wrap){e.resizeChild=this.el;this.el=this.el.wrap(typeof e.wrap=="object"?e.wrap:{cls:"xresizable-wrap"});this.el.id=this.el.dom.id=e.resizeChild.id+"-rzwrap";this.el.setStyle("overflow","hidden");this.el.setPositioning(e.resizeChild.getPositioning());e.resizeChild.clearPositioning();if(!e.width||!e.height){var g=e.resizeChild.getSize();this.el.setSize(g.width,g.height)}if(e.pinned&&!e.adjustments){e.adjustments="auto"}}this.proxy=this.el.createProxy({tag:"div",cls:"x-resizable-proxy",id:this.el.id+"-rzproxy"},Ext.getBody());this.proxy.unselectable();this.proxy.enableDisplayMode("block");Ext.apply(this,e);if(this.pinned){this.disableTrackOver=true;this.el.addClass("x-resizable-pinned")}var l=this.el.getStyle("position");if(l!="absolute"&&l!="fixed"){this.el.setStyle("position","relative")}if(!this.handles){this.handles="s,e,se";if(this.multiDirectional){this.handles+=",n,w"}}if(this.handles=="all"){this.handles="n s e w ne nw se sw"}var p=this.handles.split(/\s*?[,;]\s*?| /);var c=Ext.Resizable.positions;for(var k=0,m=p.length;k<m;k++){if(p[k]&&c[p[k]]){var o=c[p[k]];this[o]=new Ext.Resizable.Handle(this,o,this.disableTrackOver,this.transparent,this.handleCls)}}this.corner=this.southeast;if(this.handles.indexOf("n")!=-1||this.handles.indexOf("w")!=-1){this.updateBox=true}this.activeHandle=null;if(this.resizeChild){if(typeof this.resizeChild=="boolean"){this.resizeChild=Ext.get(this.el.dom.firstChild,true)}else{this.resizeChild=Ext.get(this.resizeChild,true)}}if(this.adjustments=="auto"){var b=this.resizeChild;var n=this.west,h=this.east,a=this.north,p=this.south;if(b&&(n||a)){b.position("relative");b.setLeft(n?n.el.getWidth():0);b.setTop(a?a.el.getHeight():0)}this.adjustments=[(h?-h.el.getWidth():0)+(n?-n.el.getWidth():0),(a?-a.el.getHeight():0)+(p?-p.el.getHeight():0)-1]}if(this.draggable){this.dd=this.dynamic?this.el.initDD(null):this.el.initDDProxy(null,{dragElId:this.proxy.id});this.dd.setHandleElId(this.resizeChild?this.resizeChild.id:this.el.id);if(this.constrainTo){this.dd.constrainTo(this.constrainTo)}}this.addEvents("beforeresize","resize");if(this.width!==null&&this.height!==null){this.resizeTo(this.width,this.height)}else{this.updateChildSize()}if(Ext.isIE){this.el.dom.style.zoom=1}Ext.Resizable.superclass.constructor.call(this)},adjustments:[0,0],animate:false,disableTrackOver:false,draggable:false,duration:0.35,dynamic:false,easing:"easeOutStrong",enabled:true,handles:false,multiDirectional:false,height:null,width:null,heightIncrement:0,widthIncrement:0,minHeight:5,minWidth:5,maxHeight:10000,maxWidth:10000,minX:0,minY:0,pinned:false,preserveRatio:false,resizeChild:false,transparent:false,resizeTo:function(b,a){this.el.setSize(b,a);this.updateChildSize();this.fireEvent("resize",this,b,a,null)},startSizing:function(c,b){this.fireEvent("beforeresize",this,c);if(this.enabled){if(!this.overlay){this.overlay=this.el.createProxy({tag:"div",cls:"x-resizable-overlay",html:" "},Ext.getBody());this.overlay.unselectable();this.overlay.enableDisplayMode("block");this.overlay.on({scope:this,mousemove:this.onMouseMove,mouseup:this.onMouseUp})}this.overlay.setStyle("cursor",b.el.getStyle("cursor"));this.resizing=true;this.startBox=this.el.getBox();this.startPoint=c.getXY();this.offsets=[(this.startBox.x+this.startBox.width)-this.startPoint[0],(this.startBox.y+this.startBox.height)-this.startPoint[1]];this.overlay.setSize(Ext.lib.Dom.getViewWidth(true),Ext.lib.Dom.getViewHeight(true));this.overlay.show();if(this.constrainTo){var a=Ext.get(this.constrainTo);this.resizeRegion=a.getRegion().adjust(a.getFrameWidth("t"),a.getFrameWidth("l"),-a.getFrameWidth("b"),-a.getFrameWidth("r"))}this.proxy.setStyle("visibility","hidden");this.proxy.show();this.proxy.setBox(this.startBox);if(!this.dynamic){this.proxy.setStyle("visibility","visible")}}},onMouseDown:function(a,b){if(this.enabled){b.stopEvent();this.activeHandle=a;this.startSizing(b,a)}},onMouseUp:function(b){this.activeHandle=null;var a=this.resizeElement();this.resizing=false;this.handleOut();this.overlay.hide();this.proxy.hide();this.fireEvent("resize",this,a.width,a.height,b)},updateChildSize:function(){if(this.resizeChild){var d=this.el;var e=this.resizeChild;var c=this.adjustments;if(d.dom.offsetWidth){var a=d.getSize(true);e.setSize(a.width+c[0],a.height+c[1])}if(Ext.isIE){setTimeout(function(){if(d.dom.offsetWidth){var g=d.getSize(true);e.setSize(g.width+c[0],g.height+c[1])}},10)}}},snap:function(c,e,b){if(!e||!c){return c}var d=c;var a=c%e;if(a>0){if(a>(e/2)){d=c+(e-a)}else{d=c-a}}return Math.max(b,d)},resizeElement:function(){var a=this.proxy.getBox();if(this.updateBox){this.el.setBox(a,false,this.animate,this.duration,null,this.easing)}else{this.el.setSize(a.width,a.height,this.animate,this.duration,null,this.easing)}this.updateChildSize();if(!this.dynamic){this.proxy.hide()}if(this.draggable&&this.constrainTo){this.dd.resetConstraints();this.dd.constrainTo(this.constrainTo)}return a},constrain:function(b,c,a,d){if(b-c<a){c=b-a}else{if(b-c>d){c=b-d}}return c},onMouseMove:function(A){if(this.enabled&&this.activeHandle){try{if(this.resizeRegion&&!this.resizeRegion.contains(A.getPoint())){return}var u=this.curSize||this.startBox,m=this.startBox.x,l=this.startBox.y,c=m,b=l,n=u.width,v=u.height,d=n,p=v,o=this.minWidth,B=this.minHeight,t=this.maxWidth,E=this.maxHeight,i=this.widthIncrement,a=this.heightIncrement,C=A.getXY(),s=-(this.startPoint[0]-Math.max(this.minX,C[0])),q=-(this.startPoint[1]-Math.max(this.minY,C[1])),k=this.activeHandle.position,F,g;switch(k){case"east":n+=s;n=Math.min(Math.max(o,n),t);break;case"south":v+=q;v=Math.min(Math.max(B,v),E);break;case"southeast":n+=s;v+=q;n=Math.min(Math.max(o,n),t);v=Math.min(Math.max(B,v),E);break;case"north":q=this.constrain(v,q,B,E);l+=q;v-=q;break;case"west":s=this.constrain(n,s,o,t);m+=s;n-=s;break;case"northeast":n+=s;n=Math.min(Math.max(o,n),t);q=this.constrain(v,q,B,E);l+=q;v-=q;break;case"northwest":s=this.constrain(n,s,o,t);q=this.constrain(v,q,B,E);l+=q;v-=q;m+=s;n-=s;break;case"southwest":s=this.constrain(n,s,o,t);v+=q;v=Math.min(Math.max(B,v),E);m+=s;n-=s;break}var r=this.snap(n,i,o);var D=this.snap(v,a,B);if(r!=n||D!=v){switch(k){case"northeast":l-=D-v;break;case"north":l-=D-v;break;case"southwest":m-=r-n;break;case"west":m-=r-n;break;case"northwest":m-=r-n;l-=D-v;break}n=r;v=D}if(this.preserveRatio){switch(k){case"southeast":case"east":v=p*(n/d);v=Math.min(Math.max(B,v),E);n=d*(v/p);break;case"south":n=d*(v/p);n=Math.min(Math.max(o,n),t);v=p*(n/d);break;case"northeast":n=d*(v/p);n=Math.min(Math.max(o,n),t);v=p*(n/d);break;case"north":F=n;n=d*(v/p);n=Math.min(Math.max(o,n),t);v=p*(n/d);m+=(F-n)/2;break;case"southwest":v=p*(n/d);v=Math.min(Math.max(B,v),E);F=n;n=d*(v/p);m+=F-n;break;case"west":g=v;v=p*(n/d);v=Math.min(Math.max(B,v),E);l+=(g-v)/2;F=n;n=d*(v/p);m+=F-n;break;case"northwest":F=n;g=v;v=p*(n/d);v=Math.min(Math.max(B,v),E);n=d*(v/p);l+=g-v;m+=F-n;break}}this.proxy.setBounds(m,l,n,v);if(this.dynamic){this.resizeElement()}}catch(z){}}},handleOver:function(){if(this.enabled){this.el.addClass("x-resizable-over")}},handleOut:function(){if(!this.resizing){this.el.removeClass("x-resizable-over")}},getEl:function(){return this.el},getResizeChild:function(){return this.resizeChild},destroy:function(b){Ext.destroy(this.dd,this.overlay,this.proxy);this.overlay=null;this.proxy=null;var c=Ext.Resizable.positions;for(var a in c){if(typeof c[a]!="function"&&this[c[a]]){this[c[a]].destroy()}}if(b){this.el.update("");Ext.destroy(this.el);this.el=null}this.purgeListeners()},syncHandleHeight:function(){var a=this.el.getHeight(true);if(this.west){this.west.el.setHeight(a)}if(this.east){this.east.el.setHeight(a)}}});Ext.Resizable.positions={n:"north",s:"south",e:"east",w:"west",se:"southeast",sw:"southwest",nw:"northwest",ne:"northeast"};Ext.Resizable.Handle=Ext.extend(Object,{constructor:function(d,g,c,e,a){if(!this.tpl){var b=Ext.DomHelper.createTemplate({tag:"div",cls:"x-resizable-handle x-resizable-handle-{0}"});b.compile();Ext.Resizable.Handle.prototype.tpl=b}this.position=g;this.rz=d;this.el=this.tpl.append(d.el.dom,[this.position],true);this.el.unselectable();if(e){this.el.setOpacity(0)}if(!Ext.isEmpty(a)){this.el.addClass(a)}this.el.on("mousedown",this.onMouseDown,this);if(!c){this.el.on({scope:this,mouseover:this.onMouseOver,mouseout:this.onMouseOut})}},afterResize:function(a){},onMouseDown:function(a){this.rz.onMouseDown(this,a)},onMouseOver:function(a){this.rz.handleOver(this,a)},onMouseOut:function(a){this.rz.handleOut(this,a)},destroy:function(){Ext.destroy(this.el);this.el=null}});Ext.Window=Ext.extend(Ext.Panel,{baseCls:"x-window",resizable:true,draggable:true,closable:true,closeAction:"close",constrain:false,constrainHeader:false,plain:false,minimizable:false,maximizable:false,minHeight:100,minWidth:200,expandOnShow:true,showAnimDuration:0.25,hideAnimDuration:0.25,collapsible:false,initHidden:undefined,hidden:true,elements:"header,body",frame:true,floating:true,initComponent:function(){this.initTools();Ext.Window.superclass.initComponent.call(this);this.addEvents("resize","maximize","minimize","restore");if(Ext.isDefined(this.initHidden)){this.hidden=this.initHidden}if(this.hidden===false){this.hidden=true;this.show()}},getState:function(){return Ext.apply(Ext.Window.superclass.getState.call(this)||{},this.getBox(true))},onRender:function(b,a){Ext.Window.superclass.onRender.call(this,b,a);if(this.plain){this.el.addClass("x-window-plain")}this.focusEl=this.el.createChild({tag:"a",href:"#",cls:"x-dlg-focus",tabIndex:"-1",html:" "});this.focusEl.swallowEvent("click",true);this.proxy=this.el.createProxy("x-window-proxy");this.proxy.enableDisplayMode("block");if(this.modal){this.mask=this.container.createChild({cls:"ext-el-mask"},this.el.dom);this.mask.enableDisplayMode("block");this.mask.hide();this.mon(this.mask,"click",this.focus,this)}if(this.maximizable){this.mon(this.header,"dblclick",this.toggleMaximize,this)}},initEvents:function(){Ext.Window.superclass.initEvents.call(this);if(this.animateTarget){this.setAnimateTarget(this.animateTarget)}if(this.resizable){this.resizer=new Ext.Resizable(this.el,{minWidth:this.minWidth,minHeight:this.minHeight,handles:this.resizeHandles||"all",pinned:true,resizeElement:this.resizerAction,handleCls:"x-window-handle"});this.resizer.window=this;this.mon(this.resizer,"beforeresize",this.beforeResize,this)}if(this.draggable){this.header.addClass("x-window-draggable")}this.mon(this.el,"mousedown",this.toFront,this);this.manager=this.manager||Ext.WindowMgr;this.manager.register(this);if(this.maximized){this.maximized=false;this.maximize()}if(this.closable){var a=this.getKeyMap();a.on(27,this.onEsc,this);a.disable()}},initDraggable:function(){this.dd=new Ext.Window.DD(this)},onEsc:function(a,b){b.stopEvent();this[this.closeAction]()},beforeDestroy:function(){if(this.rendered){this.hide();this.clearAnchor();Ext.destroy(this.focusEl,this.resizer,this.dd,this.proxy,this.mask)}Ext.Window.superclass.beforeDestroy.call(this)},onDestroy:function(){if(this.manager){this.manager.unregister(this)}Ext.Window.superclass.onDestroy.call(this)},initTools:function(){if(this.minimizable){this.addTool({id:"minimize",handler:this.minimize.createDelegate(this,[])})}if(this.maximizable){this.addTool({id:"maximize",handler:this.maximize.createDelegate(this,[])});this.addTool({id:"restore",handler:this.restore.createDelegate(this,[]),hidden:true})}if(this.closable){this.addTool({id:"close",handler:this[this.closeAction].createDelegate(this,[])})}},resizerAction:function(){var a=this.proxy.getBox();this.proxy.hide();this.window.handleResize(a);return a},beforeResize:function(){this.resizer.minHeight=Math.max(this.minHeight,this.getFrameHeight()+40);this.resizer.minWidth=Math.max(this.minWidth,this.getFrameWidth()+40);this.resizeBox=this.el.getBox()},updateHandles:function(){if(Ext.isIE&&this.resizer){this.resizer.syncHandleHeight();this.el.repaint()}},handleResize:function(b){var a=this.resizeBox;if(a.x!=b.x||a.y!=b.y){this.updateBox(b)}else{this.setSize(b);if(Ext.isIE6&&Ext.isStrict){this.doLayout()}}this.focus();this.updateHandles();this.saveState()},focus:function(){var e=this.focusEl,a=this.defaultButton,c=typeof a,d,b;if(Ext.isDefined(a)){if(Ext.isNumber(a)&&this.fbar){e=this.fbar.items.get(a)}else{if(Ext.isString(a)){e=Ext.getCmp(a)}else{e=a}}d=e.getEl();b=Ext.getDom(this.container);if(d&&b){if(b!=document.body&&!Ext.lib.Region.getRegion(b).contains(Ext.lib.Region.getRegion(d.dom))){return}}}e=e||this.focusEl;e.focus.defer(10,e)},setAnimateTarget:function(a){a=Ext.get(a);this.animateTarget=a},beforeShow:function(){delete this.el.lastXY;delete this.el.lastLT;if(this.x===undefined||this.y===undefined){var a=this.el.getAlignToXY(this.container,"c-c");var b=this.el.translatePoints(a[0],a[1]);this.x=this.x===undefined?b.left:this.x;this.y=this.y===undefined?b.top:this.y}this.el.setLeftTop(this.x,this.y);if(this.expandOnShow){this.expand(false)}if(this.modal){Ext.getBody().addClass("x-body-masked");this.mask.setSize(Ext.lib.Dom.getViewWidth(true),Ext.lib.Dom.getViewHeight(true));this.mask.show()}},show:function(c,a,b){if(!this.rendered){this.render(Ext.getBody())}if(this.hidden===false){this.toFront();return this}if(this.fireEvent("beforeshow",this)===false){return this}if(a){this.on("show",a,b,{single:true})}this.hidden=false;if(Ext.isDefined(c)){this.setAnimateTarget(c)}this.beforeShow();if(this.animateTarget){this.animShow()}else{this.afterShow()}return this},afterShow:function(b){if(this.isDestroyed){return false}this.proxy.hide();this.el.setStyle("display","block");this.el.show();if(this.maximized){this.fitContainer()}if(Ext.isMac&&Ext.isGecko2){this.cascade(this.setAutoScroll)}if(this.monitorResize||this.modal||this.constrain||this.constrainHeader){Ext.EventManager.onWindowResize(this.onWindowResize,this)}this.doConstrain();this.doLayout();if(this.keyMap){this.keyMap.enable()}this.toFront();this.updateHandles();if(b&&(Ext.isIE||Ext.isWebKit)){var a=this.getSize();this.onResize(a.width,a.height)}this.onShow();this.fireEvent("show",this)},animShow:function(){this.proxy.show();this.proxy.setBox(this.animateTarget.getBox());this.proxy.setOpacity(0);var a=this.getBox();this.el.setStyle("display","none");this.proxy.shift(Ext.apply(a,{callback:this.afterShow.createDelegate(this,[true],false),scope:this,easing:"easeNone",duration:this.showAnimDuration,opacity:0.5}))},hide:function(c,a,b){if(this.hidden||this.fireEvent("beforehide",this)===false){return this}if(a){this.on("hide",a,b,{single:true})}this.hidden=true;if(c!==undefined){this.setAnimateTarget(c)}if(this.modal){this.mask.hide();Ext.getBody().removeClass("x-body-masked")}if(this.animateTarget){this.animHide()}else{this.el.hide();this.afterHide()}return this},afterHide:function(){this.proxy.hide();if(this.monitorResize||this.modal||this.constrain||this.constrainHeader){Ext.EventManager.removeResizeListener(this.onWindowResize,this)}if(this.keyMap){this.keyMap.disable()}this.onHide();this.fireEvent("hide",this)},animHide:function(){this.proxy.setOpacity(0.5);this.proxy.show();var a=this.getBox(false);this.proxy.setBox(a);this.el.hide();this.proxy.shift(Ext.apply(this.animateTarget.getBox(),{callback:this.afterHide,scope:this,duration:this.hideAnimDuration,easing:"easeNone",opacity:0}))},onShow:Ext.emptyFn,onHide:Ext.emptyFn,onWindowResize:function(){if(this.maximized){this.fitContainer()}if(this.modal){this.mask.setSize("100%","100%");var a=this.mask.dom.offsetHeight;this.mask.setSize(Ext.lib.Dom.getViewWidth(true),Ext.lib.Dom.getViewHeight(true))}this.doConstrain()},doConstrain:function(){if(this.constrain||this.constrainHeader){var b;if(this.constrain){b={right:this.el.shadowOffset,left:this.el.shadowOffset,bottom:this.el.shadowOffset}}else{var a=this.getSize();b={right:-(a.width-100),bottom:-(a.height-25)}}var c=this.el.getConstrainToXY(this.container,true,b);if(c){this.setPosition(c[0],c[1])}}},ghost:function(a){var c=this.createGhost(a);var b=this.getBox(true);c.setLeftTop(b.x,b.y);c.setWidth(b.width);this.el.hide();this.activeGhost=c;return c},unghost:function(b,a){if(!this.activeGhost){return}if(b!==false){this.el.show();this.focus.defer(10,this);if(Ext.isMac&&Ext.isGecko2){this.cascade(this.setAutoScroll)}}if(a!==false){this.setPosition(this.activeGhost.getLeft(true),this.activeGhost.getTop(true))}this.activeGhost.hide();this.activeGhost.remove();delete this.activeGhost},minimize:function(){this.fireEvent("minimize",this);return this},close:function(){if(this.fireEvent("beforeclose",this)!==false){if(this.hidden){this.doClose()}else{this.hide(null,this.doClose,this)}}},doClose:function(){this.fireEvent("close",this);this.destroy()},maximize:function(){if(!this.maximized){this.expand(false);this.restoreSize=this.getSize();this.restorePos=this.getPosition(true);if(this.maximizable){this.tools.maximize.hide();this.tools.restore.show()}this.maximized=true;this.el.disableShadow();if(this.dd){this.dd.lock()}if(this.collapsible){this.tools.toggle.hide()}this.el.addClass("x-window-maximized");this.container.addClass("x-window-maximized-ct");this.setPosition(0,0);this.fitContainer();this.fireEvent("maximize",this)}return this},restore:function(){if(this.maximized){var a=this.tools;this.el.removeClass("x-window-maximized");if(a.restore){a.restore.hide()}if(a.maximize){a.maximize.show()}this.setPosition(this.restorePos[0],this.restorePos[1]);this.setSize(this.restoreSize.width,this.restoreSize.height);delete this.restorePos;delete this.restoreSize;this.maximized=false;this.el.enableShadow(true);if(this.dd){this.dd.unlock()}if(this.collapsible&&a.toggle){a.toggle.show()}this.container.removeClass("x-window-maximized-ct");this.doConstrain();this.fireEvent("restore",this)}return this},toggleMaximize:function(){return this[this.maximized?"restore":"maximize"]()},fitContainer:function(){var a=this.container.getViewSize(false);this.setSize(a.width,a.height)},setZIndex:function(a){if(this.modal){this.mask.setStyle("z-index",a)}this.el.setZIndex(++a);a+=5;if(this.resizer){this.resizer.proxy.setStyle("z-index",++a)}this.lastZIndex=a},alignTo:function(b,a,c){var d=this.el.getAlignToXY(b,a,c);this.setPagePosition(d[0],d[1]);return this},anchorTo:function(c,e,d,b){this.clearAnchor();this.anchorTarget={el:c,alignment:e,offsets:d};Ext.EventManager.onWindowResize(this.doAnchor,this);var a=typeof b;if(a!="undefined"){Ext.EventManager.on(window,"scroll",this.doAnchor,this,{buffer:a=="number"?b:50})}return this.doAnchor()},doAnchor:function(){var a=this.anchorTarget;this.alignTo(a.el,a.alignment,a.offsets);return this},clearAnchor:function(){if(this.anchorTarget){Ext.EventManager.removeResizeListener(this.doAnchor,this);Ext.EventManager.un(window,"scroll",this.doAnchor,this);delete this.anchorTarget}return this},toFront:function(a){if(this.manager.bringToFront(this)){if(!a||!a.getTarget().focus){this.focus()}}return this},setActive:function(a){if(a){if(!this.maximized){this.el.enableShadow(true)}this.fireEvent("activate",this)}else{this.el.disableShadow();this.fireEvent("deactivate",this)}},toBack:function(){this.manager.sendToBack(this);return this},center:function(){var a=this.el.getAlignToXY(this.container,"c-c");this.setPagePosition(a[0],a[1]);return this}});Ext.reg("window",Ext.Window);Ext.Window.DD=Ext.extend(Ext.dd.DD,{constructor:function(a){this.win=a;Ext.Window.DD.superclass.constructor.call(this,a.el.id,"WindowDD-"+a.id);this.setHandleElId(a.header.id);this.scroll=false},moveOnly:true,headerOffsets:[100,25],startDrag:function(){var a=this.win;this.proxy=a.ghost(a.initialConfig.cls);if(a.constrain!==false){var c=a.el.shadowOffset;this.constrainTo(a.container,{right:c,left:c,bottom:c})}else{if(a.constrainHeader!==false){var b=this.proxy.getSize();this.constrainTo(a.container,{right:-(b.width-this.headerOffsets[0]),bottom:-(b.height-this.headerOffsets[1])})}}},b4Drag:Ext.emptyFn,onDrag:function(a){this.alignElWithMouse(this.proxy,a.getPageX(),a.getPageY())},endDrag:function(a){this.win.unghost();this.win.saveState()}});Ext.WindowGroup=function(){var g={};var d=[];var e=null;var c=function(k,i){return(!k._lastAccess||k._lastAccess<i._lastAccess)?-1:1};var h=function(){var m=d,k=m.length;if(k>0){m.sort(c);var l=m[0].manager.zseed;for(var n=0;n<k;n++){var o=m[n];if(o&&!o.hidden){o.setZIndex(l+(n*10))}}}a()};var b=function(i){if(i!=e){if(e){e.setActive(false)}e=i;if(i){i.setActive(true)}}};var a=function(){for(var k=d.length-1;k>=0;--k){if(!d[k].hidden){b(d[k]);return}}b(null)};return{zseed:9000,register:function(i){if(i.manager){i.manager.unregister(i)}i.manager=this;g[i.id]=i;d.push(i);i.on("hide",a)},unregister:function(i){delete i.manager;delete g[i.id];i.un("hide",a);d.remove(i)},get:function(i){return typeof i=="object"?i:g[i]},bringToFront:function(i){i=this.get(i);if(i!=e){i._lastAccess=new Date().getTime();h();return true}return false},sendToBack:function(i){i=this.get(i);i._lastAccess=-(new Date().getTime());h();return i},hideAll:function(){for(var i in g){if(g[i]&&typeof g[i]!="function"&&g[i].isVisible()){g[i].hide()}}},getActive:function(){return e},getBy:function(m,l){var n=[];for(var k=d.length-1;k>=0;--k){var o=d[k];if(m.call(l||o,o)!==false){n.push(o)}}return n},each:function(k,i){for(var l in g){if(g[l]&&typeof g[l]!="function"){if(k.call(i||g[l],g[l])===false){return}}}}}};Ext.WindowMgr=new Ext.WindowGroup();Ext.MessageBox=function(){var v,b,r,u,h,m,t,a,o,q,k,g,s,w,p,i="",d="",n=["ok","yes","no","cancel"];var c=function(y){s[y].blur();if(v.isVisible()){v.hide();x();Ext.callback(b.fn,b.scope||window,[y,w.dom.value,b],1)}};var x=function(){if(b&&b.cls){v.el.removeClass(b.cls)}o.reset()};var e=function(A,y,z){if(b&&b.closable!==false){v.hide();x()}if(z){z.stopEvent()}};var l=function(y){var A=0,z;if(!y){Ext.each(n,function(B){s[B].hide()});return A}v.footer.dom.style.display="";Ext.iterate(s,function(B,C){z=y[B];if(z){C.show();C.setText(Ext.isString(z)?z:Ext.MessageBox.buttonText[B]);A+=C.getEl().getWidth()+15}else{C.hide()}});return A};return{getDialog:function(y){if(!v){var A=[];s={};Ext.each(n,function(B){A.push(s[B]=new Ext.Button({text:this.buttonText[B],handler:c.createCallback(B),hideMode:"offsets"}))},this);v=new Ext.Window({autoCreate:true,title:y,resizable:false,constrain:true,constrainHeader:true,minimizable:false,maximizable:false,stateful:false,modal:true,shim:true,buttonAlign:"center",width:400,height:100,minHeight:80,plain:true,footer:true,closable:true,close:function(){if(b&&b.buttons&&b.buttons.no&&!b.buttons.cancel){c("no")}else{c("cancel")}},fbar:new Ext.Toolbar({items:A,enableOverflow:false})});v.render(document.body);v.getEl().addClass("x-window-dlg");r=v.mask;h=v.body.createChild({html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><div class="ext-mb-fix-cursor"><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div></div>'});k=Ext.get(h.dom.firstChild);var z=h.dom.childNodes[1];m=Ext.get(z.firstChild);t=Ext.get(z.childNodes[2].firstChild);t.enableDisplayMode();t.addKeyListener([10,13],function(){if(v.isVisible()&&b&&b.buttons){if(b.buttons.ok){c("ok")}else{if(b.buttons.yes){c("yes")}}}});a=Ext.get(z.childNodes[2].childNodes[1]);a.enableDisplayMode();o=new Ext.ProgressBar({renderTo:h});h.createChild({cls:"x-clear"})}return v},updateText:function(B){if(!v.isVisible()&&!b.width){v.setSize(this.maxWidth,100)}m.update(B?B+" ":" ");var z=d!=""?(k.getWidth()+k.getMargins("lr")):0,D=m.getWidth()+m.getMargins("lr"),A=v.getFrameWidth("lr"),C=v.body.getFrameWidth("lr"),y;y=Math.max(Math.min(b.width||z+D+A+C,b.maxWidth||this.maxWidth),Math.max(b.minWidth||this.minWidth,p||0));if(b.prompt===true){w.setWidth(y-z-A-C)}if(b.progress===true||b.wait===true){o.setSize(y-z-A-C)}if(Ext.isIE&&y==p){y+=4}m.update(B||" ");v.setSize(y,"auto").center();return this},updateProgress:function(z,y,A){o.updateProgress(z,y);if(A){this.updateText(A)}return this},isVisible:function(){return v&&v.isVisible()},hide:function(){var y=v?v.activeGhost:null;if(this.isVisible()||y){v.hide();x();if(y){v.unghost(false,false)}}return this},show:function(B){if(this.isVisible()){this.hide()}b=B;var C=this.getDialog(b.title||" ");C.setTitle(b.title||" ");var y=(b.closable!==false&&b.progress!==true&&b.wait!==true);C.tools.close.setDisplayed(y);w=t;b.prompt=b.prompt||(b.multiline?true:false);if(b.prompt){if(b.multiline){t.hide();a.show();a.setHeight(Ext.isNumber(b.multiline)?b.multiline:this.defaultTextHeight);w=a}else{t.show();a.hide()}}else{t.hide();a.hide()}w.dom.value=b.value||"";if(b.prompt){C.focusEl=w}else{var A=b.buttons;var z=null;if(A&&A.ok){z=s.ok}else{if(A&&A.yes){z=s.yes}}if(z){C.focusEl=z}}if(Ext.isDefined(b.iconCls)){C.setIconClass(b.iconCls)}this.setIcon(Ext.isDefined(b.icon)?b.icon:i);p=l(b.buttons);o.setVisible(b.progress===true||b.wait===true);this.updateProgress(0,b.progressText);this.updateText(b.msg);if(b.cls){C.el.addClass(b.cls)}C.proxyDrag=b.proxyDrag===true;C.modal=b.modal!==false;C.mask=b.modal!==false?r:false;if(!C.isVisible()){document.body.appendChild(v.el.dom);C.setAnimateTarget(b.animEl);C.on("show",function(){if(y===true){C.keyMap.enable()}else{C.keyMap.disable()}},this,{single:true});C.show(b.animEl)}if(b.wait===true){o.wait(b.waitConfig)}return this},setIcon:function(y){if(!v){i=y;return}i=undefined;if(y&&y!=""){k.removeClass("x-hidden");k.replaceClass(d,y);h.addClass("x-dlg-icon");d=y}else{k.replaceClass(d,"x-hidden");h.removeClass("x-dlg-icon");d=""}return this},progress:function(A,z,y){this.show({title:A,msg:z,buttons:false,progress:true,closable:false,minWidth:this.minProgressWidth,progressText:y});return this},wait:function(A,z,y){this.show({title:z,msg:A,buttons:false,closable:false,wait:true,modal:true,minWidth:this.minProgressWidth,waitConfig:y});return this},alert:function(B,A,z,y){this.show({title:B,msg:A,buttons:this.OK,fn:z,scope:y,minWidth:this.minWidth});return this},confirm:function(B,A,z,y){this.show({title:B,msg:A,buttons:this.YESNO,fn:z,scope:y,icon:this.QUESTION,minWidth:this.minWidth});return this},prompt:function(D,C,A,z,y,B){this.show({title:D,msg:C,buttons:this.OKCANCEL,fn:A,minWidth:this.minPromptWidth,scope:z,prompt:true,multiline:y,value:B});return this},OK:{ok:true},CANCEL:{cancel:true},OKCANCEL:{ok:true,cancel:true},YESNO:{yes:true,no:true},YESNOCANCEL:{yes:true,no:true,cancel:true},INFO:"ext-mb-info",WARNING:"ext-mb-warning",QUESTION:"ext-mb-question",ERROR:"ext-mb-error",defaultTextHeight:75,maxWidth:600,minWidth:100,minProgressWidth:250,minPromptWidth:250,buttonText:{ok:"OK",cancel:"Cancel",yes:"Yes",no:"No"}}}();Ext.Msg=Ext.MessageBox;Ext.dd.PanelProxy=Ext.extend(Object,{constructor:function(a,b){this.panel=a;this.id=this.panel.id+"-ddproxy";Ext.apply(this,b)},insertProxy:true,setStatus:Ext.emptyFn,reset:Ext.emptyFn,update:Ext.emptyFn,stop:Ext.emptyFn,sync:Ext.emptyFn,getEl:function(){return this.ghost},getGhost:function(){return this.ghost},getProxy:function(){return this.proxy},hide:function(){if(this.ghost){if(this.proxy){this.proxy.remove();delete this.proxy}this.panel.el.dom.style.display="";this.ghost.remove();delete this.ghost}},show:function(){if(!this.ghost){this.ghost=this.panel.createGhost(this.panel.initialConfig.cls,undefined,Ext.getBody());this.ghost.setXY(this.panel.el.getXY());if(this.insertProxy){this.proxy=this.panel.el.insertSibling({cls:"x-panel-dd-spacer"});this.proxy.setSize(this.panel.getSize())}this.panel.el.dom.style.display="none"}},repair:function(b,c,a){this.hide();if(typeof c=="function"){c.call(a||this)}},moveProxy:function(a,b){if(this.proxy){a.insertBefore(this.proxy.dom,b)}}});Ext.Panel.DD=Ext.extend(Ext.dd.DragSource,{constructor:function(b,a){this.panel=b;this.dragData={panel:b};this.proxy=new Ext.dd.PanelProxy(b,a);Ext.Panel.DD.superclass.constructor.call(this,b.el,a);var d=b.header,c=b.body;if(d){this.setHandleElId(d.id);c=b.header}c.setStyle("cursor","move");this.scroll=false},showFrame:Ext.emptyFn,startDrag:Ext.emptyFn,b4StartDrag:function(a,b){this.proxy.show()},b4MouseDown:function(b){var a=b.getPageX(),c=b.getPageY();this.autoOffset(a,c)},onInitDrag:function(a,b){this.onStartDrag(a,b);return true},createFrame:Ext.emptyFn,getDragEl:function(a){return this.proxy.ghost.dom},endDrag:function(a){this.proxy.hide();this.panel.saveState()},autoOffset:function(a,b){a-=this.startPageX;b-=this.startPageY;this.setDelta(a,b)}});Ext.state.Provider=Ext.extend(Ext.util.Observable,{constructor:function(){this.addEvents("statechange");this.state={};Ext.state.Provider.superclass.constructor.call(this)},get:function(b,a){return typeof this.state[b]=="undefined"?a:this.state[b]},clear:function(a){delete this.state[a];this.fireEvent("statechange",this,a,null)},set:function(a,b){this.state[a]=b;this.fireEvent("statechange",this,a,b)},decodeValue:function(b){var e=/^(a|n|d|b|s|o|e)\:(.*)$/,h=e.exec(unescape(b)),d,c,a,g;if(!h||!h[1]){return}c=h[1];a=h[2];switch(c){case"e":return null;case"n":return parseFloat(a);case"d":return new Date(Date.parse(a));case"b":return(a=="1");case"a":d=[];if(a!=""){Ext.each(a.split("^"),function(i){d.push(this.decodeValue(i))},this)}return d;case"o":d={};if(a!=""){Ext.each(a.split("^"),function(i){g=i.split("=");d[g[0]]=this.decodeValue(g[1])},this)}return d;default:return a}},encodeValue:function(c){var b,g="",e=0,a,d;if(c==null){return"e:1"}else{if(typeof c=="number"){b="n:"+c}else{if(typeof c=="boolean"){b="b:"+(c?"1":"0")}else{if(Ext.isDate(c)){b="d:"+c.toGMTString()}else{if(Ext.isArray(c)){for(a=c.length;e<a;e++){g+=this.encodeValue(c[e]);if(e!=a-1){g+="^"}}b="a:"+g}else{if(typeof c=="object"){for(d in c){if(typeof c[d]!="function"&&c[d]!==undefined){g+=d+"="+this.encodeValue(c[d])+"^"}}b="o:"+g.substring(0,g.length-1)}else{b="s:"+c}}}}}}return escape(b)}});Ext.state.Manager=function(){var a=new Ext.state.Provider();return{setProvider:function(b){a=b},get:function(c,b){return a.get(c,b)},set:function(b,c){a.set(b,c)},clear:function(b){a.clear(b)},getProvider:function(){return a}}}();Ext.state.CookieProvider=Ext.extend(Ext.state.Provider,{constructor:function(a){Ext.state.CookieProvider.superclass.constructor.call(this);this.path="/";this.expires=new Date(new Date().getTime()+(1000*60*60*24*7));this.domain=null;this.secure=false;Ext.apply(this,a);this.state=this.readCookies()},set:function(a,b){if(typeof b=="undefined"||b===null){this.clear(a);return}this.setCookie(a,b);Ext.state.CookieProvider.superclass.set.call(this,a,b)},clear:function(a){this.clearCookie(a);Ext.state.CookieProvider.superclass.clear.call(this,a)},readCookies:function(){var d={},h=document.cookie+";",b=/\s?(.*?)=(.*?);/g,g,a,e;while((g=b.exec(h))!=null){a=g[1];e=g[2];if(a&&a.substring(0,3)=="ys-"){d[a.substr(3)]=this.decodeValue(e)}}return d},setCookie:function(a,b){document.cookie="ys-"+a+"="+this.encodeValue(b)+((this.expires==null)?"":("; expires="+this.expires.toGMTString()))+((this.path==null)?"":("; path="+this.path))+((this.domain==null)?"":("; domain="+this.domain))+((this.secure==true)?"; secure":"")},clearCookie:function(a){document.cookie="ys-"+a+"=null; expires=Thu, 01-Jan-70 00:00:01 GMT"+((this.path==null)?"":("; path="+this.path))+((this.domain==null)?"":("; domain="+this.domain))+((this.secure==true)?"; secure":"")}});Ext.DataView=Ext.extend(Ext.BoxComponent,{selectedClass:"x-view-selected",emptyText:"",deferEmptyText:true,trackOver:false,blockRefresh:false,last:false,initComponent:function(){Ext.DataView.superclass.initComponent.call(this);if(Ext.isString(this.tpl)||Ext.isArray(this.tpl)){this.tpl=new Ext.XTemplate(this.tpl)}this.addEvents("beforeclick","click","mouseenter","mouseleave","containerclick","dblclick","contextmenu","containercontextmenu","selectionchange","beforeselect");this.store=Ext.StoreMgr.lookup(this.store);this.all=new Ext.CompositeElementLite();this.selected=new Ext.CompositeElementLite()},afterRender:function(){Ext.DataView.superclass.afterRender.call(this);this.mon(this.getTemplateTarget(),{click:this.onClick,dblclick:this.onDblClick,contextmenu:this.onContextMenu,scope:this});if(this.overClass||this.trackOver){this.mon(this.getTemplateTarget(),{mouseover:this.onMouseOver,mouseout:this.onMouseOut,scope:this})}if(this.store){this.bindStore(this.store,true)}},refresh:function(){this.clearSelections(false,true);var b=this.getTemplateTarget(),a=this.store.getRange();b.update("");if(a.length<1){if(!this.deferEmptyText||this.hasSkippedEmptyText){b.update(this.emptyText)}this.all.clear()}else{this.tpl.overwrite(b,this.collectData(a,0));this.all.fill(Ext.query(this.itemSelector,b.dom));this.updateIndexes(0)}this.hasSkippedEmptyText=true},getTemplateTarget:function(){return this.el},prepareData:function(a){return a},collectData:function(b,e){var d=[],c=0,a=b.length;for(;c<a;c++){d[d.length]=this.prepareData(b[c].data,e+c,b[c])}return d},bufferRender:function(a,b){var c=document.createElement("div");this.tpl.overwrite(c,this.collectData(a,b));return Ext.query(this.itemSelector,c)},onUpdate:function(g,a){var b=this.store.indexOf(a);if(b>-1){var e=this.isSelected(b),c=this.all.elements[b],d=this.bufferRender([a],b)[0];this.all.replaceElement(b,d,true);if(e){this.selected.replaceElement(c,d);this.all.item(b).addClass(this.selectedClass)}this.updateIndexes(b,b)}},onAdd:function(g,d,e){if(this.all.getCount()===0){this.refresh();return}var c=this.bufferRender(d,e),h,b=this.all.elements;if(e<this.all.getCount()){h=this.all.item(e).insertSibling(c,"before",true);b.splice.apply(b,[e,0].concat(c))}else{h=this.all.last().insertSibling(c,"after",true);b.push.apply(b,c)}this.updateIndexes(e)},onRemove:function(c,a,b){this.deselect(b);this.all.removeElement(b,true);this.updateIndexes(b);if(this.store.getCount()===0){this.refresh()}},refreshNode:function(a){this.onUpdate(this.store,this.store.getAt(a))},updateIndexes:function(d,c){var b=this.all.elements;d=d||0;c=c||((c===0)?0:(b.length-1));for(var a=d;a<=c;a++){b[a].viewIndex=a}},getStore:function(){return this.store},bindStore:function(a,b){if(!b&&this.store){if(a!==this.store&&this.store.autoDestroy){this.store.destroy()}else{this.store.un("beforeload",this.onBeforeLoad,this);this.store.un("datachanged",this.onDataChanged,this);this.store.un("add",this.onAdd,this);this.store.un("remove",this.onRemove,this);this.store.un("update",this.onUpdate,this);this.store.un("clear",this.refresh,this)}if(!a){this.store=null}}if(a){a=Ext.StoreMgr.lookup(a);a.on({scope:this,beforeload:this.onBeforeLoad,datachanged:this.onDataChanged,add:this.onAdd,remove:this.onRemove,update:this.onUpdate,clear:this.refresh})}this.store=a;if(a){this.refresh()}},onDataChanged:function(){if(this.blockRefresh!==true){this.refresh.apply(this,arguments)}},findItemFromChild:function(a){return Ext.fly(a).findParent(this.itemSelector,this.getTemplateTarget())},onClick:function(c){var b=c.getTarget(this.itemSelector,this.getTemplateTarget()),a;if(b){a=this.indexOf(b);if(this.onItemClick(b,a,c)!==false){this.fireEvent("click",this,a,b,c)}}else{if(this.fireEvent("containerclick",this,c)!==false){this.onContainerClick(c)}}},onContainerClick:function(a){this.clearSelections()},onContextMenu:function(b){var a=b.getTarget(this.itemSelector,this.getTemplateTarget());if(a){this.fireEvent("contextmenu",this,this.indexOf(a),a,b)}else{this.fireEvent("containercontextmenu",this,b)}},onDblClick:function(b){var a=b.getTarget(this.itemSelector,this.getTemplateTarget());if(a){this.fireEvent("dblclick",this,this.indexOf(a),a,b)}},onMouseOver:function(b){var a=b.getTarget(this.itemSelector,this.getTemplateTarget());if(a&&a!==this.lastItem){this.lastItem=a;Ext.fly(a).addClass(this.overClass);this.fireEvent("mouseenter",this,this.indexOf(a),a,b)}},onMouseOut:function(a){if(this.lastItem){if(!a.within(this.lastItem,true,true)){Ext.fly(this.lastItem).removeClass(this.overClass);this.fireEvent("mouseleave",this,this.indexOf(this.lastItem),this.lastItem,a);delete this.lastItem}}},onItemClick:function(b,a,c){if(this.fireEvent("beforeclick",this,a,b,c)===false){return false}if(this.multiSelect){this.doMultiSelection(b,a,c);c.preventDefault()}else{if(this.singleSelect){this.doSingleSelection(b,a,c);c.preventDefault()}}return true},doSingleSelection:function(b,a,c){if(c.ctrlKey&&this.isSelected(a)){this.deselect(a)}else{this.select(a,false)}},doMultiSelection:function(c,a,d){if(d.shiftKey&&this.last!==false){var b=this.last;this.selectRange(b,a,d.ctrlKey);this.last=b}else{if((d.ctrlKey||this.simpleSelect)&&this.isSelected(a)){this.deselect(a)}else{this.select(a,d.ctrlKey||d.shiftKey||this.simpleSelect)}}},getSelectionCount:function(){return this.selected.getCount()},getSelectedNodes:function(){return this.selected.elements},getSelectedIndexes:function(){var b=[],d=this.selected.elements,c=0,a=d.length;for(;c<a;c++){b.push(d[c].viewIndex)}return b},getSelectedRecords:function(){return this.getRecords(this.selected.elements)},getRecords:function(c){var b=[],d=0,a=c.length;for(;d<a;d++){b[b.length]=this.store.getAt(c[d].viewIndex)}return b},getRecord:function(a){return this.store.getAt(a.viewIndex)},clearSelections:function(a,b){if((this.multiSelect||this.singleSelect)&&this.selected.getCount()>0){if(!b){this.selected.removeClass(this.selectedClass)}this.selected.clear();this.last=false;if(!a){this.fireEvent("selectionchange",this,this.selected.elements)}}},isSelected:function(a){return this.selected.contains(this.getNode(a))},deselect:function(a){if(this.isSelected(a)){a=this.getNode(a);this.selected.removeElement(a);if(this.last==a.viewIndex){this.last=false}Ext.fly(a).removeClass(this.selectedClass);this.fireEvent("selectionchange",this,this.selected.elements)}},select:function(d,g,b){if(Ext.isArray(d)){if(!g){this.clearSelections(true)}for(var c=0,a=d.length;c<a;c++){this.select(d[c],true,true)}if(!b){this.fireEvent("selectionchange",this,this.selected.elements)}}else{var e=this.getNode(d);if(!g){this.clearSelections(true)}if(e&&!this.isSelected(e)){if(this.fireEvent("beforeselect",this,e,this.selected.elements)!==false){Ext.fly(e).addClass(this.selectedClass);this.selected.add(e);this.last=e.viewIndex;if(!b){this.fireEvent("selectionchange",this,this.selected.elements)}}}}},selectRange:function(c,a,b){if(!b){this.clearSelections(true)}this.select(this.getNodes(c,a),true)},getNode:function(b){if(Ext.isString(b)){return document.getElementById(b)}else{if(Ext.isNumber(b)){return this.all.elements[b]}else{if(b instanceof Ext.data.Record){var a=this.store.indexOf(b);return this.all.elements[a]}}}return b},getNodes:function(e,a){var d=this.all.elements,b=[],c;e=e||0;a=!Ext.isDefined(a)?Math.max(d.length-1,0):a;if(e<=a){for(c=e;c<=a&&d[c];c++){b.push(d[c])}}else{for(c=e;c>=a&&d[c];c--){b.push(d[c])}}return b},indexOf:function(a){a=this.getNode(a);if(Ext.isNumber(a.viewIndex)){return a.viewIndex}return this.all.indexOf(a)},onBeforeLoad:function(){if(this.loadingText){this.clearSelections(false,true);this.getTemplateTarget().update('<div class="loading-indicator">'+this.loadingText+"</div>");this.all.clear()}},onDestroy:function(){this.all.clear();this.selected.clear();Ext.DataView.superclass.onDestroy.call(this);this.bindStore(null)}});Ext.DataView.prototype.setStore=Ext.DataView.prototype.bindStore;Ext.reg("dataview",Ext.DataView);Ext.list.ListView=Ext.extend(Ext.DataView,{itemSelector:"dl",selectedClass:"x-list-selected",overClass:"x-list-over",scrollOffset:undefined,columnResize:true,columnSort:true,maxColumnWidth:Ext.isIE?99:100,initComponent:function(){if(this.columnResize){this.colResizer=new Ext.list.ColumnResizer(this.colResizer);this.colResizer.init(this)}if(this.columnSort){this.colSorter=new Ext.list.Sorter(this.columnSort);this.colSorter.init(this)}if(!this.internalTpl){this.internalTpl=new Ext.XTemplate('<div class="x-list-header"><div class="x-list-header-inner">','<tpl for="columns">','<div style="width:{[values.width*100]}%;text-align:{align};"><em unselectable="on" id="',this.id,'-xlhd-{#}">',"{header}","</em></div>","</tpl>",'<div class="x-clear"></div>',"</div></div>",'<div class="x-list-body"><div class="x-list-body-inner">',"</div></div>")}if(!this.tpl){this.tpl=new Ext.XTemplate('<tpl for="rows">',"<dl>",'<tpl for="parent.columns">','<dt style="width:{[values.width*100]}%;text-align:{align};">','<em unselectable="on"<tpl if="cls"> class="{cls}</tpl>">',"{[values.tpl.apply(parent)]}","</em></dt>","</tpl>",'<div class="x-clear"></div>',"</dl>","</tpl>")}var l=this.columns,h=0,k=0,m=l.length,b=[];for(var g=0;g<m;g++){var n=l[g];if(!n.isColumn){n.xtype=n.xtype?(/^lv/.test(n.xtype)?n.xtype:"lv"+n.xtype):"lvcolumn";n=Ext.create(n)}if(n.width){h+=n.width*100;if(h>this.maxColumnWidth){n.width-=(h-this.maxColumnWidth)/100}k++}b.push(n)}l=this.columns=b;if(k<m){var d=m-k;if(h<this.maxColumnWidth){var a=((this.maxColumnWidth-h)/d)/100;for(var e=0;e<m;e++){var n=l[e];if(!n.width){n.width=a}}}}Ext.list.ListView.superclass.initComponent.call(this)},onRender:function(){this.autoEl={cls:"x-list-wrap"};Ext.list.ListView.superclass.onRender.apply(this,arguments);this.internalTpl.overwrite(this.el,{columns:this.columns});this.innerBody=Ext.get(this.el.dom.childNodes[1].firstChild);this.innerHd=Ext.get(this.el.dom.firstChild.firstChild);if(this.hideHeaders){this.el.dom.firstChild.style.display="none"}},getTemplateTarget:function(){return this.innerBody},collectData:function(){var a=Ext.list.ListView.superclass.collectData.apply(this,arguments);return{columns:this.columns,rows:a}},verifyInternalSize:function(){if(this.lastSize){this.onResize(this.lastSize.width,this.lastSize.height)}},onResize:function(c,e){var b=this.innerBody.dom,g=this.innerHd.dom,d=c-Ext.num(this.scrollOffset,Ext.getScrollBarWidth())+"px",a;if(!b){return}a=b.parentNode;if(Ext.isNumber(c)){if(this.reserveScrollOffset||((a.offsetWidth-a.clientWidth)>10)){b.style.width=d;g.style.width=d}else{b.style.width=c+"px";g.style.width=c+"px";setTimeout(function(){if((a.offsetWidth-a.clientWidth)>10){b.style.width=d;g.style.width=d}},10)}}if(Ext.isNumber(e)){a.style.height=Math.max(0,e-g.parentNode.offsetHeight)+"px"}},updateIndexes:function(){Ext.list.ListView.superclass.updateIndexes.apply(this,arguments);this.verifyInternalSize()},findHeaderIndex:function(g){g=g.dom||g;var a=g.parentNode,d=a.parentNode.childNodes,b=0,e;for(;e=d[b];b++){if(e==a){return b}}return -1},setHdWidths:function(){var d=this.innerHd.dom.getElementsByTagName("div"),c=0,b=this.columns,a=b.length;for(;c<a;c++){d[c].style.width=(b[c].width*100)+"%"}}});Ext.reg("listview",Ext.list.ListView);Ext.ListView=Ext.list.ListView;Ext.list.Column=Ext.extend(Object,{isColumn:true,align:"left",header:"",width:null,cls:"",constructor:function(a){if(!a.tpl){a.tpl=new Ext.XTemplate("{"+a.dataIndex+"}")}else{if(Ext.isString(a.tpl)){a.tpl=new Ext.XTemplate(a.tpl)}}Ext.apply(this,a)}});Ext.reg("lvcolumn",Ext.list.Column);Ext.list.NumberColumn=Ext.extend(Ext.list.Column,{format:"0,000.00",constructor:function(a){a.tpl=a.tpl||new Ext.XTemplate("{"+a.dataIndex+':number("'+(a.format||this.format)+'")}');Ext.list.NumberColumn.superclass.constructor.call(this,a)}});Ext.reg("lvnumbercolumn",Ext.list.NumberColumn);Ext.list.DateColumn=Ext.extend(Ext.list.Column,{format:"m/d/Y",constructor:function(a){a.tpl=a.tpl||new Ext.XTemplate("{"+a.dataIndex+':date("'+(a.format||this.format)+'")}');Ext.list.DateColumn.superclass.constructor.call(this,a)}});Ext.reg("lvdatecolumn",Ext.list.DateColumn);Ext.list.BooleanColumn=Ext.extend(Ext.list.Column,{trueText:"true",falseText:"false",undefinedText:" ",constructor:function(e){e.tpl=e.tpl||new Ext.XTemplate("{"+e.dataIndex+":this.format}");var b=this.trueText,d=this.falseText,a=this.undefinedText;e.tpl.format=function(c){if(c===undefined){return a}if(!c||c==="false"){return d}return b};Ext.list.DateColumn.superclass.constructor.call(this,e)}});Ext.reg("lvbooleancolumn",Ext.list.BooleanColumn);Ext.list.ColumnResizer=Ext.extend(Ext.util.Observable,{minPct:0.05,constructor:function(a){Ext.apply(this,a);Ext.list.ColumnResizer.superclass.constructor.call(this)},init:function(a){this.view=a;a.on("render",this.initEvents,this)},initEvents:function(a){a.mon(a.innerHd,"mousemove",this.handleHdMove,this);this.tracker=new Ext.dd.DragTracker({onBeforeStart:this.onBeforeStart.createDelegate(this),onStart:this.onStart.createDelegate(this),onDrag:this.onDrag.createDelegate(this),onEnd:this.onEnd.createDelegate(this),tolerance:3,autoStart:300});this.tracker.initEl(a.innerHd);a.on("beforedestroy",this.tracker.destroy,this.tracker)},handleHdMove:function(i,d){var c=5,b=i.getPageX(),k=i.getTarget("em",3,true);if(k){var h=k.getRegion(),g=k.dom.style,a=k.dom.parentNode;if(b-h.left<=c&&a!=a.parentNode.firstChild){this.activeHd=Ext.get(a.previousSibling.firstChild);g.cursor=Ext.isWebKit?"e-resize":"col-resize"}else{if(h.right-b<=c&&a!=a.parentNode.lastChild.previousSibling){this.activeHd=k;g.cursor=Ext.isWebKit?"w-resize":"col-resize"}else{delete this.activeHd;g.cursor=""}}}},onBeforeStart:function(a){this.dragHd=this.activeHd;return !!this.dragHd},onStart:function(g){var d=this,b=d.view,c=d.dragHd,a=d.tracker.getXY()[0];d.proxy=b.el.createChild({cls:"x-list-resizer"});d.dragX=c.getX();d.headerIndex=b.findHeaderIndex(c);d.headersDisabled=b.disableHeaders;b.disableHeaders=true;d.proxy.setHeight(b.el.getHeight());d.proxy.setX(d.dragX);d.proxy.setWidth(a-d.dragX);this.setBoundaries()},setBoundaries:function(k){var l=this.view,h=this.headerIndex,c=l.innerHd.getWidth(),k=l.innerHd.getX(),b=Math.ceil(c*this.minPct),m=c-b,e=l.columns.length,d=l.innerHd.select("em",true),g=b+k,a=m+k,i;if(e==2){this.minX=g;this.maxX=a}else{i=d.item(h+2);this.minX=d.item(h).getX()+b;this.maxX=i?i.getX()-b:a;if(h==0){this.minX=g}else{if(h==e-2){this.maxX=a}}}},onDrag:function(c){var b=this,a=b.tracker.getXY()[0].constrain(b.minX,b.maxX);b.proxy.setWidth(a-this.dragX)},onEnd:function(i){var g=this.proxy.getWidth(),h=this.headerIndex,m=this.view,c=m.columns,b=m.innerHd.getWidth(),l=Math.ceil(g*m.maxColumnWidth/b)/100,d=this.headersDisabled,n=c[h],k=c[h+1],a=n.width+k.width;this.proxy.remove();n.width=l;k.width=a-l;delete this.dragHd;m.setHdWidths();m.refresh();setTimeout(function(){m.disableHeaders=d},100)}});Ext.ListView.ColumnResizer=Ext.list.ColumnResizer;Ext.list.Sorter=Ext.extend(Ext.util.Observable,{sortClasses:["sort-asc","sort-desc"],constructor:function(a){Ext.apply(this,a);Ext.list.Sorter.superclass.constructor.call(this)},init:function(a){this.view=a;a.on("render",this.initEvents,this)},initEvents:function(a){a.mon(a.innerHd,"click",this.onHdClick,this);a.innerHd.setStyle("cursor","pointer");a.mon(a.store,"datachanged",this.updateSortState,this);this.updateSortState.defer(10,this,[a.store])},updateSortState:function(c){var g=c.getSortState();if(!g){return}this.sortState=g;var e=this.view.columns,h=-1;for(var d=0,a=e.length;d<a;d++){if(e[d].dataIndex==g.field){h=d;break}}if(h!=-1){var b=g.direction;this.updateSortIcon(h,b)}},updateSortIcon:function(b,a){var d=this.sortClasses;var c=this.view.innerHd.select("em").removeClass(d);c.item(b).addClass(d[a=="DESC"?1:0])},onHdClick:function(c){var b=c.getTarget("em",3);if(b&&!this.view.disableHeaders){var a=this.view.findHeaderIndex(b);this.view.store.sort(this.view.columns[a].dataIndex)}}});Ext.ListView.Sorter=Ext.list.Sorter;Ext.TabPanel=Ext.extend(Ext.Panel,{deferredRender:true,tabWidth:120,minTabWidth:30,resizeTabs:false,enableTabScroll:false,scrollIncrement:0,scrollRepeatInterval:400,scrollDuration:0.35,animScroll:true,tabPosition:"top",baseCls:"x-tab-panel",autoTabs:false,autoTabSelector:"div.x-tab",activeTab:undefined,tabMargin:2,plain:false,wheelIncrement:20,idDelimiter:"__",itemCls:"x-tab-item",elements:"body",headerAsText:false,frame:false,hideBorders:true,initComponent:function(){this.frame=false;Ext.TabPanel.superclass.initComponent.call(this);this.addEvents("beforetabchange","tabchange","contextmenu");this.setLayout(new Ext.layout.CardLayout(Ext.apply({layoutOnCardChange:this.layoutOnTabChange,deferredRender:this.deferredRender},this.layoutConfig)));if(this.tabPosition=="top"){this.elements+=",header";this.stripTarget="header"}else{this.elements+=",footer";this.stripTarget="footer"}if(!this.stack){this.stack=Ext.TabPanel.AccessStack()}this.initItems()},onRender:function(c,a){Ext.TabPanel.superclass.onRender.call(this,c,a);if(this.plain){var g=this.tabPosition=="top"?"header":"footer";this[g].addClass("x-tab-panel-"+g+"-plain")}var b=this[this.stripTarget];this.stripWrap=b.createChild({cls:"x-tab-strip-wrap",cn:{tag:"ul",cls:"x-tab-strip x-tab-strip-"+this.tabPosition}});var e=(this.tabPosition=="bottom"?this.stripWrap:null);b.createChild({cls:"x-tab-strip-spacer"},e);this.strip=new Ext.Element(this.stripWrap.dom.firstChild);this.edge=this.strip.createChild({tag:"li",cls:"x-tab-edge",cn:[{tag:"span",cls:"x-tab-strip-text",cn:" "}]});this.strip.createChild({cls:"x-clear"});this.body.addClass("x-tab-panel-body-"+this.tabPosition);if(!this.itemTpl){var d=new Ext.Template('<li class="{cls}" id="{id}"><a class="x-tab-strip-close"></a>','<a class="x-tab-right" href="#"><em class="x-tab-left">','<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>',"</em></a></li>");d.disableFormats=true;d.compile();Ext.TabPanel.prototype.itemTpl=d}this.items.each(this.initTab,this)},afterRender:function(){Ext.TabPanel.superclass.afterRender.call(this);if(this.autoTabs){this.readTabs(false)}if(this.activeTab!==undefined){var a=Ext.isObject(this.activeTab)?this.activeTab:this.items.get(this.activeTab);delete this.activeTab;this.setActiveTab(a)}},initEvents:function(){Ext.TabPanel.superclass.initEvents.call(this);this.mon(this.strip,{scope:this,mousedown:this.onStripMouseDown,contextmenu:this.onStripContextMenu});if(this.enableTabScroll){this.mon(this.strip,"mousewheel",this.onWheel,this)}},findTargets:function(c){var b=null,a=c.getTarget("li:not(.x-tab-edge)",this.strip);if(a){b=this.getComponent(a.id.split(this.idDelimiter)[1]);if(b.disabled){return{close:null,item:null,el:null}}}return{close:c.getTarget(".x-tab-strip-close",this.strip),item:b,el:a}},onStripMouseDown:function(b){if(b.button!==0){return}b.preventDefault();var a=this.findTargets(b);if(a.close){if(a.item.fireEvent("beforeclose",a.item)!==false){a.item.fireEvent("close",a.item);this.remove(a.item)}return}if(a.item&&a.item!=this.activeTab){this.setActiveTab(a.item)}},onStripContextMenu:function(b){b.preventDefault();var a=this.findTargets(b);if(a.item){this.fireEvent("contextmenu",this,a.item,b)}},readTabs:function(d){if(d===true){this.items.each(function(h){this.remove(h)},this)}var c=this.el.query(this.autoTabSelector);for(var b=0,a=c.length;b<a;b++){var e=c[b],g=e.getAttribute("title");e.removeAttribute("title");this.add({title:g,contentEl:e})}},initTab:function(d,b){var e=this.strip.dom.childNodes[b],g=this.getTemplateArgs(d),c=e?this.itemTpl.insertBefore(e,g):this.itemTpl.append(this.strip,g),a="x-tab-strip-over",h=Ext.get(c);h.hover(function(){if(!d.disabled){h.addClass(a)}},function(){h.removeClass(a)});if(d.tabTip){h.child("span.x-tab-strip-text",true).qtip=d.tabTip}d.tabEl=c;h.select("a").on("click",function(i){if(!i.getPageX()){this.onStripMouseDown(i)}},this,{preventDefault:true});d.on({scope:this,disable:this.onItemDisabled,enable:this.onItemEnabled,titlechange:this.onItemTitleChanged,iconchange:this.onItemIconChanged,beforeshow:this.onBeforeShowItem})},getTemplateArgs:function(b){var a=b.closable?"x-tab-strip-closable":"";if(b.disabled){a+=" x-item-disabled"}if(b.iconCls){a+=" x-tab-with-icon"}if(b.tabCls){a+=" "+b.tabCls}return{id:this.id+this.idDelimiter+b.getItemId(),text:b.title,cls:a,iconCls:b.iconCls||""}},onAdd:function(b){Ext.TabPanel.superclass.onAdd.call(this,b);if(this.rendered){var a=this.items;this.initTab(b,a.indexOf(b));this.delegateUpdates()}},onBeforeAdd:function(b){var a=b.events?(this.items.containsKey(b.getItemId())?b:null):this.items.get(b);if(a){this.setActiveTab(b);return false}Ext.TabPanel.superclass.onBeforeAdd.apply(this,arguments);var c=b.elements;b.elements=c?c.replace(",header",""):c;b.border=(b.border===true)},onRemove:function(d){var b=Ext.get(d.tabEl);if(b){b.select("a").removeAllListeners();Ext.destroy(b)}Ext.TabPanel.superclass.onRemove.call(this,d);this.stack.remove(d);delete d.tabEl;d.un("disable",this.onItemDisabled,this);d.un("enable",this.onItemEnabled,this);d.un("titlechange",this.onItemTitleChanged,this);d.un("iconchange",this.onItemIconChanged,this);d.un("beforeshow",this.onBeforeShowItem,this);if(d==this.activeTab){var a=this.stack.next();if(a){this.setActiveTab(a)}else{if(this.items.getCount()>0){this.setActiveTab(0)}else{this.setActiveTab(null)}}}if(!this.destroying){this.delegateUpdates()}},onBeforeShowItem:function(a){if(a!=this.activeTab){this.setActiveTab(a);return false}},onItemDisabled:function(b){var a=this.getTabEl(b);if(a){Ext.fly(a).addClass("x-item-disabled")}this.stack.remove(b)},onItemEnabled:function(b){var a=this.getTabEl(b);if(a){Ext.fly(a).removeClass("x-item-disabled")}},onItemTitleChanged:function(b){var a=this.getTabEl(b);if(a){Ext.fly(a).child("span.x-tab-strip-text",true).innerHTML=b.title}},onItemIconChanged:function(d,a,c){var b=this.getTabEl(d);if(b){b=Ext.get(b);b.child("span.x-tab-strip-text").replaceClass(c,a);b[Ext.isEmpty(a)?"removeClass":"addClass"]("x-tab-with-icon")}},getTabEl:function(a){var b=this.getComponent(a);return b?b.tabEl:null},onResize:function(){Ext.TabPanel.superclass.onResize.apply(this,arguments);this.delegateUpdates()},beginUpdate:function(){this.suspendUpdates=true},endUpdate:function(){this.suspendUpdates=false;this.delegateUpdates()},hideTabStripItem:function(b){b=this.getComponent(b);var a=this.getTabEl(b);if(a){a.style.display="none";this.delegateUpdates()}this.stack.remove(b)},unhideTabStripItem:function(b){b=this.getComponent(b);var a=this.getTabEl(b);if(a){a.style.display="";this.delegateUpdates()}},delegateUpdates:function(){var a=this.rendered;if(this.suspendUpdates){return}if(this.resizeTabs&&a){this.autoSizeTabs()}if(this.enableTabScroll&&a){this.autoScrollTabs()}},autoSizeTabs:function(){var h=this.items.length,b=this.tabPosition!="bottom"?"header":"footer",c=this[b].dom.offsetWidth,a=this[b].dom.clientWidth;if(!this.resizeTabs||h<1||!a){return}var l=Math.max(Math.min(Math.floor((a-4)/h)-this.tabMargin,this.tabWidth),this.minTabWidth);this.lastTabWidth=l;var n=this.strip.query("li:not(.x-tab-edge)");for(var e=0,k=n.length;e<k;e++){var m=n[e],o=Ext.fly(m).child(".x-tab-strip-inner",true),g=m.offsetWidth,d=o.offsetWidth;o.style.width=(l-(g-d))+"px"}},adjustBodyWidth:function(a){if(this.header){this.header.setWidth(a)}if(this.footer){this.footer.setWidth(a)}return a},setActiveTab:function(c){c=this.getComponent(c);if(this.fireEvent("beforetabchange",this,c,this.activeTab)===false){return}if(!this.rendered){this.activeTab=c;return}if(this.activeTab!=c){if(this.activeTab){var a=this.getTabEl(this.activeTab);if(a){Ext.fly(a).removeClass("x-tab-strip-active")}}this.activeTab=c;if(c){var b=this.getTabEl(c);Ext.fly(b).addClass("x-tab-strip-active");this.stack.add(c);this.layout.setActiveItem(c);this.delegateUpdates();if(this.scrolling){this.scrollToTab(c,this.animScroll)}}this.fireEvent("tabchange",this,c)}},getActiveTab:function(){return this.activeTab||null},getItem:function(a){return this.getComponent(a)},autoScrollTabs:function(){this.pos=this.tabPosition=="bottom"?this.footer:this.header;var h=this.items.length,d=this.pos.dom.offsetWidth,c=this.pos.dom.clientWidth,g=this.stripWrap,e=g.dom,b=e.offsetWidth,i=this.getScrollPos(),a=this.edge.getOffsetsTo(this.stripWrap)[0]+i;if(!this.enableTabScroll||b<20){return}if(h==0||a<=c){e.scrollLeft=0;g.setWidth(c);if(this.scrolling){this.scrolling=false;this.pos.removeClass("x-tab-scrolling");this.scrollLeft.hide();this.scrollRight.hide();if(Ext.isAir||Ext.isWebKit){e.style.marginLeft="";e.style.marginRight=""}}}else{if(!this.scrolling){this.pos.addClass("x-tab-scrolling");if(Ext.isAir||Ext.isWebKit){e.style.marginLeft="18px";e.style.marginRight="18px"}}c-=g.getMargins("lr");g.setWidth(c>20?c:20);if(!this.scrolling){if(!this.scrollLeft){this.createScrollers()}else{this.scrollLeft.show();this.scrollRight.show()}}this.scrolling=true;if(i>(a-c)){e.scrollLeft=a-c}else{this.scrollToTab(this.activeTab,false)}this.updateScrollButtons()}},createScrollers:function(){this.pos.addClass("x-tab-scrolling-"+this.tabPosition);var c=this.stripWrap.dom.offsetHeight;var a=this.pos.insertFirst({cls:"x-tab-scroller-left"});a.setHeight(c);a.addClassOnOver("x-tab-scroller-left-over");this.leftRepeater=new Ext.util.ClickRepeater(a,{interval:this.scrollRepeatInterval,handler:this.onScrollLeft,scope:this});this.scrollLeft=a;var b=this.pos.insertFirst({cls:"x-tab-scroller-right"});b.setHeight(c);b.addClassOnOver("x-tab-scroller-right-over");this.rightRepeater=new Ext.util.ClickRepeater(b,{interval:this.scrollRepeatInterval,handler:this.onScrollRight,scope:this});this.scrollRight=b},getScrollWidth:function(){return this.edge.getOffsetsTo(this.stripWrap)[0]+this.getScrollPos()},getScrollPos:function(){return parseInt(this.stripWrap.dom.scrollLeft,10)||0},getScrollArea:function(){return parseInt(this.stripWrap.dom.clientWidth,10)||0},getScrollAnim:function(){return{duration:this.scrollDuration,callback:this.updateScrollButtons,scope:this}},getScrollIncrement:function(){return this.scrollIncrement||(this.resizeTabs?this.lastTabWidth+2:100)},scrollToTab:function(e,a){if(!e){return}var c=this.getTabEl(e),h=this.getScrollPos(),d=this.getScrollArea(),g=Ext.fly(c).getOffsetsTo(this.stripWrap)[0]+h,b=g+c.offsetWidth;if(g<h){this.scrollTo(g,a)}else{if(b>(h+d)){this.scrollTo(b-d,a)}}},scrollTo:function(b,a){this.stripWrap.scrollTo("left",b,a?this.getScrollAnim():false);if(!a){this.updateScrollButtons()}},onWheel:function(g){var h=g.getWheelDelta()*this.wheelIncrement*-1;g.stopEvent();var i=this.getScrollPos(),c=i+h,a=this.getScrollWidth()-this.getScrollArea();var b=Math.max(0,Math.min(a,c));if(b!=i){this.scrollTo(b,false)}},onScrollRight:function(){var a=this.getScrollWidth()-this.getScrollArea(),c=this.getScrollPos(),b=Math.min(a,c+this.getScrollIncrement());if(b!=c){this.scrollTo(b,this.animScroll)}},onScrollLeft:function(){var b=this.getScrollPos(),a=Math.max(0,b-this.getScrollIncrement());if(a!=b){this.scrollTo(a,this.animScroll)}},updateScrollButtons:function(){var a=this.getScrollPos();this.scrollLeft[a===0?"addClass":"removeClass"]("x-tab-scroller-left-disabled");this.scrollRight[a>=(this.getScrollWidth()-this.getScrollArea())?"addClass":"removeClass"]("x-tab-scroller-right-disabled")},beforeDestroy:function(){Ext.destroy(this.leftRepeater,this.rightRepeater);this.deleteMembers("strip","edge","scrollLeft","scrollRight","stripWrap");this.activeTab=null;Ext.TabPanel.superclass.beforeDestroy.apply(this)}});Ext.reg("tabpanel",Ext.TabPanel);Ext.TabPanel.prototype.activate=Ext.TabPanel.prototype.setActiveTab;Ext.TabPanel.AccessStack=function(){var a=[];return{add:function(b){a.push(b);if(a.length>10){a.shift()}},remove:function(e){var d=[];for(var c=0,b=a.length;c<b;c++){if(a[c]!=e){d.push(a[c])}}a=d},next:function(){return a.pop()}}};Ext.Button=Ext.extend(Ext.BoxComponent,{hidden:false,disabled:false,pressed:false,enableToggle:false,menuAlign:"tl-bl?",type:"button",menuClassTarget:"tr:nth(2)",clickEvent:"click",handleMouseEvents:true,tooltipType:"qtip",buttonSelector:"button:first-child",scale:"small",iconAlign:"left",arrowAlign:"right",initComponent:function(){if(this.menu){this.menu=Ext.menu.MenuMgr.get(this.menu);this.menu.ownerCt=this}Ext.Button.superclass.initComponent.call(this);this.addEvents("click","toggle","mouseover","mouseout","menushow","menuhide","menutriggerover","menutriggerout");if(this.menu){this.menu.ownerCt=undefined}if(Ext.isString(this.toggleGroup)){this.enableToggle=true}},getTemplateArgs:function(){return[this.type,"x-btn-"+this.scale+" x-btn-icon-"+this.scale+"-"+this.iconAlign,this.getMenuClass(),this.cls,this.id]},setButtonClass:function(){if(this.useSetClass){if(!Ext.isEmpty(this.oldCls)){this.el.removeClass([this.oldCls,"x-btn-pressed"])}this.oldCls=(this.iconCls||this.icon)?(this.text?"x-btn-text-icon":"x-btn-icon"):"x-btn-noicon";this.el.addClass([this.oldCls,this.pressed?"x-btn-pressed":null])}},getMenuClass:function(){return this.menu?(this.arrowAlign!="bottom"?"x-btn-arrow":"x-btn-arrow-bottom"):""},onRender:function(c,a){if(!this.template){if(!Ext.Button.buttonTemplate){Ext.Button.buttonTemplate=new Ext.Template('<table id="{4}" cellspacing="0" class="x-btn {3}"><tbody class="{1}">','<tr><td class="x-btn-tl"><i> </i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i> </i></td></tr>','<tr><td class="x-btn-ml"><i> </i></td><td class="x-btn-mc"><em class="{2}" unselectable="on"><button type="{0}"></button></em></td><td class="x-btn-mr"><i> </i></td></tr>','<tr><td class="x-btn-bl"><i> </i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i> </i></td></tr>',"</tbody></table>");Ext.Button.buttonTemplate.compile()}this.template=Ext.Button.buttonTemplate}var b,d=this.getTemplateArgs();if(a){b=this.template.insertBefore(a,d,true)}else{b=this.template.append(c,d,true)}this.btnEl=b.child(this.buttonSelector);this.mon(this.btnEl,{scope:this,focus:this.onFocus,blur:this.onBlur});this.initButtonEl(b,this.btnEl);Ext.ButtonToggleMgr.register(this)},initButtonEl:function(b,c){this.el=b;this.setIcon(this.icon);this.setText(this.text);this.setIconClass(this.iconCls);if(Ext.isDefined(this.tabIndex)){c.dom.tabIndex=this.tabIndex}if(this.tooltip){this.setTooltip(this.tooltip,true)}if(this.handleMouseEvents){this.mon(b,{scope:this,mouseover:this.onMouseOver,mousedown:this.onMouseDown})}if(this.menu){this.mon(this.menu,{scope:this,show:this.onMenuShow,hide:this.onMenuHide})}if(this.repeat){var a=new Ext.util.ClickRepeater(b,Ext.isObject(this.repeat)?this.repeat:{});this.mon(a,"click",this.onRepeatClick,this)}else{this.mon(b,this.clickEvent,this.onClick,this)}},afterRender:function(){Ext.Button.superclass.afterRender.call(this);this.useSetClass=true;this.setButtonClass();this.doc=Ext.getDoc();this.doAutoWidth()},setIconClass:function(a){this.iconCls=a;if(this.el){this.btnEl.dom.className="";this.btnEl.addClass(["x-btn-text",a||""]);this.setButtonClass()}return this},setTooltip:function(b,a){if(this.rendered){if(!a){this.clearTip()}if(Ext.isObject(b)){Ext.QuickTips.register(Ext.apply({target:this.btnEl.id},b));this.tooltip=b}else{this.btnEl.dom[this.tooltipType]=b}}else{this.tooltip=b}return this},clearTip:function(){if(Ext.isObject(this.tooltip)){Ext.QuickTips.unregister(this.btnEl)}},beforeDestroy:function(){if(this.rendered){this.clearTip()}if(this.menu&&this.destroyMenu!==false){Ext.destroy(this.btnEl,this.menu)}Ext.destroy(this.repeater)},onDestroy:function(){if(this.rendered){this.doc.un("mouseover",this.monitorMouseOver,this);this.doc.un("mouseup",this.onMouseUp,this);delete this.doc;delete this.btnEl;Ext.ButtonToggleMgr.unregister(this)}Ext.Button.superclass.onDestroy.call(this)},doAutoWidth:function(){if(this.autoWidth!==false&&this.el&&this.text&&this.width===undefined){this.el.setWidth("auto");if(Ext.isIE7&&Ext.isStrict){var a=this.btnEl;if(a&&a.getWidth()>20){a.clip();a.setWidth(Ext.util.TextMetrics.measure(a,this.text).width+a.getFrameWidth("lr"))}}if(this.minWidth){if(this.el.getWidth()<this.minWidth){this.el.setWidth(this.minWidth)}}}},setHandler:function(b,a){this.handler=b;this.scope=a;return this},setText:function(a){this.text=a;if(this.el){this.btnEl.update(a||" ");this.setButtonClass()}this.doAutoWidth();return this},setIcon:function(a){this.icon=a;if(this.el){this.btnEl.setStyle("background-image",a?"url("+a+")":"");this.setButtonClass()}return this},getText:function(){return this.text},toggle:function(b,a){b=b===undefined?!this.pressed:!!b;if(b!=this.pressed){if(this.rendered){this.el[b?"addClass":"removeClass"]("x-btn-pressed")}this.pressed=b;if(!a){this.fireEvent("toggle",this,b);if(this.toggleHandler){this.toggleHandler.call(this.scope||this,this,b)}}}return this},onDisable:function(){this.onDisableChange(true)},onEnable:function(){this.onDisableChange(false)},onDisableChange:function(a){if(this.el){if(!Ext.isIE6||!this.text){this.el[a?"addClass":"removeClass"](this.disabledClass)}this.el.dom.disabled=a}this.disabled=a},showMenu:function(){if(this.rendered&&this.menu){if(this.tooltip){Ext.QuickTips.getQuickTip().cancelShow(this.btnEl)}if(this.menu.isVisible()){this.menu.hide()}this.menu.ownerCt=this;this.menu.show(this.el,this.menuAlign)}return this},hideMenu:function(){if(this.hasVisibleMenu()){this.menu.hide()}return this},hasVisibleMenu:function(){return this.menu&&this.menu.ownerCt==this&&this.menu.isVisible()},onRepeatClick:function(a,b){this.onClick(b)},onClick:function(a){if(a){a.preventDefault()}if(a.button!==0){return}if(!this.disabled){this.doToggle();if(this.menu&&!this.hasVisibleMenu()&&!this.ignoreNextClick){this.showMenu()}this.fireEvent("click",this,a);if(this.handler){this.handler.call(this.scope||this,this,a)}}},doToggle:function(){if(this.enableToggle&&(this.allowDepress!==false||!this.pressed)){this.toggle()}},isMenuTriggerOver:function(b,a){return this.menu&&!a},isMenuTriggerOut:function(b,a){return this.menu&&!a},onMouseOver:function(b){if(!this.disabled){var a=b.within(this.el,true);if(!a){this.el.addClass("x-btn-over");if(!this.monitoringMouseOver){this.doc.on("mouseover",this.monitorMouseOver,this);this.monitoringMouseOver=true}this.fireEvent("mouseover",this,b)}if(this.isMenuTriggerOver(b,a)){this.fireEvent("menutriggerover",this,this.menu,b)}}},monitorMouseOver:function(a){if(a.target!=this.el.dom&&!a.within(this.el)){if(this.monitoringMouseOver){this.doc.un("mouseover",this.monitorMouseOver,this);this.monitoringMouseOver=false}this.onMouseOut(a)}},onMouseOut:function(b){var a=b.within(this.el)&&b.target!=this.el.dom;this.el.removeClass("x-btn-over");this.fireEvent("mouseout",this,b);if(this.isMenuTriggerOut(b,a)){this.fireEvent("menutriggerout",this,this.menu,b)}},focus:function(){this.btnEl.focus()},blur:function(){this.btnEl.blur()},onFocus:function(a){if(!this.disabled){this.el.addClass("x-btn-focus")}},onBlur:function(a){this.el.removeClass("x-btn-focus")},getClickEl:function(b,a){return this.el},onMouseDown:function(a){if(!this.disabled&&a.button===0){this.getClickEl(a).addClass("x-btn-click");this.doc.on("mouseup",this.onMouseUp,this)}},onMouseUp:function(a){if(a.button===0){this.getClickEl(a,true).removeClass("x-btn-click");this.doc.un("mouseup",this.onMouseUp,this)}},onMenuShow:function(a){if(this.menu.ownerCt==this){this.menu.ownerCt=this;this.ignoreNextClick=0;this.el.addClass("x-btn-menu-active");this.fireEvent("menushow",this,this.menu)}},onMenuHide:function(a){if(this.menu.ownerCt==this){this.el.removeClass("x-btn-menu-active");this.ignoreNextClick=this.restoreClick.defer(250,this);this.fireEvent("menuhide",this,this.menu);delete this.menu.ownerCt}},restoreClick:function(){this.ignoreNextClick=0}});Ext.reg("button",Ext.Button);Ext.ButtonToggleMgr=function(){var a={};function b(e,k){if(k){var h=a[e.toggleGroup];for(var d=0,c=h.length;d<c;d++){if(h[d]!=e){h[d].toggle(false)}}}}return{register:function(c){if(!c.toggleGroup){return}var d=a[c.toggleGroup];if(!d){d=a[c.toggleGroup]=[]}d.push(c);c.on("toggle",b)},unregister:function(c){if(!c.toggleGroup){return}var d=a[c.toggleGroup];if(d){d.remove(c);c.un("toggle",b)}},getPressed:function(h){var e=a[h];if(e){for(var d=0,c=e.length;d<c;d++){if(e[d].pressed===true){return e[d]}}}return null}}}();Ext.SplitButton=Ext.extend(Ext.Button,{arrowSelector:"em",split:true,initComponent:function(){Ext.SplitButton.superclass.initComponent.call(this);this.addEvents("arrowclick")},onRender:function(){Ext.SplitButton.superclass.onRender.apply(this,arguments);if(this.arrowTooltip){this.el.child(this.arrowSelector).dom[this.tooltipType]=this.arrowTooltip}},setArrowHandler:function(b,a){this.arrowHandler=b;this.scope=a},getMenuClass:function(){return"x-btn-split"+(this.arrowAlign=="bottom"?"-bottom":"")},isClickOnArrow:function(c){if(this.arrowAlign!="bottom"){var b=this.el.child("em.x-btn-split");var a=b.getRegion().right-b.getPadding("r");return c.getPageX()>a}else{return c.getPageY()>this.btnEl.getRegion().bottom}},onClick:function(b,a){b.preventDefault();if(!this.disabled){if(this.isClickOnArrow(b)){if(this.menu&&!this.menu.isVisible()&&!this.ignoreNextClick){this.showMenu()}this.fireEvent("arrowclick",this,b);if(this.arrowHandler){this.arrowHandler.call(this.scope||this,this,b)}}else{this.doToggle();this.fireEvent("click",this,b);if(this.handler){this.handler.call(this.scope||this,this,b)}}}},isMenuTriggerOver:function(a){return this.menu&&a.target.tagName==this.arrowSelector},isMenuTriggerOut:function(b,a){return this.menu&&b.target.tagName!=this.arrowSelector}});Ext.reg("splitbutton",Ext.SplitButton);Ext.CycleButton=Ext.extend(Ext.SplitButton,{getItemText:function(a){if(a&&this.showText===true){var b="";if(this.prependText){b+=this.prependText}b+=a.text;return b}return undefined},setActiveItem:function(c,a){if(!Ext.isObject(c)){c=this.menu.getComponent(c)}if(c){if(!this.rendered){this.text=this.getItemText(c);this.iconCls=c.iconCls}else{var b=this.getItemText(c);if(b){this.setText(b)}this.setIconClass(c.iconCls)}this.activeItem=c;if(!c.checked){c.setChecked(true,false)}if(this.forceIcon){this.setIconClass(this.forceIcon)}if(!a){this.fireEvent("change",this,c)}}},getActiveItem:function(){return this.activeItem},initComponent:function(){this.addEvents("change");if(this.changeHandler){this.on("change",this.changeHandler,this.scope||this);delete this.changeHandler}this.itemCount=this.items.length;this.menu={cls:"x-cycle-menu",items:[]};var a=0;Ext.each(this.items,function(c,b){Ext.apply(c,{group:c.group||this.id,itemIndex:b,checkHandler:this.checkHandler,scope:this,checked:c.checked||false});this.menu.items.push(c);if(c.checked){a=b}},this);Ext.CycleButton.superclass.initComponent.call(this);this.on("click",this.toggleSelected,this);this.setActiveItem(a,true)},checkHandler:function(a,b){if(b){this.setActiveItem(a)}},toggleSelected:function(){var a=this.menu;a.render();if(!a.hasLayout){a.doLayout()}var d,b;for(var c=1;c<this.itemCount;c++){d=(this.activeItem.itemIndex+c)%this.itemCount;b=a.items.itemAt(d);if(!b.disabled){b.setChecked(true);break}}}});Ext.reg("cycle",Ext.CycleButton);Ext.Toolbar=function(a){if(Ext.isArray(a)){a={items:a,layout:"toolbar"}}else{a=Ext.apply({layout:"toolbar"},a);if(a.buttons){a.items=a.buttons}}Ext.Toolbar.superclass.constructor.call(this,a)};(function(){var a=Ext.Toolbar;Ext.extend(a,Ext.Container,{defaultType:"button",enableOverflow:false,trackMenus:true,internalDefaults:{removeMode:"container",hideParent:true},toolbarCls:"x-toolbar",initComponent:function(){a.superclass.initComponent.call(this);this.addEvents("overflowchange")},onRender:function(c,b){if(!this.el){if(!this.autoCreate){this.autoCreate={cls:this.toolbarCls+" x-small-editor"}}this.el=c.createChild(Ext.apply({id:this.id},this.autoCreate),b);Ext.Toolbar.superclass.onRender.apply(this,arguments)}},lookupComponent:function(b){if(Ext.isString(b)){if(b=="-"){b=new a.Separator()}else{if(b==" "){b=new a.Spacer()}else{if(b=="->"){b=new a.Fill()}else{b=new a.TextItem(b)}}}this.applyDefaults(b)}else{if(b.isFormField||b.render){b=this.createComponent(b)}else{if(b.tag){b=new a.Item({autoEl:b})}else{if(b.tagName){b=new a.Item({el:b})}else{if(Ext.isObject(b)){b=b.xtype?this.createComponent(b):this.constructButton(b)}}}}}return b},applyDefaults:function(e){if(!Ext.isString(e)){e=Ext.Toolbar.superclass.applyDefaults.call(this,e);var b=this.internalDefaults;if(e.events){Ext.applyIf(e.initialConfig,b);Ext.apply(e,b)}else{Ext.applyIf(e,b)}}return e},addSeparator:function(){return this.add(new a.Separator())},addSpacer:function(){return this.add(new a.Spacer())},addFill:function(){this.add(new a.Fill())},addElement:function(b){return this.addItem(new a.Item({el:b}))},addItem:function(b){return this.add.apply(this,arguments)},addButton:function(c){if(Ext.isArray(c)){var e=[];for(var d=0,b=c.length;d<b;d++){e.push(this.addButton(c[d]))}return e}return this.add(this.constructButton(c))},addText:function(b){return this.addItem(new a.TextItem(b))},addDom:function(b){return this.add(new a.Item({autoEl:b}))},addField:function(b){return this.add(b)},insertButton:function(c,g){if(Ext.isArray(g)){var e=[];for(var d=0,b=g.length;d<b;d++){e.push(this.insertButton(c+d,g[d]))}return e}return Ext.Toolbar.superclass.insert.call(this,c,g)},trackMenu:function(c,b){if(this.trackMenus&&c.menu){var d=b?"mun":"mon";this[d](c,"menutriggerover",this.onButtonTriggerOver,this);this[d](c,"menushow",this.onButtonMenuShow,this);this[d](c,"menuhide",this.onButtonMenuHide,this)}},constructButton:function(d){var c=d.events?d:this.createComponent(d,d.split?"splitbutton":this.defaultType);return c},onAdd:function(b){Ext.Toolbar.superclass.onAdd.call(this);this.trackMenu(b);if(this.disabled){b.disable()}},onRemove:function(b){Ext.Toolbar.superclass.onRemove.call(this);if(b==this.activeMenuBtn){delete this.activeMenuBtn}this.trackMenu(b,true)},onDisable:function(){this.items.each(function(b){if(b.disable){b.disable()}})},onEnable:function(){this.items.each(function(b){if(b.enable){b.enable()}})},onButtonTriggerOver:function(b){if(this.activeMenuBtn&&this.activeMenuBtn!=b){this.activeMenuBtn.hideMenu();b.showMenu();this.activeMenuBtn=b}},onButtonMenuShow:function(b){this.activeMenuBtn=b},onButtonMenuHide:function(b){delete this.activeMenuBtn}});Ext.reg("toolbar",Ext.Toolbar);a.Item=Ext.extend(Ext.BoxComponent,{hideParent:true,enable:Ext.emptyFn,disable:Ext.emptyFn,focus:Ext.emptyFn});Ext.reg("tbitem",a.Item);a.Separator=Ext.extend(a.Item,{onRender:function(c,b){this.el=c.createChild({tag:"span",cls:"xtb-sep"},b)}});Ext.reg("tbseparator",a.Separator);a.Spacer=Ext.extend(a.Item,{onRender:function(c,b){this.el=c.createChild({tag:"div",cls:"xtb-spacer",style:this.width?"width:"+this.width+"px":""},b)}});Ext.reg("tbspacer",a.Spacer);a.Fill=Ext.extend(a.Item,{render:Ext.emptyFn,isFill:true});Ext.reg("tbfill",a.Fill);a.TextItem=Ext.extend(a.Item,{constructor:function(b){a.TextItem.superclass.constructor.call(this,Ext.isString(b)?{text:b}:b)},onRender:function(c,b){this.autoEl={cls:"xtb-text",html:this.text||""};a.TextItem.superclass.onRender.call(this,c,b)},setText:function(b){if(this.rendered){this.el.update(b)}else{this.text=b}}});Ext.reg("tbtext",a.TextItem);a.Button=Ext.extend(Ext.Button,{});a.SplitButton=Ext.extend(Ext.SplitButton,{});Ext.reg("tbbutton",a.Button);Ext.reg("tbsplit",a.SplitButton)})();Ext.ButtonGroup=Ext.extend(Ext.Panel,{baseCls:"x-btn-group",layout:"table",defaultType:"button",frame:true,internalDefaults:{removeMode:"container",hideParent:true},initComponent:function(){this.layoutConfig=this.layoutConfig||{};Ext.applyIf(this.layoutConfig,{columns:this.columns});if(!this.title){this.addClass("x-btn-group-notitle")}this.on("afterlayout",this.onAfterLayout,this);Ext.ButtonGroup.superclass.initComponent.call(this)},applyDefaults:function(b){b=Ext.ButtonGroup.superclass.applyDefaults.call(this,b);var a=this.internalDefaults;if(b.events){Ext.applyIf(b.initialConfig,a);Ext.apply(b,a)}else{Ext.applyIf(b,a)}return b},onAfterLayout:function(){var a=this.body.getFrameWidth("lr")+this.body.dom.firstChild.offsetWidth;this.body.setWidth(a);this.el.setWidth(a+this.getFrameWidth())}});Ext.reg("buttongroup",Ext.ButtonGroup);(function(){var a=Ext.Toolbar;Ext.PagingToolbar=Ext.extend(Ext.Toolbar,{pageSize:20,displayMsg:"Displaying {0} - {1} of {2}",emptyMsg:"No data to display",beforePageText:"Page",afterPageText:"of {0}",firstText:"First Page",prevText:"Previous Page",nextText:"Next Page",lastText:"Last Page",refreshText:"Refresh",initComponent:function(){var c=[this.first=new a.Button({tooltip:this.firstText,overflowText:this.firstText,iconCls:"x-tbar-page-first",disabled:true,handler:this.moveFirst,scope:this}),this.prev=new a.Button({tooltip:this.prevText,overflowText:this.prevText,iconCls:"x-tbar-page-prev",disabled:true,handler:this.movePrevious,scope:this}),"-",this.beforePageText,this.inputItem=new Ext.form.NumberField({cls:"x-tbar-page-number",allowDecimals:false,allowNegative:false,enableKeyEvents:true,selectOnFocus:true,submitValue:false,listeners:{scope:this,keydown:this.onPagingKeyDown,blur:this.onPagingBlur}}),this.afterTextItem=new a.TextItem({text:String.format(this.afterPageText,1)}),"-",this.next=new a.Button({tooltip:this.nextText,overflowText:this.nextText,iconCls:"x-tbar-page-next",disabled:true,handler:this.moveNext,scope:this}),this.last=new a.Button({tooltip:this.lastText,overflowText:this.lastText,iconCls:"x-tbar-page-last",disabled:true,handler:this.moveLast,scope:this}),"-",this.refresh=new a.Button({tooltip:this.refreshText,overflowText:this.refreshText,iconCls:"x-tbar-loading",handler:this.doRefresh,scope:this})];var b=this.items||this.buttons||[];if(this.prependButtons){this.items=b.concat(c)}else{this.items=c.concat(b)}delete this.buttons;if(this.displayInfo){this.items.push("->");this.items.push(this.displayItem=new a.TextItem({}))}Ext.PagingToolbar.superclass.initComponent.call(this);this.addEvents("change","beforechange");this.on("afterlayout",this.onFirstLayout,this,{single:true});this.cursor=0;this.bindStore(this.store,true)},onFirstLayout:function(){if(this.dsLoaded){this.onLoad.apply(this,this.dsLoaded)}},updateInfo:function(){if(this.displayItem){var b=this.store.getCount();var c=b==0?this.emptyMsg:String.format(this.displayMsg,this.cursor+1,this.cursor+b,this.store.getTotalCount());this.displayItem.setText(c)}},onLoad:function(b,e,k){if(!this.rendered){this.dsLoaded=[b,e,k];return}var g=this.getParams();this.cursor=(k.params&&k.params[g.start])?k.params[g.start]:0;var i=this.getPageData(),c=i.activePage,h=i.pages;this.afterTextItem.setText(String.format(this.afterPageText,i.pages));this.inputItem.setValue(c);this.first.setDisabled(c==1);this.prev.setDisabled(c==1);this.next.setDisabled(c==h);this.last.setDisabled(c==h);this.refresh.enable();this.updateInfo();this.fireEvent("change",this,i)},getPageData:function(){var b=this.store.getTotalCount();return{total:b,activePage:Math.ceil((this.cursor+this.pageSize)/this.pageSize),pages:b<this.pageSize?1:Math.ceil(b/this.pageSize)}},changePage:function(b){this.doLoad(((b-1)*this.pageSize).constrain(0,this.store.getTotalCount()))},onLoadError:function(){if(!this.rendered){return}this.refresh.enable()},readPage:function(e){var b=this.inputItem.getValue(),c;if(!b||isNaN(c=parseInt(b,10))){this.inputItem.setValue(e.activePage);return false}return c},onPagingFocus:function(){this.inputItem.select()},onPagingBlur:function(b){this.inputItem.setValue(this.getPageData().activePage)},onPagingKeyDown:function(i,h){var c=h.getKey(),l=this.getPageData(),g;if(c==h.RETURN){h.stopEvent();g=this.readPage(l);if(g!==false){g=Math.min(Math.max(1,g),l.pages)-1;this.doLoad(g*this.pageSize)}}else{if(c==h.HOME||c==h.END){h.stopEvent();g=c==h.HOME?1:l.pages;i.setValue(g)}else{if(c==h.UP||c==h.PAGEUP||c==h.DOWN||c==h.PAGEDOWN){h.stopEvent();if((g=this.readPage(l))){var b=h.shiftKey?10:1;if(c==h.DOWN||c==h.PAGEDOWN){b*=-1}g+=b;if(g>=1&g<=l.pages){i.setValue(g)}}}}}},getParams:function(){return this.paramNames||this.store.paramNames},beforeLoad:function(){if(this.rendered&&this.refresh){this.refresh.disable()}},doLoad:function(d){var c={},b=this.getParams();c[b.start]=d;c[b.limit]=this.pageSize;if(this.fireEvent("beforechange",this,c)!==false){this.store.load({params:c})}},moveFirst:function(){this.doLoad(0)},movePrevious:function(){this.doLoad(Math.max(0,this.cursor-this.pageSize))},moveNext:function(){this.doLoad(this.cursor+this.pageSize)},moveLast:function(){var c=this.store.getTotalCount(),b=c%this.pageSize;this.doLoad(b?(c-b):c-this.pageSize)},doRefresh:function(){this.doLoad(this.cursor)},bindStore:function(c,d){var b;if(!d&&this.store){if(c!==this.store&&this.store.autoDestroy){this.store.destroy()}else{this.store.un("beforeload",this.beforeLoad,this);this.store.un("load",this.onLoad,this);this.store.un("exception",this.onLoadError,this)}if(!c){this.store=null}}if(c){c=Ext.StoreMgr.lookup(c);c.on({scope:this,beforeload:this.beforeLoad,load:this.onLoad,exception:this.onLoadError});b=true}this.store=c;if(b){this.onLoad(c,null,{})}},unbind:function(b){this.bindStore(null)},bind:function(b){this.bindStore(b)},onDestroy:function(){this.bindStore(null);Ext.PagingToolbar.superclass.onDestroy.call(this)}})})();Ext.reg("paging",Ext.PagingToolbar);Ext.History=(function(){var e,c;var l=false;var d;function g(){var m=location.href,n=m.indexOf("#");return n>=0?m.substr(n+1):null}function a(){c.value=d}function h(m){d=m;Ext.History.fireEvent("change",m)}function i(n){var m=['<html><body><div id="state">',Ext.util.Format.htmlEncode(n),"</div></body></html>"].join("");try{var p=e.contentWindow.document;p.open();p.write(m);p.close();return true}catch(o){return false}}function b(){if(!e.contentWindow||!e.contentWindow.document){setTimeout(b,10);return}var p=e.contentWindow.document;var n=p.getElementById("state");var m=n?n.innerText:null;var o=g();setInterval(function(){p=e.contentWindow.document;n=p.getElementById("state");var r=n?n.innerText:null;var q=g();if(r!==m){m=r;h(m);top.location.hash=m;o=m;a()}else{if(q!==o){o=q;i(q)}}},50);l=true;Ext.History.fireEvent("ready",Ext.History)}function k(){d=c.value?c.value:g();if(Ext.isIE){b()}else{var m=g();setInterval(function(){var n=g();if(n!==m){m=n;h(m);a()}},50);l=true;Ext.History.fireEvent("ready",Ext.History)}}return{fieldId:"x-history-field",iframeId:"x-history-frame",events:{},init:function(n,m){if(l){Ext.callback(n,m,[this]);return}if(!Ext.isReady){Ext.onReady(function(){Ext.History.init(n,m)});return}c=Ext.getDom(Ext.History.fieldId);if(Ext.isIE){e=Ext.getDom(Ext.History.iframeId)}this.addEvents("ready","change");if(n){this.on("ready",n,m,{single:true})}k()},add:function(m,n){if(n!==false){if(this.getToken()==m){return true}}if(Ext.isIE){return i(m)}else{top.location.hash=m;return true}},back:function(){history.go(-1)},forward:function(){history.go(1)},getToken:function(){return l?d:g()}}})();Ext.apply(Ext.History,new Ext.util.Observable());Ext.Tip=Ext.extend(Ext.Panel,{minWidth:40,maxWidth:300,shadow:"sides",defaultAlign:"tl-bl?",autoRender:true,quickShowInterval:250,frame:true,hidden:true,baseCls:"x-tip",floating:{shadow:true,shim:true,useDisplay:true,constrain:false},autoHeight:true,closeAction:"hide",initComponent:function(){Ext.Tip.superclass.initComponent.call(this);if(this.closable&&!this.title){this.elements+=",header"}},afterRender:function(){Ext.Tip.superclass.afterRender.call(this);if(this.closable){this.addTool({id:"close",handler:this[this.closeAction],scope:this})}},showAt:function(a){Ext.Tip.superclass.show.call(this);if(this.measureWidth!==false&&(!this.initialConfig||typeof this.initialConfig.width!="number")){this.doAutoWidth()}if(this.constrainPosition){a=this.el.adjustForConstraints(a)}this.setPagePosition(a[0],a[1])},doAutoWidth:function(a){a=a||0;var b=this.body.getTextWidth();if(this.title){b=Math.max(b,this.header.child("span").getTextWidth(this.title))}b+=this.getFrameWidth()+(this.closable?20:0)+this.body.getPadding("lr")+a;this.setWidth(b.constrain(this.minWidth,this.maxWidth));if(Ext.isIE7&&!this.repainted){this.el.repaint();this.repainted=true}},showBy:function(a,b){if(!this.rendered){this.render(Ext.getBody())}this.showAt(this.el.getAlignToXY(a,b||this.defaultAlign))},initDraggable:function(){this.dd=new Ext.Tip.DD(this,typeof this.draggable=="boolean"?null:this.draggable);this.header.addClass("x-tip-draggable")}});Ext.reg("tip",Ext.Tip);Ext.Tip.DD=function(b,a){Ext.apply(this,a);this.tip=b;Ext.Tip.DD.superclass.constructor.call(this,b.el.id,"WindowDD-"+b.id);this.setHandleElId(b.header.id);this.scroll=false};Ext.extend(Ext.Tip.DD,Ext.dd.DD,{moveOnly:true,scroll:false,headerOffsets:[100,25],startDrag:function(){this.tip.el.disableShadow()},endDrag:function(a){this.tip.el.enableShadow(true)}});Ext.ToolTip=Ext.extend(Ext.Tip,{showDelay:500,hideDelay:200,dismissDelay:5000,trackMouse:false,anchorToTarget:true,anchorOffset:0,targetCounter:0,constrainPosition:false,initComponent:function(){Ext.ToolTip.superclass.initComponent.call(this);this.lastActive=new Date();this.initTarget(this.target);this.origAnchor=this.anchor},onRender:function(b,a){Ext.ToolTip.superclass.onRender.call(this,b,a);this.anchorCls="x-tip-anchor-"+this.getAnchorPosition();this.anchorEl=this.el.createChild({cls:"x-tip-anchor "+this.anchorCls})},afterRender:function(){Ext.ToolTip.superclass.afterRender.call(this);this.anchorEl.setStyle("z-index",this.el.getZIndex()+1).setVisibilityMode(Ext.Element.DISPLAY)},initTarget:function(c){var a;if((a=Ext.get(c))){if(this.target){var b=Ext.get(this.target);this.mun(b,"mouseover",this.onTargetOver,this);this.mun(b,"mouseout",this.onTargetOut,this);this.mun(b,"mousemove",this.onMouseMove,this)}this.mon(a,{mouseover:this.onTargetOver,mouseout:this.onTargetOut,mousemove:this.onMouseMove,scope:this});this.target=a}if(this.anchor){this.anchorTarget=this.target}},onMouseMove:function(b){var a=this.delegate?b.getTarget(this.delegate):this.triggerElement=true;if(a){this.targetXY=b.getXY();if(a===this.triggerElement){if(!this.hidden&&this.trackMouse){this.setPagePosition(this.getTargetXY())}}else{this.hide();this.lastActive=new Date(0);this.onTargetOver(b)}}else{if(!this.closable&&this.isVisible()){this.hide()}}},getTargetXY:function(){if(this.delegate){this.anchorTarget=this.triggerElement}if(this.anchor){this.targetCounter++;var c=this.getOffsets(),m=(this.anchorToTarget&&!this.trackMouse)?this.el.getAlignToXY(this.anchorTarget,this.getAnchorAlign()):this.targetXY,a=Ext.lib.Dom.getViewWidth()-5,h=Ext.lib.Dom.getViewHeight()-5,i=document.documentElement,e=document.body,l=(i.scrollLeft||e.scrollLeft||0)+5,k=(i.scrollTop||e.scrollTop||0)+5,b=[m[0]+c[0],m[1]+c[1]],g=this.getSize();this.anchorEl.removeClass(this.anchorCls);if(this.targetCounter<2){if(b[0]<l){if(this.anchorToTarget){this.defaultAlign="l-r";if(this.mouseOffset){this.mouseOffset[0]*=-1}}this.anchor="left";return this.getTargetXY()}if(b[0]+g.width>a){if(this.anchorToTarget){this.defaultAlign="r-l";if(this.mouseOffset){this.mouseOffset[0]*=-1}}this.anchor="right";return this.getTargetXY()}if(b[1]<k){if(this.anchorToTarget){this.defaultAlign="t-b";if(this.mouseOffset){this.mouseOffset[1]*=-1}}this.anchor="top";return this.getTargetXY()}if(b[1]+g.height>h){if(this.anchorToTarget){this.defaultAlign="b-t";if(this.mouseOffset){this.mouseOffset[1]*=-1}}this.anchor="bottom";return this.getTargetXY()}}this.anchorCls="x-tip-anchor-"+this.getAnchorPosition();this.anchorEl.addClass(this.anchorCls);this.targetCounter=0;return b}else{var d=this.getMouseOffset();return[this.targetXY[0]+d[0],this.targetXY[1]+d[1]]}},getMouseOffset:function(){var a=this.anchor?[0,0]:[15,18];if(this.mouseOffset){a[0]+=this.mouseOffset[0];a[1]+=this.mouseOffset[1]}return a},getAnchorPosition:function(){if(this.anchor){this.tipAnchor=this.anchor.charAt(0)}else{var a=this.defaultAlign.match(/^([a-z]+)-([a-z]+)(\?)?$/);if(!a){throw"AnchorTip.defaultAlign is invalid"}this.tipAnchor=a[1].charAt(0)}switch(this.tipAnchor){case"t":return"top";case"b":return"bottom";case"r":return"right"}return"left"},getAnchorAlign:function(){switch(this.anchor){case"top":return"tl-bl";case"left":return"tl-tr";case"right":return"tr-tl";default:return"bl-tl"}},getOffsets:function(){var b,a=this.getAnchorPosition().charAt(0);if(this.anchorToTarget&&!this.trackMouse){switch(a){case"t":b=[0,9];break;case"b":b=[0,-13];break;case"r":b=[-13,0];break;default:b=[9,0];break}}else{switch(a){case"t":b=[-15-this.anchorOffset,30];break;case"b":b=[-19-this.anchorOffset,-13-this.el.dom.offsetHeight];break;case"r":b=[-15-this.el.dom.offsetWidth,-13-this.anchorOffset];break;default:b=[25,-13-this.anchorOffset];break}}var c=this.getMouseOffset();b[0]+=c[0];b[1]+=c[1];return b},onTargetOver:function(b){if(this.disabled||b.within(this.target.dom,true)){return}var a=b.getTarget(this.delegate);if(a){this.triggerElement=a;this.clearTimer("hide");this.targetXY=b.getXY();this.delayShow()}},delayShow:function(){if(this.hidden&&!this.showTimer){if(this.lastActive.getElapsed()<this.quickShowInterval){this.show()}else{this.showTimer=this.show.defer(this.showDelay,this)}}else{if(!this.hidden&&this.autoHide!==false){this.show()}}},onTargetOut:function(a){if(this.disabled||a.within(this.target.dom,true)){return}this.clearTimer("show");if(this.autoHide!==false){this.delayHide()}},delayHide:function(){if(!this.hidden&&!this.hideTimer){this.hideTimer=this.hide.defer(this.hideDelay,this)}},hide:function(){this.clearTimer("dismiss");this.lastActive=new Date();if(this.anchorEl){this.anchorEl.hide()}Ext.ToolTip.superclass.hide.call(this);delete this.triggerElement},show:function(){if(this.anchor){this.showAt([-1000,-1000]);this.origConstrainPosition=this.constrainPosition;this.constrainPosition=false;this.anchor=this.origAnchor}this.showAt(this.getTargetXY());if(this.anchor){this.anchorEl.show();this.syncAnchor();this.constrainPosition=this.origConstrainPosition}else{this.anchorEl.hide()}},showAt:function(a){this.lastActive=new Date();this.clearTimers();Ext.ToolTip.superclass.showAt.call(this,a);if(this.dismissDelay&&this.autoHide!==false){this.dismissTimer=this.hide.defer(this.dismissDelay,this)}if(this.anchor&&!this.anchorEl.isVisible()){this.syncAnchor();this.anchorEl.show()}else{this.anchorEl.hide()}},syncAnchor:function(){var a,b,c;switch(this.tipAnchor.charAt(0)){case"t":a="b";b="tl";c=[20+this.anchorOffset,2];break;case"r":a="l";b="tr";c=[-2,11+this.anchorOffset];break;case"b":a="t";b="bl";c=[20+this.anchorOffset,-2];break;default:a="r";b="tl";c=[2,11+this.anchorOffset];break}this.anchorEl.alignTo(this.el,a+"-"+b,c)},setPagePosition:function(a,b){Ext.ToolTip.superclass.setPagePosition.call(this,a,b);if(this.anchor){this.syncAnchor()}},clearTimer:function(a){a=a+"Timer";clearTimeout(this[a]);delete this[a]},clearTimers:function(){this.clearTimer("show");this.clearTimer("dismiss");this.clearTimer("hide")},onShow:function(){Ext.ToolTip.superclass.onShow.call(this);Ext.getDoc().on("mousedown",this.onDocMouseDown,this)},onHide:function(){Ext.ToolTip.superclass.onHide.call(this);Ext.getDoc().un("mousedown",this.onDocMouseDown,this)},onDocMouseDown:function(a){if(this.autoHide!==true&&!this.closable&&!a.within(this.el.dom)){this.disable();this.doEnable.defer(100,this)}},doEnable:function(){if(!this.isDestroyed){this.enable()}},onDisable:function(){this.clearTimers();this.hide()},adjustPosition:function(a,d){if(this.contstrainPosition){var c=this.targetXY[1],b=this.getSize().height;if(d<=c&&(d+b)>=c){d=c-b-5}}return{x:a,y:d}},beforeDestroy:function(){this.clearTimers();Ext.destroy(this.anchorEl);delete this.anchorEl;delete this.target;delete this.anchorTarget;delete this.triggerElement;Ext.ToolTip.superclass.beforeDestroy.call(this)},onDestroy:function(){Ext.getDoc().un("mousedown",this.onDocMouseDown,this);Ext.ToolTip.superclass.onDestroy.call(this)}});Ext.reg("tooltip",Ext.ToolTip);Ext.QuickTip=Ext.extend(Ext.ToolTip,{interceptTitles:false,tagConfig:{namespace:"ext",attribute:"qtip",width:"qwidth",target:"target",title:"qtitle",hide:"hide",cls:"qclass",align:"qalign",anchor:"anchor"},initComponent:function(){this.target=this.target||Ext.getDoc();this.targets=this.targets||{};Ext.QuickTip.superclass.initComponent.call(this)},register:function(e){var h=Ext.isArray(e)?e:arguments;for(var g=0,a=h.length;g<a;g++){var l=h[g];var k=l.target;if(k){if(Ext.isArray(k)){for(var d=0,b=k.length;d<b;d++){this.targets[Ext.id(k[d])]=l}}else{this.targets[Ext.id(k)]=l}}}},unregister:function(a){delete this.targets[Ext.id(a)]},cancelShow:function(b){var a=this.activeTarget;b=Ext.get(b).dom;if(this.isVisible()){if(a&&a.el==b){this.hide()}}else{if(a&&a.el==b){this.clearTimer("show")}}},getTipCfg:function(d){var b=d.getTarget(),c,a;if(this.interceptTitles&&b.title&&Ext.isString(b.title)){c=b.title;b.qtip=c;b.removeAttribute("title");d.preventDefault()}else{a=this.tagConfig;c=b.qtip||Ext.fly(b).getAttribute(a.attribute,a.namespace)}return c},onTargetOver:function(i){if(this.disabled){return}this.targetXY=i.getXY();var c=i.getTarget();if(!c||c.nodeType!==1||c==document||c==document.body){return}if(this.activeTarget&&((c==this.activeTarget.el)||Ext.fly(this.activeTarget.el).contains(c))){this.clearTimer("hide");this.show();return}if(c&&this.targets[c.id]){this.activeTarget=this.targets[c.id];this.activeTarget.el=c;this.anchor=this.activeTarget.anchor;if(this.anchor){this.anchorTarget=c}this.delayShow();return}var g,h=Ext.fly(c),b=this.tagConfig,d=b.namespace;if(g=this.getTipCfg(i)){var a=h.getAttribute(b.hide,d);this.activeTarget={el:c,text:g,width:h.getAttribute(b.width,d),autoHide:a!="user"&&a!=="false",title:h.getAttribute(b.title,d),cls:h.getAttribute(b.cls,d),align:h.getAttribute(b.align,d)};this.anchor=h.getAttribute(b.anchor,d);if(this.anchor){this.anchorTarget=c}this.delayShow()}},onTargetOut:function(a){if(this.activeTarget&&a.within(this.activeTarget.el)&&!this.getTipCfg(a)){return}this.clearTimer("show");if(this.autoHide!==false){this.delayHide()}},showAt:function(b){var a=this.activeTarget;if(a){if(!this.rendered){this.render(Ext.getBody());this.activeTarget=a}if(a.width){this.setWidth(a.width);this.body.setWidth(this.adjustBodyWidth(a.width-this.getFrameWidth()));this.measureWidth=false}else{this.measureWidth=true}this.setTitle(a.title||"");this.body.update(a.text);this.autoHide=a.autoHide;this.dismissDelay=a.dismissDelay||this.dismissDelay;if(this.lastCls){this.el.removeClass(this.lastCls);delete this.lastCls}if(a.cls){this.el.addClass(a.cls);this.lastCls=a.cls}if(this.anchor){this.constrainPosition=false}else{if(a.align){b=this.el.getAlignToXY(a.el,a.align);this.constrainPosition=false}else{this.constrainPosition=true}}}Ext.QuickTip.superclass.showAt.call(this,b)},hide:function(){delete this.activeTarget;Ext.QuickTip.superclass.hide.call(this)}});Ext.reg("quicktip",Ext.QuickTip);Ext.QuickTips=function(){var b,a=false;return{init:function(c){if(!b){if(!Ext.isReady){Ext.onReady(function(){Ext.QuickTips.init(c)});return}b=new Ext.QuickTip({elements:"header,body",disabled:a});if(c!==false){b.render(Ext.getBody())}}},ddDisable:function(){if(b&&!a){b.disable()}},ddEnable:function(){if(b&&!a){b.enable()}},enable:function(){if(b){b.enable()}a=false},disable:function(){if(b){b.disable()}a=true},isEnabled:function(){return b!==undefined&&!b.disabled},getQuickTip:function(){return b},register:function(){b.register.apply(b,arguments)},unregister:function(){b.unregister.apply(b,arguments)},tips:function(){b.register.apply(b,arguments)}}}();Ext.slider.Tip=Ext.extend(Ext.Tip,{minWidth:10,offsets:[0,-10],init:function(a){a.on({scope:this,dragstart:this.onSlide,drag:this.onSlide,dragend:this.hide,destroy:this.destroy})},onSlide:function(b,c,a){this.show();this.body.update(this.getText(a));this.doAutoWidth();this.el.alignTo(a.el,"b-t?",this.offsets)},getText:function(a){return String(a.value)}});Ext.ux.SliderTip=Ext.slider.Tip;Ext.tree.TreePanel=Ext.extend(Ext.Panel,{rootVisible:true,animate:Ext.enableFx,lines:true,enableDD:false,hlDrop:Ext.enableFx,pathSeparator:"/",bubbleEvents:[],initComponent:function(){Ext.tree.TreePanel.superclass.initComponent.call(this);if(!this.eventModel){this.eventModel=new Ext.tree.TreeEventModel(this)}var a=this.loader;if(!a){a=new Ext.tree.TreeLoader({dataUrl:this.dataUrl,requestMethod:this.requestMethod})}else{if(Ext.isObject(a)&&!a.load){a=new Ext.tree.TreeLoader(a)}}this.loader=a;this.nodeHash={};if(this.root){var b=this.root;delete this.root;this.setRootNode(b)}this.addEvents("append","remove","movenode","insert","beforeappend","beforeremove","beforemovenode","beforeinsert","beforeload","load","textchange","beforeexpandnode","beforecollapsenode","expandnode","disabledchange","collapsenode","beforeclick","click","containerclick","checkchange","beforedblclick","dblclick","containerdblclick","contextmenu","containercontextmenu","beforechildrenrendered","startdrag","enddrag","dragdrop","beforenodedrop","nodedrop","nodedragover");if(this.singleExpand){this.on("beforeexpandnode",this.restrictExpand,this)}},proxyNodeEvent:function(c,b,a,h,g,e,d){if(c=="collapse"||c=="expand"||c=="beforecollapse"||c=="beforeexpand"||c=="move"||c=="beforemove"){c=c+"node"}return this.fireEvent(c,b,a,h,g,e,d)},getRootNode:function(){return this.root},setRootNode:function(b){this.destroyRoot();if(!b.render){b=this.loader.createNode(b)}this.root=b;b.ownerTree=this;b.isRoot=true;this.registerNode(b);if(!this.rootVisible){var a=b.attributes.uiProvider;b.ui=a?new a(b):new Ext.tree.RootTreeNodeUI(b)}if(this.innerCt){this.clearInnerCt();this.renderRoot()}return b},clearInnerCt:function(){this.innerCt.update("")},renderRoot:function(){this.root.render();if(!this.rootVisible){this.root.renderChildren()}},getNodeById:function(a){return this.nodeHash[a]},registerNode:function(a){this.nodeHash[a.id]=a},unregisterNode:function(a){delete this.nodeHash[a.id]},toString:function(){return"[Tree"+(this.id?" "+this.id:"")+"]"},restrictExpand:function(a){var b=a.parentNode;if(b){if(b.expandedChild&&b.expandedChild.parentNode==b){b.expandedChild.collapse()}b.expandedChild=a}},getChecked:function(b,c){c=c||this.root;var d=[];var e=function(){if(this.attributes.checked){d.push(!b?this:(b=="id"?this.id:this.attributes[b]))}};c.cascade(e);return d},getLoader:function(){return this.loader},expandAll:function(){this.root.expand(true)},collapseAll:function(){this.root.collapse(true)},getSelectionModel:function(){if(!this.selModel){this.selModel=new Ext.tree.DefaultSelectionModel()}return this.selModel},expandPath:function(g,a,h){if(Ext.isEmpty(g)){if(h){h(false,undefined)}return}a=a||"id";var d=g.split(this.pathSeparator);var c=this.root;if(c.attributes[a]!=d[1]){if(h){h(false,null)}return}var b=1;var e=function(){if(++b==d.length){if(h){h(true,c)}return}var i=c.findChild(a,d[b]);if(!i){if(h){h(false,c)}return}c=i;i.expand(false,false,e)};c.expand(false,false,e)},selectPath:function(e,a,g){if(Ext.isEmpty(e)){if(g){g(false,undefined)}return}a=a||"id";var c=e.split(this.pathSeparator),b=c.pop();if(c.length>1){var d=function(i,h){if(i&&h){var k=h.findChild(a,b);if(k){k.select();if(g){g(true,k)}}else{if(g){g(false,k)}}}else{if(g){g(false,k)}}};this.expandPath(c.join(this.pathSeparator),a,d)}else{this.root.select();if(g){g(true,this.root)}}},getTreeEl:function(){return this.body},onRender:function(b,a){Ext.tree.TreePanel.superclass.onRender.call(this,b,a);this.el.addClass("x-tree");this.innerCt=this.body.createChild({tag:"ul",cls:"x-tree-root-ct "+(this.useArrows?"x-tree-arrows":this.lines?"x-tree-lines":"x-tree-no-lines")})},initEvents:function(){Ext.tree.TreePanel.superclass.initEvents.call(this);if(this.containerScroll){Ext.dd.ScrollManager.register(this.body)}if((this.enableDD||this.enableDrop)&&!this.dropZone){this.dropZone=new Ext.tree.TreeDropZone(this,this.dropConfig||{ddGroup:this.ddGroup||"TreeDD",appendOnly:this.ddAppendOnly===true})}if((this.enableDD||this.enableDrag)&&!this.dragZone){this.dragZone=new Ext.tree.TreeDragZone(this,this.dragConfig||{ddGroup:this.ddGroup||"TreeDD",scroll:this.ddScroll})}this.getSelectionModel().init(this)},afterRender:function(){Ext.tree.TreePanel.superclass.afterRender.call(this);this.renderRoot()},beforeDestroy:function(){if(this.rendered){Ext.dd.ScrollManager.unregister(this.body);Ext.destroy(this.dropZone,this.dragZone)}this.destroyRoot();Ext.destroy(this.loader);this.nodeHash=this.root=this.loader=null;Ext.tree.TreePanel.superclass.beforeDestroy.call(this)},destroyRoot:function(){if(this.root&&this.root.destroy){this.root.destroy(true)}}});Ext.tree.TreePanel.nodeTypes={};Ext.reg("treepanel",Ext.tree.TreePanel);Ext.tree.TreeEventModel=function(a){this.tree=a;this.tree.on("render",this.initEvents,this)};Ext.tree.TreeEventModel.prototype={initEvents:function(){var a=this.tree;if(a.trackMouseOver!==false){a.mon(a.innerCt,{scope:this,mouseover:this.delegateOver,mouseout:this.delegateOut})}a.mon(a.getTreeEl(),{scope:this,click:this.delegateClick,dblclick:this.delegateDblClick,contextmenu:this.delegateContextMenu})},getNode:function(b){var a;if(a=b.getTarget(".x-tree-node-el",10)){var c=Ext.fly(a,"_treeEvents").getAttribute("tree-node-id","ext");if(c){return this.tree.getNodeById(c)}}return null},getNodeTarget:function(b){var a=b.getTarget(".x-tree-node-icon",1);if(!a){a=b.getTarget(".x-tree-node-el",6)}return a},delegateOut:function(b,a){if(!this.beforeEvent(b)){return}if(b.getTarget(".x-tree-ec-icon",1)){var c=this.getNode(b);this.onIconOut(b,c);if(c==this.lastEcOver){delete this.lastEcOver}}if((a=this.getNodeTarget(b))&&!b.within(a,true)){this.onNodeOut(b,this.getNode(b))}},delegateOver:function(b,a){if(!this.beforeEvent(b)){return}if(Ext.isGecko&&!this.trackingDoc){Ext.getBody().on("mouseover",this.trackExit,this);this.trackingDoc=true}if(this.lastEcOver){this.onIconOut(b,this.lastEcOver);delete this.lastEcOver}if(b.getTarget(".x-tree-ec-icon",1)){this.lastEcOver=this.getNode(b);this.onIconOver(b,this.lastEcOver)}if(a=this.getNodeTarget(b)){this.onNodeOver(b,this.getNode(b))}},trackExit:function(a){if(this.lastOverNode){if(this.lastOverNode.ui&&!a.within(this.lastOverNode.ui.getEl())){this.onNodeOut(a,this.lastOverNode)}delete this.lastOverNode;Ext.getBody().un("mouseover",this.trackExit,this);this.trackingDoc=false}},delegateClick:function(b,a){if(this.beforeEvent(b)){if(b.getTarget("input[type=checkbox]",1)){this.onCheckboxClick(b,this.getNode(b))}else{if(b.getTarget(".x-tree-ec-icon",1)){this.onIconClick(b,this.getNode(b))}else{if(this.getNodeTarget(b)){this.onNodeClick(b,this.getNode(b))}}}}else{this.checkContainerEvent(b,"click")}},delegateDblClick:function(b,a){if(this.beforeEvent(b)){if(this.getNodeTarget(b)){this.onNodeDblClick(b,this.getNode(b))}}else{this.checkContainerEvent(b,"dblclick")}},delegateContextMenu:function(b,a){if(this.beforeEvent(b)){if(this.getNodeTarget(b)){this.onNodeContextMenu(b,this.getNode(b))}}else{this.checkContainerEvent(b,"contextmenu")}},checkContainerEvent:function(b,a){if(this.disabled){b.stopEvent();return false}this.onContainerEvent(b,a)},onContainerEvent:function(b,a){this.tree.fireEvent("container"+a,this.tree,b)},onNodeClick:function(b,a){a.ui.onClick(b)},onNodeOver:function(b,a){this.lastOverNode=a;a.ui.onOver(b)},onNodeOut:function(b,a){a.ui.onOut(b)},onIconOver:function(b,a){a.ui.addClass("x-tree-ec-over")},onIconOut:function(b,a){a.ui.removeClass("x-tree-ec-over")},onIconClick:function(b,a){a.ui.ecClick(b)},onCheckboxClick:function(b,a){a.ui.onCheckChange(b)},onNodeDblClick:function(b,a){a.ui.onDblClick(b)},onNodeContextMenu:function(b,a){a.ui.onContextMenu(b)},beforeEvent:function(b){var a=this.getNode(b);if(this.disabled||!a||!a.ui){b.stopEvent();return false}return true},disable:function(){this.disabled=true},enable:function(){this.disabled=false}};Ext.tree.DefaultSelectionModel=Ext.extend(Ext.util.Observable,{constructor:function(a){this.selNode=null;this.addEvents("selectionchange","beforeselect");Ext.apply(this,a);Ext.tree.DefaultSelectionModel.superclass.constructor.call(this)},init:function(a){this.tree=a;a.mon(a.getTreeEl(),"keydown",this.onKeyDown,this);a.on("click",this.onNodeClick,this)},onNodeClick:function(a,b){this.select(a)},select:function(c,a){if(!Ext.fly(c.ui.wrap).isVisible()&&a){return a.call(this,c)}var b=this.selNode;if(c==b){c.ui.onSelectedChange(true)}else{if(this.fireEvent("beforeselect",this,c,b)!==false){if(b&&b.ui){b.ui.onSelectedChange(false)}this.selNode=c;c.ui.onSelectedChange(true);this.fireEvent("selectionchange",this,c,b)}}return c},unselect:function(b,a){if(this.selNode==b){this.clearSelections(a)}},clearSelections:function(a){var b=this.selNode;if(b){b.ui.onSelectedChange(false);this.selNode=null;if(a!==true){this.fireEvent("selectionchange",this,null)}}return b},getSelectedNode:function(){return this.selNode},isSelected:function(a){return this.selNode==a},selectPrevious:function(a){if(!(a=a||this.selNode||this.lastSelNode)){return null}var c=a.previousSibling;if(c){if(!c.isExpanded()||c.childNodes.length<1){return this.select(c,this.selectPrevious)}else{var b=c.lastChild;while(b&&b.isExpanded()&&Ext.fly(b.ui.wrap).isVisible()&&b.childNodes.length>0){b=b.lastChild}return this.select(b,this.selectPrevious)}}else{if(a.parentNode&&(this.tree.rootVisible||!a.parentNode.isRoot)){return this.select(a.parentNode,this.selectPrevious)}}return null},selectNext:function(b){if(!(b=b||this.selNode||this.lastSelNode)){return null}if(b.firstChild&&b.isExpanded()&&Ext.fly(b.ui.wrap).isVisible()){return this.select(b.firstChild,this.selectNext)}else{if(b.nextSibling){return this.select(b.nextSibling,this.selectNext)}else{if(b.parentNode){var a=null;b.parentNode.bubble(function(){if(this.nextSibling){a=this.getOwnerTree().selModel.select(this.nextSibling,this.selectNext);return false}});return a}}}return null},onKeyDown:function(c){var b=this.selNode||this.lastSelNode;var d=this;if(!b){return}var a=c.getKey();switch(a){case c.DOWN:c.stopEvent();this.selectNext();break;case c.UP:c.stopEvent();this.selectPrevious();break;case c.RIGHT:c.preventDefault();if(b.hasChildNodes()){if(!b.isExpanded()){b.expand()}else{if(b.firstChild){this.select(b.firstChild,c)}}}break;case c.LEFT:c.preventDefault();if(b.hasChildNodes()&&b.isExpanded()){b.collapse()}else{if(b.parentNode&&(this.tree.rootVisible||b.parentNode!=this.tree.getRootNode())){this.select(b.parentNode,c)}}break}}});Ext.tree.MultiSelectionModel=Ext.extend(Ext.util.Observable,{constructor:function(a){this.selNodes=[];this.selMap={};this.addEvents("selectionchange");Ext.apply(this,a);Ext.tree.MultiSelectionModel.superclass.constructor.call(this)},init:function(a){this.tree=a;a.mon(a.getTreeEl(),"keydown",this.onKeyDown,this);a.on("click",this.onNodeClick,this)},onNodeClick:function(a,b){if(b.ctrlKey&&this.isSelected(a)){this.unselect(a)}else{this.select(a,b,b.ctrlKey)}},select:function(a,c,b){if(b!==true){this.clearSelections(true)}if(this.isSelected(a)){this.lastSelNode=a;return a}this.selNodes.push(a);this.selMap[a.id]=a;this.lastSelNode=a;a.ui.onSelectedChange(true);this.fireEvent("selectionchange",this,this.selNodes);return a},unselect:function(b){if(this.selMap[b.id]){b.ui.onSelectedChange(false);var c=this.selNodes;var a=c.indexOf(b);if(a!=-1){this.selNodes.splice(a,1)}delete this.selMap[b.id];this.fireEvent("selectionchange",this,this.selNodes)}},clearSelections:function(b){var d=this.selNodes;if(d.length>0){for(var c=0,a=d.length;c<a;c++){d[c].ui.onSelectedChange(false)}this.selNodes=[];this.selMap={};if(b!==true){this.fireEvent("selectionchange",this,this.selNodes)}}},isSelected:function(a){return this.selMap[a.id]?true:false},getSelectedNodes:function(){return this.selNodes.concat([])},onKeyDown:Ext.tree.DefaultSelectionModel.prototype.onKeyDown,selectNext:Ext.tree.DefaultSelectionModel.prototype.selectNext,selectPrevious:Ext.tree.DefaultSelectionModel.prototype.selectPrevious});Ext.data.Tree=Ext.extend(Ext.util.Observable,{constructor:function(a){this.nodeHash={};this.root=null;if(a){this.setRootNode(a)}this.addEvents("append","remove","move","insert","beforeappend","beforeremove","beforemove","beforeinsert");Ext.data.Tree.superclass.constructor.call(this)},pathSeparator:"/",proxyNodeEvent:function(){return this.fireEvent.apply(this,arguments)},getRootNode:function(){return this.root},setRootNode:function(a){this.root=a;a.ownerTree=this;a.isRoot=true;this.registerNode(a);return a},getNodeById:function(a){return this.nodeHash[a]},registerNode:function(a){this.nodeHash[a.id]=a},unregisterNode:function(a){delete this.nodeHash[a.id]},toString:function(){return"[Tree"+(this.id?" "+this.id:"")+"]"}});Ext.data.Node=Ext.extend(Ext.util.Observable,{constructor:function(a){this.attributes=a||{};this.leaf=this.attributes.leaf;this.id=this.attributes.id;if(!this.id){this.id=Ext.id(null,"xnode-");this.attributes.id=this.id}this.childNodes=[];this.parentNode=null;this.firstChild=null;this.lastChild=null;this.previousSibling=null;this.nextSibling=null;this.addEvents({append:true,remove:true,move:true,insert:true,beforeappend:true,beforeremove:true,beforemove:true,beforeinsert:true});this.listeners=this.attributes.listeners;Ext.data.Node.superclass.constructor.call(this)},fireEvent:function(b){if(Ext.data.Node.superclass.fireEvent.apply(this,arguments)===false){return false}var a=this.getOwnerTree();if(a){if(a.proxyNodeEvent.apply(a,arguments)===false){return false}}return true},isLeaf:function(){return this.leaf===true},setFirstChild:function(a){this.firstChild=a},setLastChild:function(a){this.lastChild=a},isLast:function(){return(!this.parentNode?true:this.parentNode.lastChild==this)},isFirst:function(){return(!this.parentNode?true:this.parentNode.firstChild==this)},hasChildNodes:function(){return !this.isLeaf()&&this.childNodes.length>0},isExpandable:function(){return this.attributes.expandable||this.hasChildNodes()},appendChild:function(e){var g=false;if(Ext.isArray(e)){g=e}else{if(arguments.length>1){g=arguments}}if(g){for(var d=0,a=g.length;d<a;d++){this.appendChild(g[d])}}else{if(this.fireEvent("beforeappend",this.ownerTree,this,e)===false){return false}var b=this.childNodes.length;var c=e.parentNode;if(c){if(e.fireEvent("beforemove",e.getOwnerTree(),e,c,this,b)===false){return false}c.removeChild(e)}b=this.childNodes.length;if(b===0){this.setFirstChild(e)}this.childNodes.push(e);e.parentNode=this;var h=this.childNodes[b-1];if(h){e.previousSibling=h;h.nextSibling=e}else{e.previousSibling=null}e.nextSibling=null;this.setLastChild(e);e.setOwnerTree(this.getOwnerTree());this.fireEvent("append",this.ownerTree,this,e,b);if(c){e.fireEvent("move",this.ownerTree,e,c,this,b)}return e}},removeChild:function(c,b){var a=this.childNodes.indexOf(c);if(a==-1){return false}if(this.fireEvent("beforeremove",this.ownerTree,this,c)===false){return false}this.childNodes.splice(a,1);if(c.previousSibling){c.previousSibling.nextSibling=c.nextSibling}if(c.nextSibling){c.nextSibling.previousSibling=c.previousSibling}if(this.firstChild==c){this.setFirstChild(c.nextSibling)}if(this.lastChild==c){this.setLastChild(c.previousSibling)}this.fireEvent("remove",this.ownerTree,this,c);if(b){c.destroy(true)}else{c.clear()}return c},clear:function(a){this.setOwnerTree(null,a);this.parentNode=this.previousSibling=this.nextSibling=null;if(a){this.firstChild=this.lastChild=null}},destroy:function(a){if(a===true){this.purgeListeners();this.clear(true);Ext.each(this.childNodes,function(b){b.destroy(true)});this.childNodes=null}else{this.remove(true)}},insertBefore:function(d,a){if(!a){return this.appendChild(d)}if(d==a){return false}if(this.fireEvent("beforeinsert",this.ownerTree,this,d,a)===false){return false}var b=this.childNodes.indexOf(a);var c=d.parentNode;var e=b;if(c==this&&this.childNodes.indexOf(d)<b){e--}if(c){if(d.fireEvent("beforemove",d.getOwnerTree(),d,c,this,b,a)===false){return false}c.removeChild(d)}if(e===0){this.setFirstChild(d)}this.childNodes.splice(e,0,d);d.parentNode=this;var g=this.childNodes[e-1];if(g){d.previousSibling=g;g.nextSibling=d}else{d.previousSibling=null}d.nextSibling=a;a.previousSibling=d;d.setOwnerTree(this.getOwnerTree());this.fireEvent("insert",this.ownerTree,this,d,a);if(c){d.fireEvent("move",this.ownerTree,d,c,this,e,a)}return d},remove:function(a){if(this.parentNode){this.parentNode.removeChild(this,a)}return this},removeAll:function(a){var c=this.childNodes,b;while((b=c[0])){this.removeChild(b,a)}return this},item:function(a){return this.childNodes[a]},replaceChild:function(a,c){var b=c?c.nextSibling:null;this.removeChild(c);this.insertBefore(a,b);return c},indexOf:function(a){return this.childNodes.indexOf(a)},getOwnerTree:function(){if(!this.ownerTree){var a=this;while(a){if(a.ownerTree){this.ownerTree=a.ownerTree;break}a=a.parentNode}}return this.ownerTree},getDepth:function(){var b=0;var a=this;while(a.parentNode){++b;a=a.parentNode}return b},setOwnerTree:function(a,b){if(a!=this.ownerTree){if(this.ownerTree){this.ownerTree.unregisterNode(this)}this.ownerTree=a;if(b!==true){Ext.each(this.childNodes,function(c){c.setOwnerTree(a)})}if(a){a.registerNode(this)}}},setId:function(b){if(b!==this.id){var a=this.ownerTree;if(a){a.unregisterNode(this)}this.id=this.attributes.id=b;if(a){a.registerNode(this)}this.onIdChange(b)}},onIdChange:Ext.emptyFn,getPath:function(c){c=c||"id";var e=this.parentNode;var a=[this.attributes[c]];while(e){a.unshift(e.attributes[c]);e=e.parentNode}var d=this.getOwnerTree().pathSeparator;return d+a.join(d)},bubble:function(c,b,a){var d=this;while(d){if(c.apply(b||d,a||[d])===false){break}d=d.parentNode}},cascade:function(g,e,b){if(g.apply(e||this,b||[this])!==false){var d=this.childNodes;for(var c=0,a=d.length;c<a;c++){d[c].cascade(g,e,b)}}},eachChild:function(g,e,b){var d=this.childNodes;for(var c=0,a=d.length;c<a;c++){if(g.apply(e||d[c],b||[d[c]])===false){break}}},findChild:function(b,c,a){return this.findChildBy(function(){return this.attributes[b]==c},null,a)},findChildBy:function(h,g,b){var e=this.childNodes,a=e.length,d=0,k,c;for(;d<a;d++){k=e[d];if(h.call(g||k,k)===true){return k}else{if(b){c=k.findChildBy(h,g,b);if(c!=null){return c}}}}return null},sort:function(e,d){var c=this.childNodes;var a=c.length;if(a>0){var g=d?function(){e.apply(d,arguments)}:e;c.sort(g);for(var b=0;b<a;b++){var h=c[b];h.previousSibling=c[b-1];h.nextSibling=c[b+1];if(b===0){this.setFirstChild(h)}if(b==a-1){this.setLastChild(h)}}}},contains:function(a){return a.isAncestor(this)},isAncestor:function(a){var b=this.parentNode;while(b){if(b==a){return true}b=b.parentNode}return false},toString:function(){return"[Node"+(this.id?" "+this.id:"")+"]"}});Ext.tree.TreeNode=Ext.extend(Ext.data.Node,{constructor:function(a){a=a||{};if(Ext.isString(a)){a={text:a}}this.childrenRendered=false;this.rendered=false;Ext.tree.TreeNode.superclass.constructor.call(this,a);this.expanded=a.expanded===true;this.isTarget=a.isTarget!==false;this.draggable=a.draggable!==false&&a.allowDrag!==false;this.allowChildren=a.allowChildren!==false&&a.allowDrop!==false;this.text=a.text;this.disabled=a.disabled===true;this.hidden=a.hidden===true;this.addEvents("textchange","beforeexpand","beforecollapse","expand","disabledchange","collapse","beforeclick","click","checkchange","beforedblclick","dblclick","contextmenu","beforechildrenrendered");var b=this.attributes.uiProvider||this.defaultUI||Ext.tree.TreeNodeUI;this.ui=new b(this)},preventHScroll:true,isExpanded:function(){return this.expanded},getUI:function(){return this.ui},getLoader:function(){var a;return this.loader||((a=this.getOwnerTree())&&a.loader?a.loader:(this.loader=new Ext.tree.TreeLoader()))},setFirstChild:function(a){var b=this.firstChild;Ext.tree.TreeNode.superclass.setFirstChild.call(this,a);if(this.childrenRendered&&b&&a!=b){b.renderIndent(true,true)}if(this.rendered){this.renderIndent(true,true)}},setLastChild:function(b){var a=this.lastChild;Ext.tree.TreeNode.superclass.setLastChild.call(this,b);if(this.childrenRendered&&a&&b!=a){a.renderIndent(true,true)}if(this.rendered){this.renderIndent(true,true)}},appendChild:function(b){if(!b.render&&!Ext.isArray(b)){b=this.getLoader().createNode(b)}var a=Ext.tree.TreeNode.superclass.appendChild.call(this,b);if(a&&this.childrenRendered){a.render()}this.ui.updateExpandIcon();return a},removeChild:function(b,a){this.ownerTree.getSelectionModel().unselect(b);Ext.tree.TreeNode.superclass.removeChild.apply(this,arguments);if(!a){var c=b.ui.rendered;if(c){b.ui.remove()}if(c&&this.childNodes.length<1){this.collapse(false,false)}else{this.ui.updateExpandIcon()}if(!this.firstChild&&!this.isHiddenRoot()){this.childrenRendered=false}}return b},insertBefore:function(c,a){if(!c.render){c=this.getLoader().createNode(c)}var b=Ext.tree.TreeNode.superclass.insertBefore.call(this,c,a);if(b&&a&&this.childrenRendered){c.render()}this.ui.updateExpandIcon();return b},setText:function(b){var a=this.text;this.text=this.attributes.text=b;if(this.rendered){this.ui.onTextChange(this,b,a)}this.fireEvent("textchange",this,b,a)},setIconCls:function(b){var a=this.attributes.iconCls;this.attributes.iconCls=b;if(this.rendered){this.ui.onIconClsChange(this,b,a)}},setTooltip:function(a,b){this.attributes.qtip=a;this.attributes.qtipTitle=b;if(this.rendered){this.ui.onTipChange(this,a,b)}},setIcon:function(a){this.attributes.icon=a;if(this.rendered){this.ui.onIconChange(this,a)}},setHref:function(a,b){this.attributes.href=a;this.attributes.hrefTarget=b;if(this.rendered){this.ui.onHrefChange(this,a,b)}},setCls:function(b){var a=this.attributes.cls;this.attributes.cls=b;if(this.rendered){this.ui.onClsChange(this,b,a)}},select:function(){var a=this.getOwnerTree();if(a){a.getSelectionModel().select(this)}},unselect:function(a){var b=this.getOwnerTree();if(b){b.getSelectionModel().unselect(this,a)}},isSelected:function(){var a=this.getOwnerTree();return a?a.getSelectionModel().isSelected(this):false},expand:function(a,c,d,b){if(!this.expanded){if(this.fireEvent("beforeexpand",this,a,c)===false){return}if(!this.childrenRendered){this.renderChildren()}this.expanded=true;if(!this.isHiddenRoot()&&(this.getOwnerTree().animate&&c!==false)||c){this.ui.animExpand(function(){this.fireEvent("expand",this);this.runCallback(d,b||this,[this]);if(a===true){this.expandChildNodes(true,true)}}.createDelegate(this));return}else{this.ui.expand();this.fireEvent("expand",this);this.runCallback(d,b||this,[this])}}else{this.runCallback(d,b||this,[this])}if(a===true){this.expandChildNodes(true)}},runCallback:function(a,c,b){if(Ext.isFunction(a)){a.apply(c,b)}},isHiddenRoot:function(){return this.isRoot&&!this.getOwnerTree().rootVisible},collapse:function(b,g,h,e){if(this.expanded&&!this.isHiddenRoot()){if(this.fireEvent("beforecollapse",this,b,g)===false){return}this.expanded=false;if((this.getOwnerTree().animate&&g!==false)||g){this.ui.animCollapse(function(){this.fireEvent("collapse",this);this.runCallback(h,e||this,[this]);if(b===true){this.collapseChildNodes(true)}}.createDelegate(this));return}else{this.ui.collapse();this.fireEvent("collapse",this);this.runCallback(h,e||this,[this])}}else{if(!this.expanded){this.runCallback(h,e||this,[this])}}if(b===true){var d=this.childNodes;for(var c=0,a=d.length;c<a;c++){d[c].collapse(true,false)}}},delayedExpand:function(a){if(!this.expandProcId){this.expandProcId=this.expand.defer(a,this)}},cancelExpand:function(){if(this.expandProcId){clearTimeout(this.expandProcId)}this.expandProcId=false},toggle:function(){if(this.expanded){this.collapse()}else{this.expand()}},ensureVisible:function(c,b){var a=this.getOwnerTree();a.expandPath(this.parentNode?this.parentNode.getPath():this.getPath(),false,function(){var d=a.getNodeById(this.id);a.getTreeEl().scrollChildIntoView(d.ui.anchor);this.runCallback(c,b||this,[this])}.createDelegate(this))},expandChildNodes:function(b,e){var d=this.childNodes,c,a=d.length;for(c=0;c<a;c++){d[c].expand(b,e)}},collapseChildNodes:function(b){var d=this.childNodes;for(var c=0,a=d.length;c<a;c++){d[c].collapse(b)}},disable:function(){this.disabled=true;this.unselect();if(this.rendered&&this.ui.onDisableChange){this.ui.onDisableChange(this,true)}this.fireEvent("disabledchange",this,true)},enable:function(){this.disabled=false;if(this.rendered&&this.ui.onDisableChange){this.ui.onDisableChange(this,false)}this.fireEvent("disabledchange",this,false)},renderChildren:function(b){if(b!==false){this.fireEvent("beforechildrenrendered",this)}var d=this.childNodes;for(var c=0,a=d.length;c<a;c++){d[c].render(true)}this.childrenRendered=true},sort:function(e,d){Ext.tree.TreeNode.superclass.sort.apply(this,arguments);if(this.childrenRendered){var c=this.childNodes;for(var b=0,a=c.length;b<a;b++){c[b].render(true)}}},render:function(a){this.ui.render(a);if(!this.rendered){this.getOwnerTree().registerNode(this);this.rendered=true;if(this.expanded){this.expanded=false;this.expand(false,false)}}},renderIndent:function(b,e){if(e){this.ui.childIndent=null}this.ui.renderIndent();if(b===true&&this.childrenRendered){var d=this.childNodes;for(var c=0,a=d.length;c<a;c++){d[c].renderIndent(true,e)}}},beginUpdate:function(){this.childrenRendered=false},endUpdate:function(){if(this.expanded&&this.rendered){this.renderChildren()}},destroy:function(a){if(a===true){this.unselect(true)}Ext.tree.TreeNode.superclass.destroy.call(this,a);Ext.destroy(this.ui,this.loader);this.ui=this.loader=null},onIdChange:function(a){this.ui.onIdChange(a)}});Ext.tree.TreePanel.nodeTypes.node=Ext.tree.TreeNode;Ext.tree.AsyncTreeNode=function(a){this.loaded=a&&a.loaded===true;this.loading=false;Ext.tree.AsyncTreeNode.superclass.constructor.apply(this,arguments);this.addEvents("beforeload","load")};Ext.extend(Ext.tree.AsyncTreeNode,Ext.tree.TreeNode,{expand:function(b,e,h,c){if(this.loading){var g;var d=function(){if(!this.loading){clearInterval(g);this.expand(b,e,h,c)}}.createDelegate(this);g=setInterval(d,200);return}if(!this.loaded){if(this.fireEvent("beforeload",this)===false){return}this.loading=true;this.ui.beforeLoad(this);var a=this.loader||this.attributes.loader||this.getOwnerTree().getLoader();if(a){a.load(this,this.loadComplete.createDelegate(this,[b,e,h,c]),this);return}}Ext.tree.AsyncTreeNode.superclass.expand.call(this,b,e,h,c)},isLoading:function(){return this.loading},loadComplete:function(a,c,d,b){this.loading=false;this.loaded=true;this.ui.afterLoad(this);this.fireEvent("load",this);this.expand(a,c,d,b)},isLoaded:function(){return this.loaded},hasChildNodes:function(){if(!this.isLeaf()&&!this.loaded){return true}else{return Ext.tree.AsyncTreeNode.superclass.hasChildNodes.call(this)}},reload:function(b,a){this.collapse(false,false);while(this.firstChild){this.removeChild(this.firstChild).destroy()}this.childrenRendered=false;this.loaded=false;if(this.isHiddenRoot()){this.expanded=false}this.expand(false,false,b,a)}});Ext.tree.TreePanel.nodeTypes.async=Ext.tree.AsyncTreeNode;Ext.tree.TreeNodeUI=Ext.extend(Object,{constructor:function(a){Ext.apply(this,{node:a,rendered:false,animating:false,wasLeaf:true,ecc:"x-tree-ec-icon x-tree-elbow",emptyIcon:Ext.BLANK_IMAGE_URL})},removeChild:function(a){if(this.rendered){this.ctNode.removeChild(a.ui.getEl())}},beforeLoad:function(){this.addClass("x-tree-node-loading")},afterLoad:function(){this.removeClass("x-tree-node-loading")},onTextChange:function(b,c,a){if(this.rendered){this.textNode.innerHTML=c}},onIconClsChange:function(c,a,b){if(this.rendered){Ext.fly(this.iconNode).replaceClass(b,a)}},onIconChange:function(b,a){if(this.rendered){var c=Ext.isEmpty(a);this.iconNode.src=c?this.emptyIcon:a;Ext.fly(this.iconNode)[c?"removeClass":"addClass"]("x-tree-node-inline-icon")}},onTipChange:function(b,c,d){if(this.rendered){var a=Ext.isDefined(d);if(this.textNode.setAttributeNS){this.textNode.setAttributeNS("ext","qtip",c);if(a){this.textNode.setAttributeNS("ext","qtitle",d)}}else{this.textNode.setAttribute("ext:qtip",c);if(a){this.textNode.setAttribute("ext:qtitle",d)}}}},onHrefChange:function(b,a,c){if(this.rendered){this.anchor.href=this.getHref(a);if(Ext.isDefined(c)){this.anchor.target=c}}},onClsChange:function(c,a,b){if(this.rendered){Ext.fly(this.elNode).replaceClass(b,a)}},onDisableChange:function(a,b){this.disabled=b;if(this.checkbox){this.checkbox.disabled=b}this[b?"addClass":"removeClass"]("x-tree-node-disabled")},onSelectedChange:function(a){if(a){this.focus();this.addClass("x-tree-selected")}else{this.removeClass("x-tree-selected")}},onMove:function(a,h,e,g,d,b){this.childIndent=null;if(this.rendered){var i=g.ui.getContainer();if(!i){this.holder=document.createElement("div");this.holder.appendChild(this.wrap);return}var c=b?b.ui.getEl():null;if(c){i.insertBefore(this.wrap,c)}else{i.appendChild(this.wrap)}this.node.renderIndent(true,e!=g)}},addClass:function(a){if(this.elNode){Ext.fly(this.elNode).addClass(a)}},removeClass:function(a){if(this.elNode){Ext.fly(this.elNode).removeClass(a)}},remove:function(){if(this.rendered){this.holder=document.createElement("div");this.holder.appendChild(this.wrap)}},fireEvent:function(){return this.node.fireEvent.apply(this.node,arguments)},initEvents:function(){this.node.on("move",this.onMove,this);if(this.node.disabled){this.onDisableChange(this.node,true)}if(this.node.hidden){this.hide()}var b=this.node.getOwnerTree();var a=b.enableDD||b.enableDrag||b.enableDrop;if(a&&(!this.node.isRoot||b.rootVisible)){Ext.dd.Registry.register(this.elNode,{node:this.node,handles:this.getDDHandles(),isHandle:false})}},getDDHandles:function(){return[this.iconNode,this.textNode,this.elNode]},hide:function(){this.node.hidden=true;if(this.wrap){this.wrap.style.display="none"}},show:function(){this.node.hidden=false;if(this.wrap){this.wrap.style.display=""}},onContextMenu:function(a){if(this.node.hasListener("contextmenu")||this.node.getOwnerTree().hasListener("contextmenu")){a.preventDefault();this.focus();this.fireEvent("contextmenu",this.node,a)}},onClick:function(c){if(this.dropping){c.stopEvent();return}if(this.fireEvent("beforeclick",this.node,c)!==false){var b=c.getTarget("a");if(!this.disabled&&this.node.attributes.href&&b){this.fireEvent("click",this.node,c);return}else{if(b&&c.ctrlKey){c.stopEvent()}}c.preventDefault();if(this.disabled){return}if(this.node.attributes.singleClickExpand&&!this.animating&&this.node.isExpandable()){this.node.toggle()}this.fireEvent("click",this.node,c)}else{c.stopEvent()}},onDblClick:function(a){a.preventDefault();if(this.disabled){return}if(this.fireEvent("beforedblclick",this.node,a)!==false){if(this.checkbox){this.toggleCheck()}if(!this.animating&&this.node.isExpandable()){this.node.toggle()}this.fireEvent("dblclick",this.node,a)}},onOver:function(a){this.addClass("x-tree-node-over")},onOut:function(a){this.removeClass("x-tree-node-over")},onCheckChange:function(){var a=this.checkbox.checked;this.checkbox.defaultChecked=a;this.node.attributes.checked=a;this.fireEvent("checkchange",this.node,a)},ecClick:function(a){if(!this.animating&&this.node.isExpandable()){this.node.toggle()}},startDrop:function(){this.dropping=true},endDrop:function(){setTimeout(function(){this.dropping=false}.createDelegate(this),50)},expand:function(){this.updateExpandIcon();this.ctNode.style.display=""},focus:function(){if(!this.node.preventHScroll){try{this.anchor.focus()}catch(c){}}else{try{var b=this.node.getOwnerTree().getTreeEl().dom;var a=b.scrollLeft;this.anchor.focus();b.scrollLeft=a}catch(c){}}},toggleCheck:function(b){var a=this.checkbox;if(a){a.checked=(b===undefined?!a.checked:b);this.onCheckChange()}},blur:function(){try{this.anchor.blur()}catch(a){}},animExpand:function(b){var a=Ext.get(this.ctNode);a.stopFx();if(!this.node.isExpandable()){this.updateExpandIcon();this.ctNode.style.display="";Ext.callback(b);return}this.animating=true;this.updateExpandIcon();a.slideIn("t",{callback:function(){this.animating=false;Ext.callback(b)},scope:this,duration:this.node.ownerTree.duration||0.25})},highlight:function(){var a=this.node.getOwnerTree();Ext.fly(this.wrap).highlight(a.hlColor||"C3DAF9",{endColor:a.hlBaseColor})},collapse:function(){this.updateExpandIcon();this.ctNode.style.display="none"},animCollapse:function(b){var a=Ext.get(this.ctNode);a.enableDisplayMode("block");a.stopFx();this.animating=true;this.updateExpandIcon();a.slideOut("t",{callback:function(){this.animating=false;Ext.callback(b)},scope:this,duration:this.node.ownerTree.duration||0.25})},getContainer:function(){return this.ctNode},getEl:function(){return this.wrap},appendDDGhost:function(a){a.appendChild(this.elNode.cloneNode(true))},getDDRepairXY:function(){return Ext.lib.Dom.getXY(this.iconNode)},onRender:function(){this.render()},render:function(c){var e=this.node,b=e.attributes;var d=e.parentNode?e.parentNode.ui.getContainer():e.ownerTree.innerCt.dom;if(!this.rendered){this.rendered=true;this.renderElements(e,b,d,c);if(b.qtip){this.onTipChange(e,b.qtip,b.qtipTitle)}else{if(b.qtipCfg){b.qtipCfg.target=Ext.id(this.textNode);Ext.QuickTips.register(b.qtipCfg)}}this.initEvents();if(!this.node.expanded){this.updateExpandIcon(true)}}else{if(c===true){d.appendChild(this.wrap)}}},renderElements:function(e,l,k,m){this.indentMarkup=e.parentNode?e.parentNode.ui.getChildIndent():"";var g=Ext.isBoolean(l.checked),b,c=this.getHref(l.href),d=['<li class="x-tree-node"><div ext:tree-node-id="',e.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ',l.cls,'" unselectable="on">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img alt="" src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow" />','<img alt="" src="',l.icon||this.emptyIcon,'" class="x-tree-node-icon',(l.icon?" x-tree-node-inline-icon":""),(l.iconCls?" "+l.iconCls:""),'" unselectable="on" />',g?('<input class="x-tree-node-cb" type="checkbox" '+(l.checked?'checked="checked" />':"/>")):"",'<a hidefocus="on" class="x-tree-node-anchor" href="',c,'" tabIndex="1" ',l.hrefTarget?' target="'+l.hrefTarget+'"':"",'><span unselectable="on">',e.text,"</span></a></div>",'<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>"].join("");if(m!==true&&e.nextSibling&&(b=e.nextSibling.ui.getEl())){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",b,d)}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",k,d)}this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var i=this.elNode.childNodes;this.indentNode=i[0];this.ecNode=i[1];this.iconNode=i[2];var h=3;if(g){this.checkbox=i[3];this.checkbox.defaultChecked=this.checkbox.checked;h++}this.anchor=i[h];this.textNode=i[h].firstChild},getHref:function(a){return Ext.isEmpty(a)?(Ext.isGecko?"":"#"):a},getAnchor:function(){return this.anchor},getTextEl:function(){return this.textNode},getIconEl:function(){return this.iconNode},isChecked:function(){return this.checkbox?this.checkbox.checked:false},updateExpandIcon:function(){if(this.rendered){var g=this.node,d,c,a=g.isLast()?"x-tree-elbow-end":"x-tree-elbow",e=g.hasChildNodes();if(e||g.attributes.expandable){if(g.expanded){a+="-minus";d="x-tree-node-collapsed";c="x-tree-node-expanded"}else{a+="-plus";d="x-tree-node-expanded";c="x-tree-node-collapsed"}if(this.wasLeaf){this.removeClass("x-tree-node-leaf");this.wasLeaf=false}if(this.c1!=d||this.c2!=c){Ext.fly(this.elNode).replaceClass(d,c);this.c1=d;this.c2=c}}else{if(!this.wasLeaf){Ext.fly(this.elNode).replaceClass("x-tree-node-expanded","x-tree-node-collapsed");delete this.c1;delete this.c2;this.wasLeaf=true}}var b="x-tree-ec-icon "+a;if(this.ecc!=b){this.ecNode.className=b;this.ecc=b}}},onIdChange:function(a){if(this.rendered){this.elNode.setAttribute("ext:tree-node-id",a)}},getChildIndent:function(){if(!this.childIndent){var a=[],b=this.node;while(b){if(!b.isRoot||(b.isRoot&&b.ownerTree.rootVisible)){if(!b.isLast()){a.unshift('<img alt="" src="'+this.emptyIcon+'" class="x-tree-elbow-line" />')}else{a.unshift('<img alt="" src="'+this.emptyIcon+'" class="x-tree-icon" />')}}b=b.parentNode}this.childIndent=a.join("")}return this.childIndent},renderIndent:function(){if(this.rendered){var a="",b=this.node.parentNode;if(b){a=b.ui.getChildIndent()}if(this.indentMarkup!=a){this.indentNode.innerHTML=a;this.indentMarkup=a}this.updateExpandIcon()}},destroy:function(){if(this.elNode){Ext.dd.Registry.unregister(this.elNode.id)}Ext.each(["textnode","anchor","checkbox","indentNode","ecNode","iconNode","elNode","ctNode","wrap","holder"],function(a){if(this[a]){Ext.fly(this[a]).remove();delete this[a]}},this);delete this.node}});Ext.tree.RootTreeNodeUI=Ext.extend(Ext.tree.TreeNodeUI,{render:function(){if(!this.rendered){var a=this.node.ownerTree.innerCt.dom;this.node.expanded=true;a.innerHTML='<div class="x-tree-root-node"></div>';this.wrap=this.ctNode=a.firstChild}},collapse:Ext.emptyFn,expand:Ext.emptyFn});Ext.tree.TreeLoader=function(a){this.baseParams={};Ext.apply(this,a);this.addEvents("beforeload","load","loadexception");Ext.tree.TreeLoader.superclass.constructor.call(this);if(Ext.isString(this.paramOrder)){this.paramOrder=this.paramOrder.split(/[\s,|]/)}};Ext.extend(Ext.tree.TreeLoader,Ext.util.Observable,{uiProviders:{},clearOnLoad:true,paramOrder:undefined,paramsAsHash:false,nodeParameter:"node",directFn:undefined,load:function(b,c,a){if(this.clearOnLoad){while(b.firstChild){b.removeChild(b.firstChild)}}if(this.doPreload(b)){this.runCallback(c,a||b,[b])}else{if(this.directFn||this.dataUrl||this.url){this.requestData(b,c,a||b)}}},doPreload:function(d){if(d.attributes.children){if(d.childNodes.length<1){var c=d.attributes.children;d.beginUpdate();for(var b=0,a=c.length;b<a;b++){var e=d.appendChild(this.createNode(c[b]));if(this.preloadChildren){this.doPreload(e)}}d.endUpdate()}return true}return false},getParams:function(g){var e=Ext.apply({},this.baseParams),h=this.nodeParameter,b=this.paramOrder;h&&(e[h]=g.id);if(this.directFn){var c=[g.id];if(b){if(h&&b.indexOf(h)>-1){c=[]}for(var d=0,a=b.length;d<a;d++){c.push(e[b[d]])}}else{if(this.paramsAsHash){c=[e]}}return c}else{return e}},requestData:function(c,d,b){if(this.fireEvent("beforeload",this,c,d)!==false){if(this.directFn){var a=this.getParams(c);a.push(this.processDirectResponse.createDelegate(this,[{callback:d,node:c,scope:b}],true));this.directFn.apply(window,a)}else{this.transId=Ext.Ajax.request({method:this.requestMethod,url:this.dataUrl||this.url,success:this.handleResponse,failure:this.handleFailure,scope:this,argument:{callback:d,node:c,scope:b},params:this.getParams(c)})}}else{this.runCallback(d,b||c,[])}},processDirectResponse:function(a,b,c){if(b.status){this.handleResponse({responseData:Ext.isArray(a)?a:null,responseText:a,argument:c})}else{this.handleFailure({argument:c})}},runCallback:function(a,c,b){if(Ext.isFunction(a)){a.apply(c,b)}},isLoading:function(){return !!this.transId},abort:function(){if(this.isLoading()){Ext.Ajax.abort(this.transId)}},createNode:function(attr){if(this.baseAttrs){Ext.applyIf(attr,this.baseAttrs)}if(this.applyLoader!==false&&!attr.loader){attr.loader=this}if(Ext.isString(attr.uiProvider)){attr.uiProvider=this.uiProviders[attr.uiProvider]||eval(attr.uiProvider)}if(attr.nodeType){return new Ext.tree.TreePanel.nodeTypes[attr.nodeType](attr)}else{return attr.leaf?new Ext.tree.TreeNode(attr):new Ext.tree.AsyncTreeNode(attr)}},processResponse:function(d,c,l,m){var p=d.responseText;try{var a=d.responseData||Ext.decode(p);c.beginUpdate();for(var g=0,h=a.length;g<h;g++){var b=this.createNode(a[g]);if(b){c.appendChild(b)}}c.endUpdate();this.runCallback(l,m||c,[c])}catch(k){this.handleFailure(d)}},handleResponse:function(c){this.transId=false;var b=c.argument;this.processResponse(c,b.node,b.callback,b.scope);this.fireEvent("load",this,b.node,c)},handleFailure:function(c){this.transId=false;var b=c.argument;this.fireEvent("loadexception",this,b.node,c);this.runCallback(b.callback,b.scope||b.node,[b.node])},destroy:function(){this.abort();this.purgeListeners()}});Ext.tree.TreeFilter=function(a,b){this.tree=a;this.filtered={};Ext.apply(this,b)};Ext.tree.TreeFilter.prototype={clearBlank:false,reverse:false,autoClear:false,remove:false,filter:function(d,a,b){a=a||"text";var c;if(typeof d=="string"){var e=d.length;if(e==0&&this.clearBlank){this.clear();return}d=d.toLowerCase();c=function(g){return g.attributes[a].substr(0,e).toLowerCase()==d}}else{if(d.exec){c=function(g){return d.test(g.attributes[a])}}else{throw"Illegal filter type, must be string or regex"}}this.filterBy(c,null,b)},filterBy:function(d,c,b){b=b||this.tree.root;if(this.autoClear){this.clear()}var a=this.filtered,i=this.reverse;var e=function(l){if(l==b){return true}if(a[l.id]){return false}var k=d.call(c||l,l);if(!k||i){a[l.id]=l;l.ui.hide();return false}return true};b.cascade(e);if(this.remove){for(var h in a){if(typeof h!="function"){var g=a[h];if(g&&g.parentNode){g.parentNode.removeChild(g)}}}}},clear:function(){var b=this.tree;var a=this.filtered;for(var d in a){if(typeof d!="function"){var c=a[d];if(c){c.ui.show()}}}this.filtered={}}};Ext.tree.TreeSorter=Ext.extend(Object,{constructor:function(a,b){Ext.apply(this,b);a.on({scope:this,beforechildrenrendered:this.doSort,append:this.updateSort,insert:this.updateSort,textchange:this.updateSortParent});var c=this.dir&&this.dir.toLowerCase()=="desc",d=this.property||"text";sortType=this.sortType;folderSort=this.folderSort;caseSensitive=this.caseSensitive===true;leafAttr=this.leafAttr||"leaf";if(Ext.isString(sortType)){sortType=Ext.data.SortTypes[sortType]}this.sortFn=function(l,i){var g=l.attributes,e=i.attributes;if(folderSort){if(g[leafAttr]&&!e[leafAttr]){return 1}if(!g[leafAttr]&&e[leafAttr]){return -1}}var k=g[d],h=e[d],m=sortType?sortType(k):(caseSensitive?k:k.toUpperCase());v2=sortType?sortType(h):(caseSensitive?h:h.toUpperCase());if(m<v2){return c?1:-1}else{if(m>v2){return c?-1:1}}return 0}},doSort:function(a){a.sort(this.sortFn)},updateSort:function(a,b){if(b.childrenRendered){this.doSort.defer(1,this,[b])}},updateSortParent:function(a){var b=a.parentNode;if(b&&b.childrenRendered){this.doSort.defer(1,this,[b])}}});if(Ext.dd.DropZone){Ext.tree.TreeDropZone=function(a,b){this.allowParentInsert=b.allowParentInsert||false;this.allowContainerDrop=b.allowContainerDrop||false;this.appendOnly=b.appendOnly||false;Ext.tree.TreeDropZone.superclass.constructor.call(this,a.getTreeEl(),b);this.tree=a;this.dragOverData={};this.lastInsertClass="x-tree-no-status"};Ext.extend(Ext.tree.TreeDropZone,Ext.dd.DropZone,{ddGroup:"TreeDD",expandDelay:1000,expandNode:function(a){if(a.hasChildNodes()&&!a.isExpanded()){a.expand(false,null,this.triggerCacheRefresh.createDelegate(this))}},queueExpand:function(a){this.expandProcId=this.expandNode.defer(this.expandDelay,this,[a])},cancelExpand:function(){if(this.expandProcId){clearTimeout(this.expandProcId);this.expandProcId=false}},isValidDropPoint:function(a,l,i,d,c){if(!a||!c){return false}var g=a.node;var h=c.node;if(!(g&&g.isTarget&&l)){return false}if(l=="append"&&g.allowChildren===false){return false}if((l=="above"||l=="below")&&(g.parentNode&&g.parentNode.allowChildren===false)){return false}if(h&&(g==h||h.contains(g))){return false}var b=this.dragOverData;b.tree=this.tree;b.target=g;b.data=c;b.point=l;b.source=i;b.rawEvent=d;b.dropNode=h;b.cancel=false;var k=this.tree.fireEvent("nodedragover",b);return b.cancel===false&&k!==false},getDropPoint:function(h,g,m){var o=g.node;if(o.isRoot){return o.allowChildren!==false?"append":false}var c=g.ddel;var p=Ext.lib.Dom.getY(c),k=p+c.offsetHeight;var i=Ext.lib.Event.getPageY(h);var l=o.allowChildren===false||o.isLeaf();if(this.appendOnly||o.parentNode.allowChildren===false){return l?false:"append"}var d=false;if(!this.allowParentInsert){d=o.hasChildNodes()&&o.isExpanded()}var a=(k-p)/(l?2:3);if(i>=p&&i<(p+a)){return"above"}else{if(!d&&(l||i>=k-a&&i<=k)){return"below"}else{return"append"}}},onNodeEnter:function(d,a,c,b){this.cancelExpand()},onContainerOver:function(a,c,b){if(this.allowContainerDrop&&this.isValidDropPoint({ddel:this.tree.getRootNode().ui.elNode,node:this.tree.getRootNode()},"append",a,c,b)){return this.dropAllowed}return this.dropNotAllowed},onNodeOver:function(b,i,h,g){var l=this.getDropPoint(h,b,i);var c=b.node;if(!this.expandProcId&&l=="append"&&c.hasChildNodes()&&!b.node.isExpanded()){this.queueExpand(c)}else{if(l!="append"){this.cancelExpand()}}var d=this.dropNotAllowed;if(this.isValidDropPoint(b,l,i,h,g)){if(l){var a=b.ddel;var k;if(l=="above"){d=b.node.isFirst()?"x-tree-drop-ok-above":"x-tree-drop-ok-between";k="x-tree-drag-insert-above"}else{if(l=="below"){d=b.node.isLast()?"x-tree-drop-ok-below":"x-tree-drop-ok-between";k="x-tree-drag-insert-below"}else{d="x-tree-drop-ok-append";k="x-tree-drag-append"}}if(this.lastInsertClass!=k){Ext.fly(a).replaceClass(this.lastInsertClass,k);this.lastInsertClass=k}}}return d},onNodeOut:function(d,a,c,b){this.cancelExpand();this.removeDropIndicators(d)},onNodeDrop:function(i,b,h,d){var a=this.getDropPoint(h,i,b);var g=i.node;g.ui.startDrop();if(!this.isValidDropPoint(i,a,b,h,d)){g.ui.endDrop();return false}var c=d.node||(b.getTreeNode?b.getTreeNode(d,g,a,h):null);return this.processDrop(g,d,a,b,h,c)},onContainerDrop:function(a,g,c){if(this.allowContainerDrop&&this.isValidDropPoint({ddel:this.tree.getRootNode().ui.elNode,node:this.tree.getRootNode()},"append",a,g,c)){var d=this.tree.getRootNode();d.ui.startDrop();var b=c.node||(a.getTreeNode?a.getTreeNode(c,d,"append",g):null);return this.processDrop(d,c,"append",a,g,b)}return false},processDrop:function(k,h,b,a,i,d){var g={tree:this.tree,target:k,data:h,point:b,source:a,rawEvent:i,dropNode:d,cancel:!d,dropStatus:false};var c=this.tree.fireEvent("beforenodedrop",g);if(c===false||g.cancel===true||!g.dropNode){k.ui.endDrop();return g.dropStatus}k=g.target;if(b=="append"&&!k.isExpanded()){k.expand(false,null,function(){this.completeDrop(g)}.createDelegate(this))}else{this.completeDrop(g)}return true},completeDrop:function(h){var d=h.dropNode,e=h.point,c=h.target;if(!Ext.isArray(d)){d=[d]}var g;for(var b=0,a=d.length;b<a;b++){g=d[b];if(e=="above"){c.parentNode.insertBefore(g,c)}else{if(e=="below"){c.parentNode.insertBefore(g,c.nextSibling)}else{c.appendChild(g)}}}g.ui.focus();if(Ext.enableFx&&this.tree.hlDrop){g.ui.highlight()}c.ui.endDrop();this.tree.fireEvent("nodedrop",h)},afterNodeMoved:function(a,c,g,d,b){if(Ext.enableFx&&this.tree.hlDrop){b.ui.focus();b.ui.highlight()}this.tree.fireEvent("nodedrop",this.tree,d,c,a,g)},getTree:function(){return this.tree},removeDropIndicators:function(b){if(b&&b.ddel){var a=b.ddel;Ext.fly(a).removeClass(["x-tree-drag-insert-above","x-tree-drag-insert-below","x-tree-drag-append"]);this.lastInsertClass="_noclass"}},beforeDragDrop:function(b,a,c){this.cancelExpand();return true},afterRepair:function(a){if(a&&Ext.enableFx){a.node.ui.highlight()}this.hideProxy()}})}if(Ext.dd.DragZone){Ext.tree.TreeDragZone=function(a,b){Ext.tree.TreeDragZone.superclass.constructor.call(this,a.innerCt,b);this.tree=a};Ext.extend(Ext.tree.TreeDragZone,Ext.dd.DragZone,{ddGroup:"TreeDD",onBeforeDrag:function(a,b){var c=a.node;return c&&c.draggable&&!c.disabled},onInitDrag:function(b){var a=this.dragData;this.tree.getSelectionModel().select(a.node);this.tree.eventModel.disable();this.proxy.update("");a.node.ui.appendDDGhost(this.proxy.ghost.dom);this.tree.fireEvent("startdrag",this.tree,a.node,b)},getRepairXY:function(b,a){return a.node.ui.getDDRepairXY()},onEndDrag:function(a,b){this.tree.eventModel.enable.defer(100,this.tree.eventModel);this.tree.fireEvent("enddrag",this.tree,a.node,b)},onValidDrop:function(a,b,c){this.tree.fireEvent("dragdrop",this.tree,this.dragData.node,a,b);this.hideProxy()},beforeInvalidDrop:function(a,c){var b=this.tree.getSelectionModel();b.clearSelections();b.select(this.dragData.node)},afterRepair:function(){if(Ext.enableFx&&this.tree.hlDrop){Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor||"c3daf9")}this.dragging=false}})}Ext.tree.TreeEditor=function(a,c,b){c=c||{};var d=c.events?c:new Ext.form.TextField(c);Ext.tree.TreeEditor.superclass.constructor.call(this,d,b);this.tree=a;if(!a.rendered){a.on("render",this.initEditor,this)}else{this.initEditor(a)}};Ext.extend(Ext.tree.TreeEditor,Ext.Editor,{alignment:"l-l",autoSize:false,hideEl:false,cls:"x-small-editor x-tree-editor",shim:false,shadow:"frame",maxWidth:250,editDelay:350,initEditor:function(a){a.on({scope:this,beforeclick:this.beforeNodeClick,dblclick:this.onNodeDblClick});this.on({scope:this,complete:this.updateNode,beforestartedit:this.fitToTree,specialkey:this.onSpecialKey});this.on("startedit",this.bindScroll,this,{delay:10})},fitToTree:function(b,c){var e=this.tree.getTreeEl().dom,d=c.dom;if(e.scrollLeft>d.offsetLeft){e.scrollLeft=d.offsetLeft}var a=Math.min(this.maxWidth,(e.clientWidth>20?e.clientWidth:e.offsetWidth)-Math.max(0,d.offsetLeft-e.scrollLeft)-5);this.setSize(a,"")},triggerEdit:function(a,c){this.completeEdit();if(a.attributes.editable!==false){this.editNode=a;if(this.tree.autoScroll){Ext.fly(a.ui.getEl()).scrollIntoView(this.tree.body)}var b=a.text||"";if(!Ext.isGecko&&Ext.isEmpty(a.text)){a.setText(" ")}this.autoEditTimer=this.startEdit.defer(this.editDelay,this,[a.ui.textNode,b]);return false}},bindScroll:function(){this.tree.getTreeEl().on("scroll",this.cancelEdit,this)},beforeNodeClick:function(a,b){clearTimeout(this.autoEditTimer);if(this.tree.getSelectionModel().isSelected(a)){b.stopEvent();return this.triggerEdit(a)}},onNodeDblClick:function(a,b){clearTimeout(this.autoEditTimer)},updateNode:function(a,b){this.tree.getTreeEl().un("scroll",this.cancelEdit,this);this.editNode.setText(b)},onHide:function(){Ext.tree.TreeEditor.superclass.onHide.call(this);if(this.editNode){this.editNode.ui.focus.defer(50,this.editNode.ui)}},onSpecialKey:function(c,b){var a=b.getKey();if(a==b.ESC){b.stopEvent();this.cancelEdit()}else{if(a==b.ENTER&&!b.hasModifier()){b.stopEvent();this.completeEdit()}}},onDestroy:function(){clearTimeout(this.autoEditTimer);Ext.tree.TreeEditor.superclass.onDestroy.call(this);var a=this.tree;a.un("beforeclick",this.beforeNodeClick,this);a.un("dblclick",this.onNodeDblClick,this)}});
/* SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){var F="undefined",t="object",U="Shockwave Flash",Y="ShockwaveFlash.ShockwaveFlash",s="application/x-shockwave-flash",T="SWFObjectExprInst",z="onreadystatechange",Q=window,l=document,v=navigator,V=false,W=[i],q=[],P=[],K=[],n,S,G,D,L=false,a=false,p,I,o=true,O=function(){var ac=typeof l.getElementById!=F&&typeof l.getElementsByTagName!=F&&typeof l.createElement!=F,aj=v.userAgent.toLowerCase(),aa=v.platform.toLowerCase(),ag=aa?(/win/).test(aa):/win/.test(aj),ae=aa?(/mac/).test(aa):/mac/.test(aj),ah=/webkit/.test(aj)?parseFloat(aj.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,Z=!+"\v1",ai=[0,0,0],ad=null;if(typeof v.plugins!=F&&typeof v.plugins[U]==t){ad=v.plugins[U].description;if(ad&&!(typeof v.mimeTypes!=F&&v.mimeTypes[s]&&!v.mimeTypes[s].enabledPlugin)){V=true;Z=false;ad=ad.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ai[0]=parseInt(ad.replace(/^(.*)\..*$/,"$1"),10);ai[1]=parseInt(ad.replace(/^.*\.(.*)\s.*$/,"$1"),10);ai[2]=/[a-zA-Z]/.test(ad)?parseInt(ad.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof Q.ActiveXObject!=F){try{var af=new ActiveXObject(Y);if(af){ad=af.GetVariable("$version");if(ad){Z=true;ad=ad.split(" ")[1].split(",");ai=[parseInt(ad[0],10),parseInt(ad[1],10),parseInt(ad[2],10)]}}}catch(ab){}}}return{w3:ac,pv:ai,wk:ah,ie:Z,win:ag,mac:ae}}(),m=function(){if(!O.w3){return}if((typeof l.readyState!=F&&l.readyState=="complete")||(typeof l.readyState==F&&(l.getElementsByTagName("body")[0]||l.body))){g()}if(!L){if(typeof l.addEventListener!=F){l.addEventListener("DOMContentLoaded",g,false)}if(O.ie&&O.win){l.attachEvent(z,function(){if(l.readyState=="complete"){l.detachEvent(z,arguments.callee);g()}});if(Q==top){(function(){if(L){return}try{l.documentElement.doScroll("left")}catch(Z){setTimeout(arguments.callee,0);return}g()})()}}if(O.wk){(function(){if(L){return}if(!(/loaded|complete/).test(l.readyState)){setTimeout(arguments.callee,0);return}g()})()}u(g)}}();function g(){if(L){return}try{var ab=l.getElementsByTagName("body")[0].appendChild(E("span"));ab.parentNode.removeChild(ab)}catch(ac){return}L=true;var Z=W.length;for(var aa=0;aa<Z;aa++){W[aa]()}}function M(Z){if(L){Z()}else{W[W.length]=Z}}function u(aa){if(typeof Q.addEventListener!=F){Q.addEventListener("load",aa,false)}else{if(typeof l.addEventListener!=F){l.addEventListener("load",aa,false)}else{if(typeof Q.attachEvent!=F){k(Q,"onload",aa)}else{if(typeof Q.onload=="function"){var Z=Q.onload;Q.onload=function(){Z();aa()}}else{Q.onload=aa}}}}}function i(){if(V){X()}else{J()}}function X(){var Z=l.getElementsByTagName("body")[0];var ac=E(t);ac.setAttribute("type",s);var ab=Z.appendChild(ac);if(ab){var aa=0;(function(){if(typeof ab.GetVariable!=F){var ad=ab.GetVariable("$version");if(ad){ad=ad.split(" ")[1].split(",");O.pv=[parseInt(ad[0],10),parseInt(ad[1],10),parseInt(ad[2],10)]}}else{if(aa<10){aa++;setTimeout(arguments.callee,10);return}}Z.removeChild(ac);ab=null;J()})()}else{J()}}function J(){var ai=q.length;if(ai>0){for(var ah=0;ah<ai;ah++){var aa=q[ah].id;var ad=q[ah].callbackFn;var ac={success:false,id:aa};if(O.pv[0]>0){var ag=c(aa);if(ag){if(H(q[ah].swfVersion)&&!(O.wk&&O.wk<312)){y(aa,true);if(ad){ac.success=true;ac.ref=B(aa);ad(ac)}}else{if(q[ah].expressInstall&&C()){var ak={};ak.data=q[ah].expressInstall;ak.width=ag.getAttribute("width")||"0";ak.height=ag.getAttribute("height")||"0";if(ag.getAttribute("class")){ak.styleclass=ag.getAttribute("class")}if(ag.getAttribute("align")){ak.align=ag.getAttribute("align")}var aj={};var Z=ag.getElementsByTagName("param");var ae=Z.length;for(var af=0;af<ae;af++){if(Z[af].getAttribute("name").toLowerCase()!="movie"){aj[Z[af].getAttribute("name")]=Z[af].getAttribute("value")}}R(ak,aj,aa,ad)}else{r(ag);if(ad){ad(ac)}}}}}else{y(aa,true);if(ad){var ab=B(aa);if(ab&&typeof ab.SetVariable!=F){ac.success=true;ac.ref=ab}ad(ac)}}}}}function B(ac){var Z=null;var aa=c(ac);if(aa&&aa.nodeName=="OBJECT"){if(typeof aa.SetVariable!=F){Z=aa}else{var ab=aa.getElementsByTagName(t)[0];if(ab){Z=ab}}}return Z}function C(){return !a&&H("6.0.65")&&(O.win||O.mac)&&!(O.wk&&O.wk<312)}function R(ac,ad,Z,ab){a=true;G=ab||null;D={success:false,id:Z};var ag=c(Z);if(ag){if(ag.nodeName=="OBJECT"){n=h(ag);S=null}else{n=ag;S=Z}ac.id=T;if(typeof ac.width==F||(!(/%$/).test(ac.width)&&parseInt(ac.width,10)<310)){ac.width="310"}if(typeof ac.height==F||(!(/%$/).test(ac.height)&&parseInt(ac.height,10)<137)){ac.height="137"}l.title=l.title.slice(0,47)+" - Flash Player Installation";var af=O.ie&&O.win?"ActiveX":"PlugIn",ae="MMredirectURL="+Q.location.toString().replace(/&/g,"%26")+"&MMplayerType="+af+"&MMdoctitle="+l.title;if(typeof ad.flashvars!=F){ad.flashvars+="&"+ae}else{ad.flashvars=ae}if(O.ie&&O.win&&ag.readyState!=4){var aa=E("div");Z+="SWFObjectNew";aa.setAttribute("id",Z);ag.parentNode.insertBefore(aa,ag);ag.style.display="none";(function(){if(ag.readyState==4){ag.parentNode.removeChild(ag)}else{setTimeout(arguments.callee,10)}})()}w(ac,ad,Z)}}function r(aa){if(O.ie&&O.win&&aa.readyState!=4){var Z=E("div");aa.parentNode.insertBefore(Z,aa);Z.parentNode.replaceChild(h(aa),Z);aa.style.display="none";(function(){if(aa.readyState==4){aa.parentNode.removeChild(aa)}else{setTimeout(arguments.callee,10)}})()}else{aa.parentNode.replaceChild(h(aa),aa)}}function h(ae){var ad=E("div");if(O.win&&O.ie){ad.innerHTML=ae.innerHTML}else{var aa=ae.getElementsByTagName(t)[0];if(aa){var af=aa.childNodes;if(af){var Z=af.length;for(var ab=0;ab<Z;ab++){if(!(af[ab].nodeType==1&&af[ab].nodeName=="PARAM")&&!(af[ab].nodeType==8)){ad.appendChild(af[ab].cloneNode(true))}}}}}return ad}function w(ak,ai,aa){var Z,ac=c(aa);if(O.wk&&O.wk<312){return Z}if(ac){if(typeof ak.id==F){ak.id=aa}if(O.ie&&O.win){var aj="";for(var ag in ak){if(ak[ag]!=Object.prototype[ag]){if(ag.toLowerCase()=="data"){ai.movie=ak[ag]}else{if(ag.toLowerCase()=="styleclass"){aj+=' class="'+ak[ag]+'"'}else{if(ag.toLowerCase()!="classid"){aj+=" "+ag+'="'+ak[ag]+'"'}}}}}var ah="";for(var af in ai){if(ai[af]!=Object.prototype[af]){ah+='<param name="'+af+'" value="'+ai[af]+'" />'}}ac.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+aj+">"+ah+"</object>";P[P.length]=ak.id;Z=c(ak.id)}else{var ab=E(t);ab.setAttribute("type",s);for(var ae in ak){if(ak[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="styleclass"){ab.setAttribute("class",ak[ae])}else{if(ae.toLowerCase()!="classid"){ab.setAttribute(ae,ak[ae])}}}}for(var ad in ai){if(ai[ad]!=Object.prototype[ad]&&ad.toLowerCase()!="movie"){e(ab,ad,ai[ad])}}ac.parentNode.replaceChild(ab,ac);Z=ab}}return Z}function e(ab,Z,aa){var ac=E("param");ac.setAttribute("name",Z);ac.setAttribute("value",aa);ab.appendChild(ac)}function A(aa){var Z=c(aa);if(Z&&Z.nodeName=="OBJECT"){if(O.ie&&O.win){Z.style.display="none";(function(){if(Z.readyState==4){b(aa)}else{setTimeout(arguments.callee,10)}})()}else{Z.parentNode.removeChild(Z)}}}function b(ab){var aa=c(ab);if(aa){for(var Z in aa){if(typeof aa[Z]=="function"){aa[Z]=null}}aa.parentNode.removeChild(aa)}}function c(ab){var Z=null;try{Z=l.getElementById(ab)}catch(aa){}return Z}function E(Z){return l.createElement(Z)}function k(ab,Z,aa){ab.attachEvent(Z,aa);K[K.length]=[ab,Z,aa]}function H(ab){var aa=O.pv,Z=ab.split(".");Z[0]=parseInt(Z[0],10);Z[1]=parseInt(Z[1],10)||0;Z[2]=parseInt(Z[2],10)||0;return(aa[0]>Z[0]||(aa[0]==Z[0]&&aa[1]>Z[1])||(aa[0]==Z[0]&&aa[1]==Z[1]&&aa[2]>=Z[2]))?true:false}function x(ae,aa,af,ad){if(O.ie&&O.mac){return}var ac=l.getElementsByTagName("head")[0];if(!ac){return}var Z=(af&&typeof af=="string")?af:"screen";if(ad){p=null;I=null}if(!p||I!=Z){var ab=E("style");ab.setAttribute("type","text/css");ab.setAttribute("media",Z);p=ac.appendChild(ab);if(O.ie&&O.win&&typeof l.styleSheets!=F&&l.styleSheets.length>0){p=l.styleSheets[l.styleSheets.length-1]}I=Z}if(O.ie&&O.win){if(p&&typeof p.addRule==t){p.addRule(ae,aa)}}else{if(p&&typeof l.createTextNode!=F){p.appendChild(l.createTextNode(ae+" {"+aa+"}"))}}}function y(ab,Z){if(!o){return}var aa=Z?"visible":"hidden";if(L&&c(ab)){c(ab).style.visibility=aa}else{x("#"+ab,"visibility:"+aa)}}function N(aa){var ab=/[\\\"<>\.;]/;var Z=ab.exec(aa)!=null;return Z&&typeof encodeURIComponent!=F?encodeURIComponent(aa):aa}var d=function(){if(O.ie&&O.win){window.attachEvent("onunload",function(){var ae=K.length;for(var ad=0;ad<ae;ad++){K[ad][0].detachEvent(K[ad][1],K[ad][2])}var ab=P.length;for(var ac=0;ac<ab;ac++){A(P[ac])}for(var aa in O){O[aa]=null}O=null;for(var Z in swfobject){swfobject[Z]=null}swfobject=null})}}();return{registerObject:function(ad,Z,ac,ab){if(O.w3&&ad&&Z){var aa={};aa.id=ad;aa.swfVersion=Z;aa.expressInstall=ac;aa.callbackFn=ab;q[q.length]=aa;y(ad,false)}else{if(ab){ab({success:false,id:ad})}}},getObjectById:function(Z){if(O.w3){return B(Z)}},embedSWF:function(ad,aj,ag,ai,aa,ac,ab,af,ah,ae){var Z={success:false,id:aj};if(O.w3&&!(O.wk&&O.wk<312)&&ad&&aj&&ag&&ai&&aa){y(aj,false);M(function(){ag+="";ai+="";var al={};if(ah&&typeof ah===t){for(var an in ah){al[an]=ah[an]}}al.data=ad;al.width=ag;al.height=ai;var ao={};if(af&&typeof af===t){for(var am in af){ao[am]=af[am]}}if(ab&&typeof ab===t){for(var ak in ab){if(typeof ao.flashvars!=F){ao.flashvars+="&"+ak+"="+ab[ak]}else{ao.flashvars=ak+"="+ab[ak]}}}if(H(aa)){var ap=w(al,ao,aj);if(al.id==aj){y(aj,true)}Z.success=true;Z.ref=ap}else{if(ac&&C()){al.data=ac;R(al,ao,aj,ae);return}else{y(aj,true)}}if(ae){ae(Z)}})}else{if(ae){ae(Z)}}},switchOffAutoHideShow:function(){o=false},ua:O,getFlashPlayerVersion:function(){return{major:O.pv[0],minor:O.pv[1],release:O.pv[2]}},hasFlashPlayerVersion:H,createSWF:function(ab,aa,Z){if(O.w3){return w(ab,aa,Z)}else{return undefined}},showExpressInstall:function(ab,ac,Z,aa){if(O.w3&&C()){R(ab,ac,Z,aa)}},removeSWF:function(Z){if(O.w3){A(Z)}},createCSS:function(ac,ab,aa,Z){if(O.w3){x(ac,ab,aa,Z)}},addDomLoadEvent:M,addLoadEvent:u,getQueryParamValue:function(ac){var ab=l.location.search||l.location.hash;if(ab){if(/\?/.test(ab)){ab=ab.split("?")[1]}if(ac==null){return N(ab)}var aa=ab.split("&");for(var Z=0;Z<aa.length;Z++){if(aa[Z].substring(0,aa[Z].indexOf("="))==ac){return N(aa[Z].substring((aa[Z].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var Z=c(T);if(Z&&n){Z.parentNode.replaceChild(n,Z);if(S){y(S,true);if(O.ie&&O.win){n.style.display="block"}}if(G){G(D)}}a=false}}}}();Ext.FlashComponent=Ext.extend(Ext.BoxComponent,{flashVersion:"9.0.115",backgroundColor:"#ffffff",wmode:"opaque",flashVars:undefined,flashParams:undefined,url:undefined,swfId:undefined,swfWidth:"100%",swfHeight:"100%",expressInstall:false,initComponent:function(){Ext.FlashComponent.superclass.initComponent.call(this);this.addEvents("initialize")},onRender:function(){Ext.FlashComponent.superclass.onRender.apply(this,arguments);var b=Ext.apply({allowScriptAccess:"always",bgcolor:this.backgroundColor,wmode:this.wmode},this.flashParams),a=Ext.apply({allowedDomain:document.location.hostname,YUISwfId:this.getId(),YUIBridgeCallback:"Ext.FlashEventProxy.onEvent"},this.flashVars);new swfobject.embedSWF(this.url,this.id,this.swfWidth,this.swfHeight,this.flashVersion,this.expressInstall?Ext.FlashComponent.EXPRESS_INSTALL_URL:undefined,a,b);this.swf=Ext.getDom(this.id);this.el=Ext.get(this.swf)},getSwfId:function(){return this.swfId||(this.swfId="extswf"+(++Ext.Component.AUTO_ID))},getId:function(){return this.id||(this.id="extflashcmp"+(++Ext.Component.AUTO_ID))},onFlashEvent:function(a){switch(a.type){case"swfReady":this.initSwf();return;case"log":return}a.component=this;this.fireEvent(a.type.toLowerCase().replace(/event$/,""),a)},initSwf:function(){this.onSwfReady(!!this.isInitialized);this.isInitialized=true;this.fireEvent("initialize",this)},beforeDestroy:function(){if(this.rendered){swfobject.removeSWF(this.swf.id)}Ext.FlashComponent.superclass.beforeDestroy.call(this)},onSwfReady:Ext.emptyFn});Ext.FlashComponent.EXPRESS_INSTALL_URL="http://swfobject.googlecode.com/svn/trunk/swfobject/expressInstall.swf";Ext.reg("flash",Ext.FlashComponent);Ext.FlashEventProxy={onEvent:function(c,b){var a=Ext.getCmp(c);if(a){a.onFlashEvent(b)}else{arguments.callee.defer(10,this,[c,b])}}};Ext.chart.Chart=Ext.extend(Ext.FlashComponent,{refreshBuffer:100,chartStyle:{padding:10,animationEnabled:true,font:{name:"Tahoma",color:4473924,size:11},dataTip:{padding:5,border:{color:10075112,size:1},background:{color:14346230,alpha:0.9},font:{name:"Tahoma",color:1393291,size:10,bold:true}}},extraStyle:null,seriesStyles:null,disableCaching:Ext.isIE||Ext.isOpera,disableCacheParam:"_dc",initComponent:function(){Ext.chart.Chart.superclass.initComponent.call(this);if(!this.url){this.url=Ext.chart.Chart.CHART_URL}if(this.disableCaching){this.url=Ext.urlAppend(this.url,String.format("{0}={1}",this.disableCacheParam,new Date().getTime()))}this.addEvents("itemmouseover","itemmouseout","itemclick","itemdoubleclick","itemdragstart","itemdrag","itemdragend","beforerefresh","refresh");this.store=Ext.StoreMgr.lookup(this.store)},setStyle:function(a,b){this.swf.setStyle(a,Ext.encode(b))},setStyles:function(a){this.swf.setStyles(Ext.encode(a))},setSeriesStyles:function(b){this.seriesStyles=b;var a=[];Ext.each(b,function(c){a.push(Ext.encode(c))});this.swf.setSeriesStyles(a)},setCategoryNames:function(a){this.swf.setCategoryNames(a)},setLegendRenderer:function(c,b){var a=this;b=b||a;a.removeFnProxy(a.legendFnName);a.legendFnName=a.createFnProxy(function(d){return c.call(b,d)});a.swf.setLegendLabelFunction(a.legendFnName)},setTipRenderer:function(c,b){var a=this;b=b||a;a.removeFnProxy(a.tipFnName);a.tipFnName=a.createFnProxy(function(h,e,g){var d=a.store.getAt(e);return c.call(b,a,d,e,g)});a.swf.setDataTipFunction(a.tipFnName)},setSeries:function(a){this.series=a;this.refresh()},bindStore:function(a,b){if(!b&&this.store){if(a!==this.store&&this.store.autoDestroy){this.store.destroy()}else{this.store.un("datachanged",this.refresh,this);this.store.un("add",this.delayRefresh,this);this.store.un("remove",this.delayRefresh,this);this.store.un("update",this.delayRefresh,this);this.store.un("clear",this.refresh,this)}}if(a){a=Ext.StoreMgr.lookup(a);a.on({scope:this,datachanged:this.refresh,add:this.delayRefresh,remove:this.delayRefresh,update:this.delayRefresh,clear:this.refresh})}this.store=a;if(a&&!b){this.refresh()}},onSwfReady:function(b){Ext.chart.Chart.superclass.onSwfReady.call(this,b);var a;this.swf.setType(this.type);if(this.chartStyle){this.setStyles(Ext.apply({},this.extraStyle,this.chartStyle))}if(this.categoryNames){this.setCategoryNames(this.categoryNames)}if(this.tipRenderer){a=this.getFunctionRef(this.tipRenderer);this.setTipRenderer(a.fn,a.scope)}if(this.legendRenderer){a=this.getFunctionRef(this.legendRenderer);this.setLegendRenderer(a.fn,a.scope)}if(!b){this.bindStore(this.store,true)}this.refresh.defer(10,this)},delayRefresh:function(){if(!this.refreshTask){this.refreshTask=new Ext.util.DelayedTask(this.refresh,this)}this.refreshTask.delay(this.refreshBuffer)},refresh:function(){if(this.fireEvent("beforerefresh",this)!==false){var m=false;var k=[],c=this.store.data.items;for(var g=0,l=c.length;g<l;g++){k[g]=c[g].data}var e=[];var d=0;var n=null;var h=0;if(this.series){d=this.series.length;for(h=0;h<d;h++){n=this.series[h];var b={};for(var a in n){if(a=="style"&&n.style!==null){b.style=Ext.encode(n.style);m=true}else{b[a]=n[a]}}e.push(b)}}if(d>0){for(h=0;h<d;h++){n=e[h];if(!n.type){n.type=this.type}n.dataProvider=k}}else{e.push({type:this.type,dataProvider:k})}this.swf.setDataProvider(e);if(this.seriesStyles){this.setSeriesStyles(this.seriesStyles)}this.fireEvent("refresh",this)}},createFnProxy:function(a){var b="extFnProxy"+(++Ext.chart.Chart.PROXY_FN_ID);Ext.chart.Chart.proxyFunction[b]=a;return"Ext.chart.Chart.proxyFunction."+b},removeFnProxy:function(a){if(!Ext.isEmpty(a)){a=a.replace("Ext.chart.Chart.proxyFunction.","");delete Ext.chart.Chart.proxyFunction[a]}},getFunctionRef:function(a){if(Ext.isFunction(a)){return{fn:a,scope:this}}else{return{fn:a.fn,scope:a.scope||this}}},onDestroy:function(){if(this.refreshTask&&this.refreshTask.cancel){this.refreshTask.cancel()}Ext.chart.Chart.superclass.onDestroy.call(this);this.bindStore(null);this.removeFnProxy(this.tipFnName);this.removeFnProxy(this.legendFnName)}});Ext.reg("chart",Ext.chart.Chart);Ext.chart.Chart.PROXY_FN_ID=0;Ext.chart.Chart.proxyFunction={};Ext.chart.Chart.CHART_URL="http://yui.yahooapis.com/2.8.2/build/charts/assets/charts.swf";Ext.chart.PieChart=Ext.extend(Ext.chart.Chart,{type:"pie",onSwfReady:function(a){Ext.chart.PieChart.superclass.onSwfReady.call(this,a);this.setDataField(this.dataField);this.setCategoryField(this.categoryField)},setDataField:function(a){this.dataField=a;this.swf.setDataField(a)},setCategoryField:function(a){this.categoryField=a;this.swf.setCategoryField(a)}});Ext.reg("piechart",Ext.chart.PieChart);Ext.chart.CartesianChart=Ext.extend(Ext.chart.Chart,{onSwfReady:function(a){Ext.chart.CartesianChart.superclass.onSwfReady.call(this,a);this.labelFn=[];if(this.xField){this.setXField(this.xField)}if(this.yField){this.setYField(this.yField)}if(this.xAxis){this.setXAxis(this.xAxis)}if(this.xAxes){this.setXAxes(this.xAxes)}if(this.yAxis){this.setYAxis(this.yAxis)}if(this.yAxes){this.setYAxes(this.yAxes)}if(Ext.isDefined(this.constrainViewport)){this.swf.setConstrainViewport(this.constrainViewport)}},setXField:function(a){this.xField=a;this.swf.setHorizontalField(a)},setYField:function(a){this.yField=a;this.swf.setVerticalField(a)},setXAxis:function(a){this.xAxis=this.createAxis("xAxis",a);this.swf.setHorizontalAxis(this.xAxis)},setXAxes:function(c){var b;for(var a=0;a<c.length;a++){b=this.createAxis("xAxis"+a,c[a]);this.swf.setHorizontalAxis(b)}},setYAxis:function(a){this.yAxis=this.createAxis("yAxis",a);this.swf.setVerticalAxis(this.yAxis)},setYAxes:function(c){var b;for(var a=0;a<c.length;a++){b=this.createAxis("yAxis"+a,c[a]);this.swf.setVerticalAxis(b)}},createAxis:function(b,d){var e=Ext.apply({},d),c,a;if(this[b]){a=this[b].labelFunction;this.removeFnProxy(a);this.labelFn.remove(a)}if(e.labelRenderer){c=this.getFunctionRef(e.labelRenderer);e.labelFunction=this.createFnProxy(function(g){return c.fn.call(c.scope,g)});delete e.labelRenderer;this.labelFn.push(e.labelFunction)}if(b.indexOf("xAxis")>-1&&e.position=="left"){e.position="bottom"}return e},onDestroy:function(){Ext.chart.CartesianChart.superclass.onDestroy.call(this);Ext.each(this.labelFn,function(a){this.removeFnProxy(a)},this)}});Ext.reg("cartesianchart",Ext.chart.CartesianChart);Ext.chart.LineChart=Ext.extend(Ext.chart.CartesianChart,{type:"line"});Ext.reg("linechart",Ext.chart.LineChart);Ext.chart.ColumnChart=Ext.extend(Ext.chart.CartesianChart,{type:"column"});Ext.reg("columnchart",Ext.chart.ColumnChart);Ext.chart.StackedColumnChart=Ext.extend(Ext.chart.CartesianChart,{type:"stackcolumn"});Ext.reg("stackedcolumnchart",Ext.chart.StackedColumnChart);Ext.chart.BarChart=Ext.extend(Ext.chart.CartesianChart,{type:"bar"});Ext.reg("barchart",Ext.chart.BarChart);Ext.chart.StackedBarChart=Ext.extend(Ext.chart.CartesianChart,{type:"stackbar"});Ext.reg("stackedbarchart",Ext.chart.StackedBarChart);Ext.chart.Axis=function(a){Ext.apply(this,a)};Ext.chart.Axis.prototype={type:null,orientation:"horizontal",reverse:false,labelFunction:null,hideOverlappingLabels:true,labelSpacing:2};Ext.chart.NumericAxis=Ext.extend(Ext.chart.Axis,{type:"numeric",minimum:NaN,maximum:NaN,majorUnit:NaN,minorUnit:NaN,snapToUnits:true,alwaysShowZero:true,scale:"linear",roundMajorUnit:true,calculateByLabelSize:true,position:"left",adjustMaximumByMajorUnit:true,adjustMinimumByMajorUnit:true});Ext.chart.TimeAxis=Ext.extend(Ext.chart.Axis,{type:"time",minimum:null,maximum:null,majorUnit:NaN,majorTimeUnit:null,minorUnit:NaN,minorTimeUnit:null,snapToUnits:true,stackingEnabled:false,calculateByLabelSize:true});Ext.chart.CategoryAxis=Ext.extend(Ext.chart.Axis,{type:"category",categoryNames:null,calculateCategoryCount:false});Ext.chart.Series=function(a){Ext.apply(this,a)};Ext.chart.Series.prototype={type:null,displayName:null};Ext.chart.CartesianSeries=Ext.extend(Ext.chart.Series,{xField:null,yField:null,showInLegend:true,axis:"primary"});Ext.chart.ColumnSeries=Ext.extend(Ext.chart.CartesianSeries,{type:"column"});Ext.chart.LineSeries=Ext.extend(Ext.chart.CartesianSeries,{type:"line"});Ext.chart.BarSeries=Ext.extend(Ext.chart.CartesianSeries,{type:"bar"});Ext.chart.PieSeries=Ext.extend(Ext.chart.Series,{type:"pie",dataField:null,categoryField:null});Ext.menu.Menu=Ext.extend(Ext.Container,{minWidth:120,shadow:"sides",subMenuAlign:"tl-tr?",defaultAlign:"tl-bl?",allowOtherMenus:false,ignoreParentClicks:false,enableScrolling:true,maxHeight:null,scrollIncrement:24,showSeparator:true,defaultOffsets:[0,0],plain:false,floating:true,zIndex:15000,hidden:true,layout:"menu",hideMode:"offsets",scrollerHeight:8,autoLayout:true,defaultType:"menuitem",bufferResize:false,initComponent:function(){if(Ext.isArray(this.initialConfig)){Ext.apply(this,{items:this.initialConfig})}this.addEvents("click","mouseover","mouseout","itemclick");Ext.menu.MenuMgr.register(this);if(this.floating){Ext.EventManager.onWindowResize(this.hide,this)}else{if(this.initialConfig.hidden!==false){this.hidden=false}this.internalDefaults={hideOnClick:false}}Ext.menu.Menu.superclass.initComponent.call(this);if(this.autoLayout){var a=this.doLayout.createDelegate(this,[]);this.on({add:a,remove:a})}},getLayoutTarget:function(){return this.ul},onRender:function(b,a){if(!b){b=Ext.getBody()}var c={id:this.getId(),cls:"x-menu "+((this.floating)?"x-menu-floating x-layer ":"")+(this.cls||"")+(this.plain?" x-menu-plain":"")+(this.showSeparator?"":" x-menu-nosep"),style:this.style,cn:[{tag:"a",cls:"x-menu-focus",href:"#",onclick:"return false;",tabIndex:"-1"},{tag:"ul",cls:"x-menu-list"}]};if(this.floating){this.el=new Ext.Layer({shadow:this.shadow,dh:c,constrain:false,parentEl:b,zindex:this.zIndex})}else{this.el=b.createChild(c)}Ext.menu.Menu.superclass.onRender.call(this,b,a);if(!this.keyNav){this.keyNav=new Ext.menu.MenuNav(this)}this.focusEl=this.el.child("a.x-menu-focus");this.ul=this.el.child("ul.x-menu-list");this.mon(this.ul,{scope:this,click:this.onClick,mouseover:this.onMouseOver,mouseout:this.onMouseOut});if(this.enableScrolling){this.mon(this.el,{scope:this,delegate:".x-menu-scroller",click:this.onScroll,mouseover:this.deactivateActive})}},findTargetItem:function(b){var a=b.getTarget(".x-menu-list-item",this.ul,true);if(a&&a.menuItemId){return this.items.get(a.menuItemId)}},onClick:function(b){var a=this.findTargetItem(b);if(a){if(a.isFormField){this.setActiveItem(a)}else{if(a instanceof Ext.menu.BaseItem){if(a.menu&&this.ignoreParentClicks){a.expandMenu();b.preventDefault()}else{if(a.onClick){a.onClick(b);this.fireEvent("click",this,a,b)}}}}}},setActiveItem:function(a,b){if(a!=this.activeItem){this.deactivateActive();if((this.activeItem=a).isFormField){a.focus()}else{a.activate(b)}}else{if(b){a.expandMenu()}}},deactivateActive:function(){var b=this.activeItem;if(b){if(b.isFormField){if(b.collapse){b.collapse()}}else{b.deactivate()}delete this.activeItem}},tryActivate:function(g,e){var b=this.items;for(var c=g,a=b.length;c>=0&&c<a;c+=e){var d=b.get(c);if(d.isVisible()&&!d.disabled&&(d.canActivate||d.isFormField)){this.setActiveItem(d,false);return d}}return false},onMouseOver:function(b){var a=this.findTargetItem(b);if(a){if(a.canActivate&&!a.disabled){this.setActiveItem(a,true)}}this.over=true;this.fireEvent("mouseover",this,b,a)},onMouseOut:function(b){var a=this.findTargetItem(b);if(a){if(a==this.activeItem&&a.shouldDeactivate&&a.shouldDeactivate(b)){this.activeItem.deactivate();delete this.activeItem}}this.over=false;this.fireEvent("mouseout",this,b,a)},onScroll:function(d,b){if(d){d.stopEvent()}var a=this.ul.dom,c=Ext.fly(b).is(".x-menu-scroller-top");a.scrollTop+=this.scrollIncrement*(c?-1:1);if(c?a.scrollTop<=0:a.scrollTop+this.activeMax>=a.scrollHeight){this.onScrollerOut(null,b)}},onScrollerIn:function(d,b){var a=this.ul.dom,c=Ext.fly(b).is(".x-menu-scroller-top");if(c?a.scrollTop>0:a.scrollTop+this.activeMax<a.scrollHeight){Ext.fly(b).addClass(["x-menu-item-active","x-menu-scroller-active"])}},onScrollerOut:function(b,a){Ext.fly(a).removeClass(["x-menu-item-active","x-menu-scroller-active"])},show:function(b,c,a){if(this.floating){this.parentMenu=a;if(!this.el){this.render();this.doLayout(false,true)}this.showAt(this.el.getAlignToXY(b,c||this.defaultAlign,this.defaultOffsets),a)}else{Ext.menu.Menu.superclass.show.call(this)}},showAt:function(b,a){if(this.fireEvent("beforeshow",this)!==false){this.parentMenu=a;if(!this.el){this.render()}if(this.enableScrolling){this.el.setXY(b);b[1]=this.constrainScroll(b[1]);b=[this.el.adjustForConstraints(b)[0],b[1]]}else{b=this.el.adjustForConstraints(b)}this.el.setXY(b);this.el.show();Ext.menu.Menu.superclass.onShow.call(this);if(Ext.isIE){this.fireEvent("autosize",this);if(!Ext.isIE8){this.el.repaint()}}this.hidden=false;this.focus();this.fireEvent("show",this)}},constrainScroll:function(i){var b,d=this.ul.setHeight("auto").getHeight(),a=i,h,e,g,c;if(this.floating){e=Ext.fly(this.el.dom.parentNode);g=e.getScroll().top;c=e.getViewSize().height;h=i-g;b=this.maxHeight?this.maxHeight:c-h;if(d>c){b=c;a=i-h}else{if(b<d){a=i-(d-b);b=d}}}else{b=this.getHeight()}if(this.maxHeight){b=Math.min(this.maxHeight,b)}if(d>b&&b>0){this.activeMax=b-this.scrollerHeight*2-this.el.getFrameWidth("tb")-Ext.num(this.el.shadowOffset,0);this.ul.setHeight(this.activeMax);this.createScrollers();this.el.select(".x-menu-scroller").setDisplayed("")}else{this.ul.setHeight(d);this.el.select(".x-menu-scroller").setDisplayed("none")}this.ul.dom.scrollTop=0;return a},createScrollers:function(){if(!this.scroller){this.scroller={pos:0,top:this.el.insertFirst({tag:"div",cls:"x-menu-scroller x-menu-scroller-top",html:" "}),bottom:this.el.createChild({tag:"div",cls:"x-menu-scroller x-menu-scroller-bottom",html:" "})};this.scroller.top.hover(this.onScrollerIn,this.onScrollerOut,this);this.scroller.topRepeater=new Ext.util.ClickRepeater(this.scroller.top,{listeners:{click:this.onScroll.createDelegate(this,[null,this.scroller.top],false)}});this.scroller.bottom.hover(this.onScrollerIn,this.onScrollerOut,this);this.scroller.bottomRepeater=new Ext.util.ClickRepeater(this.scroller.bottom,{listeners:{click:this.onScroll.createDelegate(this,[null,this.scroller.bottom],false)}})}},onLayout:function(){if(this.isVisible()){if(this.enableScrolling){this.constrainScroll(this.el.getTop())}if(this.floating){this.el.sync()}}},focus:function(){if(!this.hidden){this.doFocus.defer(50,this)}},doFocus:function(){if(!this.hidden){this.focusEl.focus()}},hide:function(a){if(!this.isDestroyed){this.deepHide=a;Ext.menu.Menu.superclass.hide.call(this);delete this.deepHide}},onHide:function(){Ext.menu.Menu.superclass.onHide.call(this);this.deactivateActive();if(this.el&&this.floating){this.el.hide()}var a=this.parentMenu;if(this.deepHide===true&&a){if(a.floating){a.hide(true)}else{a.deactivateActive()}}},lookupComponent:function(a){if(Ext.isString(a)){a=(a=="separator"||a=="-")?new Ext.menu.Separator():new Ext.menu.TextItem(a);this.applyDefaults(a)}else{if(Ext.isObject(a)){a=this.getMenuItem(a)}else{if(a.tagName||a.el){a=new Ext.BoxComponent({el:a})}}}return a},applyDefaults:function(b){if(!Ext.isString(b)){b=Ext.menu.Menu.superclass.applyDefaults.call(this,b);var a=this.internalDefaults;if(a){if(b.events){Ext.applyIf(b.initialConfig,a);Ext.apply(b,a)}else{Ext.applyIf(b,a)}}}return b},getMenuItem:function(a){if(!a.isXType){if(!a.xtype&&Ext.isBoolean(a.checked)){return new Ext.menu.CheckItem(a)}return Ext.create(a,this.defaultType)}return a},addSeparator:function(){return this.add(new Ext.menu.Separator())},addElement:function(a){return this.add(new Ext.menu.BaseItem({el:a}))},addItem:function(a){return this.add(a)},addMenuItem:function(a){return this.add(this.getMenuItem(a))},addText:function(a){return this.add(new Ext.menu.TextItem(a))},onDestroy:function(){Ext.EventManager.removeResizeListener(this.hide,this);var a=this.parentMenu;if(a&&a.activeChild==this){delete a.activeChild}delete this.parentMenu;Ext.menu.Menu.superclass.onDestroy.call(this);Ext.menu.MenuMgr.unregister(this);if(this.keyNav){this.keyNav.disable()}var b=this.scroller;if(b){Ext.destroy(b.topRepeater,b.bottomRepeater,b.top,b.bottom)}Ext.destroy(this.el,this.focusEl,this.ul)}});Ext.reg("menu",Ext.menu.Menu);Ext.menu.MenuNav=Ext.extend(Ext.KeyNav,function(){function a(d,c){if(!c.tryActivate(c.items.indexOf(c.activeItem)-1,-1)){c.tryActivate(c.items.length-1,-1)}}function b(d,c){if(!c.tryActivate(c.items.indexOf(c.activeItem)+1,1)){c.tryActivate(0,1)}}return{constructor:function(c){Ext.menu.MenuNav.superclass.constructor.call(this,c.el);this.scope=this.menu=c},doRelay:function(g,d){var c=g.getKey();if(this.menu.activeItem&&this.menu.activeItem.isFormField&&c!=g.TAB){return false}if(!this.menu.activeItem&&g.isNavKeyPress()&&c!=g.SPACE&&c!=g.RETURN){this.menu.tryActivate(0,1);return false}return d.call(this.scope||this,g,this.menu)},tab:function(d,c){d.stopEvent();if(d.shiftKey){a(d,c)}else{b(d,c)}},up:a,down:b,right:function(d,c){if(c.activeItem){c.activeItem.expandMenu(true)}},left:function(d,c){c.hide();if(c.parentMenu&&c.parentMenu.activeItem){c.parentMenu.activeItem.activate()}},enter:function(d,c){if(c.activeItem){d.stopPropagation();c.activeItem.onClick(d);c.fireEvent("click",this,c.activeItem);return true}}}}());Ext.menu.MenuMgr=function(){var g,d,c={},a=false,l=new Date();function n(){g={};d=new Ext.util.MixedCollection();Ext.getDoc().addKeyListener(27,function(){if(d.length>0){i()}})}function i(){if(d&&d.length>0){var o=d.clone();o.each(function(p){p.hide()});return true}return false}function e(o){d.remove(o);if(d.length<1){Ext.getDoc().un("mousedown",m);a=false}}function k(o){var p=d.last();l=new Date();d.add(o);if(!a){Ext.getDoc().on("mousedown",m);a=true}if(o.parentMenu){o.getEl().setZIndex(parseInt(o.parentMenu.getEl().getStyle("z-index"),10)+3);o.parentMenu.activeChild=o}else{if(p&&!p.isDestroyed&&p.isVisible()){o.getEl().setZIndex(parseInt(p.getEl().getStyle("z-index"),10)+3)}}}function b(o){if(o.activeChild){o.activeChild.hide()}if(o.autoHideTimer){clearTimeout(o.autoHideTimer);delete o.autoHideTimer}}function h(o){var p=o.parentMenu;if(!p&&!o.allowOtherMenus){i()}else{if(p&&p.activeChild){p.activeChild.hide()}}}function m(o){if(l.getElapsed()>50&&d.length>0&&!o.getTarget(".x-menu")){i()}}return{hideAll:function(){return i()},register:function(o){if(!g){n()}g[o.id]=o;o.on({beforehide:b,hide:e,beforeshow:h,show:k})},get:function(o){if(typeof o=="string"){if(!g){return null}return g[o]}else{if(o.events){return o}else{if(typeof o.length=="number"){return new Ext.menu.Menu({items:o})}else{return Ext.create(o,"menu")}}}},unregister:function(o){delete g[o.id];o.un("beforehide",b);o.un("hide",e);o.un("beforeshow",h);o.un("show",k)},registerCheckable:function(o){var p=o.group;if(p){if(!c[p]){c[p]=[]}c[p].push(o)}},unregisterCheckable:function(o){var p=o.group;if(p){c[p].remove(o)}},onCheckChange:function(q,r){if(q.group&&r){var t=c[q.group],p=0,o=t.length,s;for(;p<o;p++){s=t[p];if(s!=q){s.setChecked(false)}}}},getCheckedItem:function(q){var r=c[q];if(r){for(var p=0,o=r.length;p<o;p++){if(r[p].checked){return r[p]}}}return null},setCheckedItem:function(q,s){var r=c[q];if(r){for(var p=0,o=r.length;p<o;p++){if(r[p].id==s){r[p].setChecked(true)}}}return null}}}();Ext.menu.BaseItem=Ext.extend(Ext.Component,{canActivate:false,activeClass:"x-menu-item-active",hideOnClick:true,clickHideDelay:1,ctype:"Ext.menu.BaseItem",actionMode:"container",initComponent:function(){Ext.menu.BaseItem.superclass.initComponent.call(this);this.addEvents("click","activate","deactivate");if(this.handler){this.on("click",this.handler,this.scope)}},onRender:function(b,a){Ext.menu.BaseItem.superclass.onRender.apply(this,arguments);if(this.ownerCt&&this.ownerCt instanceof Ext.menu.Menu){this.parentMenu=this.ownerCt}else{this.container.addClass("x-menu-list-item");this.mon(this.el,{scope:this,click:this.onClick,mouseenter:this.activate,mouseleave:this.deactivate})}},setHandler:function(b,a){if(this.handler){this.un("click",this.handler,this.scope)}this.on("click",this.handler=b,this.scope=a)},onClick:function(a){if(!this.disabled&&this.fireEvent("click",this,a)!==false&&(this.parentMenu&&this.parentMenu.fireEvent("itemclick",this,a)!==false)){this.handleClick(a)}else{a.stopEvent()}},activate:function(){if(this.disabled){return false}var a=this.container;a.addClass(this.activeClass);this.region=a.getRegion().adjust(2,2,-2,-2);this.fireEvent("activate",this);return true},deactivate:function(){this.container.removeClass(this.activeClass);this.fireEvent("deactivate",this)},shouldDeactivate:function(a){return !this.region||!this.region.contains(a.getPoint())},handleClick:function(b){var a=this.parentMenu;if(this.hideOnClick){if(a.floating){a.hide.defer(this.clickHideDelay,a,[true])}else{a.deactivateActive()}}},expandMenu:Ext.emptyFn,hideMenu:Ext.emptyFn});Ext.reg("menubaseitem",Ext.menu.BaseItem);Ext.menu.TextItem=Ext.extend(Ext.menu.BaseItem,{hideOnClick:false,itemCls:"x-menu-text",constructor:function(a){if(typeof a=="string"){a={text:a}}Ext.menu.TextItem.superclass.constructor.call(this,a)},onRender:function(){var a=document.createElement("span");a.className=this.itemCls;a.innerHTML=this.text;this.el=a;Ext.menu.TextItem.superclass.onRender.apply(this,arguments)}});Ext.reg("menutextitem",Ext.menu.TextItem);Ext.menu.Separator=Ext.extend(Ext.menu.BaseItem,{itemCls:"x-menu-sep",hideOnClick:false,activeClass:"",onRender:function(a){var b=document.createElement("span");b.className=this.itemCls;b.innerHTML=" ";this.el=b;a.addClass("x-menu-sep-li");Ext.menu.Separator.superclass.onRender.apply(this,arguments)}});Ext.reg("menuseparator",Ext.menu.Separator);Ext.menu.Item=Ext.extend(Ext.menu.BaseItem,{itemCls:"x-menu-item",canActivate:true,showDelay:200,altText:"",hideDelay:200,ctype:"Ext.menu.Item",initComponent:function(){Ext.menu.Item.superclass.initComponent.call(this);if(this.menu){this.menu=Ext.menu.MenuMgr.get(this.menu);this.menu.ownerCt=this}},onRender:function(d,b){if(!this.itemTpl){this.itemTpl=Ext.menu.Item.prototype.itemTpl=new Ext.XTemplate('<a id="{id}" class="{cls}" hidefocus="true" unselectable="on" href="{href}"','<tpl if="hrefTarget">',' target="{hrefTarget}"',"</tpl>",">",'<img alt="{altText}" src="{icon}" class="x-menu-item-icon {iconCls}"/>','<span class="x-menu-item-text">{text}</span>',"</a>")}var c=this.getTemplateArgs();this.el=b?this.itemTpl.insertBefore(b,c,true):this.itemTpl.append(d,c,true);this.iconEl=this.el.child("img.x-menu-item-icon");this.textEl=this.el.child(".x-menu-item-text");if(!this.href){this.mon(this.el,"click",Ext.emptyFn,null,{preventDefault:true})}Ext.menu.Item.superclass.onRender.call(this,d,b)},getTemplateArgs:function(){return{id:this.id,cls:this.itemCls+(this.menu?" x-menu-item-arrow":"")+(this.cls?" "+this.cls:""),href:this.href||"#",hrefTarget:this.hrefTarget,icon:this.icon||Ext.BLANK_IMAGE_URL,iconCls:this.iconCls||"",text:this.itemText||this.text||" ",altText:this.altText||""}},setText:function(a){this.text=a||" ";if(this.rendered){this.textEl.update(this.text);this.parentMenu.layout.doAutoSize()}},setIconClass:function(a){var b=this.iconCls;this.iconCls=a;if(this.rendered){this.iconEl.replaceClass(b,this.iconCls)}},beforeDestroy:function(){if(this.menu){delete this.menu.ownerCt;this.menu.destroy()}Ext.menu.Item.superclass.beforeDestroy.call(this)},handleClick:function(a){if(!this.href){a.stopEvent()}Ext.menu.Item.superclass.handleClick.apply(this,arguments)},activate:function(a){if(Ext.menu.Item.superclass.activate.apply(this,arguments)){this.focus();if(a){this.expandMenu()}}return true},shouldDeactivate:function(a){if(Ext.menu.Item.superclass.shouldDeactivate.call(this,a)){if(this.menu&&this.menu.isVisible()){return !this.menu.getEl().getRegion().contains(a.getPoint())}return true}return false},deactivate:function(){Ext.menu.Item.superclass.deactivate.apply(this,arguments);this.hideMenu()},expandMenu:function(a){if(!this.disabled&&this.menu){clearTimeout(this.hideTimer);delete this.hideTimer;if(!this.menu.isVisible()&&!this.showTimer){this.showTimer=this.deferExpand.defer(this.showDelay,this,[a])}else{if(this.menu.isVisible()&&a){this.menu.tryActivate(0,1)}}}},deferExpand:function(a){delete this.showTimer;this.menu.show(this.container,this.parentMenu.subMenuAlign||"tl-tr?",this.parentMenu);if(a){this.menu.tryActivate(0,1)}},hideMenu:function(){clearTimeout(this.showTimer);delete this.showTimer;if(!this.hideTimer&&this.menu&&this.menu.isVisible()){this.hideTimer=this.deferHide.defer(this.hideDelay,this)}},deferHide:function(){delete this.hideTimer;if(this.menu.over){this.parentMenu.setActiveItem(this,false)}else{this.menu.hide()}}});Ext.reg("menuitem",Ext.menu.Item);Ext.menu.CheckItem=Ext.extend(Ext.menu.Item,{itemCls:"x-menu-item x-menu-check-item",groupClass:"x-menu-group-item",checked:false,ctype:"Ext.menu.CheckItem",initComponent:function(){Ext.menu.CheckItem.superclass.initComponent.call(this);this.addEvents("beforecheckchange","checkchange");if(this.checkHandler){this.on("checkchange",this.checkHandler,this.scope)}Ext.menu.MenuMgr.registerCheckable(this)},onRender:function(a){Ext.menu.CheckItem.superclass.onRender.apply(this,arguments);if(this.group){this.el.addClass(this.groupClass)}if(this.checked){this.checked=false;this.setChecked(true,true)}},destroy:function(){Ext.menu.MenuMgr.unregisterCheckable(this);Ext.menu.CheckItem.superclass.destroy.apply(this,arguments)},setChecked:function(b,a){var c=a===true;if(this.checked!=b&&(c||this.fireEvent("beforecheckchange",this,b)!==false)){Ext.menu.MenuMgr.onCheckChange(this,b);if(this.container){this.container[b?"addClass":"removeClass"]("x-menu-item-checked")}this.checked=b;if(!c){this.fireEvent("checkchange",this,b)}}},handleClick:function(a){if(!this.disabled&&!(this.checked&&this.group)){this.setChecked(!this.checked)}Ext.menu.CheckItem.superclass.handleClick.apply(this,arguments)}});Ext.reg("menucheckitem",Ext.menu.CheckItem);Ext.menu.DateMenu=Ext.extend(Ext.menu.Menu,{enableScrolling:false,hideOnClick:true,pickerId:null,cls:"x-date-menu",initComponent:function(){this.on("beforeshow",this.onBeforeShow,this);if(this.strict=(Ext.isIE7&&Ext.isStrict)){this.on("show",this.onShow,this,{single:true,delay:20})}Ext.apply(this,{plain:true,showSeparator:false,items:this.picker=new Ext.DatePicker(Ext.applyIf({internalRender:this.strict||!Ext.isIE,ctCls:"x-menu-date-item",id:this.pickerId},this.initialConfig))});this.picker.purgeListeners();Ext.menu.DateMenu.superclass.initComponent.call(this);this.relayEvents(this.picker,["select"]);this.on("show",this.picker.focus,this.picker);this.on("select",this.menuHide,this);if(this.handler){this.on("select",this.handler,this.scope||this)}},menuHide:function(){if(this.hideOnClick){this.hide(true)}},onBeforeShow:function(){if(this.picker){this.picker.hideMonthPicker(true)}},onShow:function(){var a=this.picker.getEl();a.setWidth(a.getWidth())}});Ext.reg("datemenu",Ext.menu.DateMenu);Ext.menu.ColorMenu=Ext.extend(Ext.menu.Menu,{enableScrolling:false,hideOnClick:true,cls:"x-color-menu",paletteId:null,initComponent:function(){Ext.apply(this,{plain:true,showSeparator:false,items:this.palette=new Ext.ColorPalette(Ext.applyIf({id:this.paletteId},this.initialConfig))});this.palette.purgeListeners();Ext.menu.ColorMenu.superclass.initComponent.call(this);this.relayEvents(this.palette,["select"]);this.on("select",this.menuHide,this);if(this.handler){this.on("select",this.handler,this.scope||this)}},menuHide:function(){if(this.hideOnClick){this.hide(true)}}});Ext.reg("colormenu",Ext.menu.ColorMenu);Ext.form.Field=Ext.extend(Ext.BoxComponent,{invalidClass:"x-form-invalid",invalidText:"The value in this field is invalid",focusClass:"x-form-focus",validationEvent:"keyup",validateOnBlur:true,validationDelay:250,defaultAutoCreate:{tag:"input",type:"text",size:"20",autocomplete:"off"},fieldClass:"x-form-field",msgTarget:"qtip",msgFx:"normal",readOnly:false,disabled:false,submitValue:true,isFormField:true,msgDisplay:"",hasFocus:false,initComponent:function(){Ext.form.Field.superclass.initComponent.call(this);this.addEvents("focus","blur","specialkey","change","invalid","valid")},getName:function(){return this.rendered&&this.el.dom.name?this.el.dom.name:this.name||this.id||""},onRender:function(c,a){if(!this.el){var b=this.getAutoCreate();if(!b.name){b.name=this.name||this.id}if(this.inputType){b.type=this.inputType}this.autoEl=b}Ext.form.Field.superclass.onRender.call(this,c,a);if(this.submitValue===false){this.el.dom.removeAttribute("name")}var d=this.el.dom.type;if(d){if(d=="password"){d="text"}this.el.addClass("x-form-"+d)}if(this.readOnly){this.setReadOnly(true)}if(this.tabIndex!==undefined){this.el.dom.setAttribute("tabIndex",this.tabIndex)}this.el.addClass([this.fieldClass,this.cls])},getItemCt:function(){return this.itemCt},initValue:function(){if(this.value!==undefined){this.setValue(this.value)}else{if(!Ext.isEmpty(this.el.dom.value)&&this.el.dom.value!=this.emptyText){this.setValue(this.el.dom.value)}}this.originalValue=this.getValue()},isDirty:function(){if(this.disabled||!this.rendered){return false}return String(this.getValue())!==String(this.originalValue)},setReadOnly:function(a){if(this.rendered){this.el.dom.readOnly=a}this.readOnly=a},afterRender:function(){Ext.form.Field.superclass.afterRender.call(this);this.initEvents();this.initValue()},fireKey:function(a){if(a.isSpecialKey()){this.fireEvent("specialkey",this,a)}},reset:function(){this.setValue(this.originalValue);this.clearInvalid()},initEvents:function(){this.mon(this.el,Ext.EventManager.getKeyEvent(),this.fireKey,this);this.mon(this.el,"focus",this.onFocus,this);this.mon(this.el,"blur",this.onBlur,this,this.inEditor?{buffer:10}:null)},preFocus:Ext.emptyFn,onFocus:function(){this.preFocus();if(this.focusClass){this.el.addClass(this.focusClass)}if(!this.hasFocus){this.hasFocus=true;this.startValue=this.getValue();this.fireEvent("focus",this)}},beforeBlur:Ext.emptyFn,onBlur:function(){this.beforeBlur();if(this.focusClass){this.el.removeClass(this.focusClass)}this.hasFocus=false;if(this.validationEvent!==false&&(this.validateOnBlur||this.validationEvent=="blur")){this.validate()}var a=this.getValue();if(String(a)!==String(this.startValue)){this.fireEvent("change",this,a,this.startValue)}this.fireEvent("blur",this);this.postBlur()},postBlur:Ext.emptyFn,isValid:function(a){if(this.disabled){return true}var c=this.preventMark;this.preventMark=a===true;var b=this.validateValue(this.processValue(this.getRawValue()));this.preventMark=c;return b},validate:function(){if(this.disabled||this.validateValue(this.processValue(this.getRawValue()))){this.clearInvalid();return true}return false},processValue:function(a){return a},validateValue:function(b){var a=this.getErrors(b)[0];if(a==undefined){return true}else{this.markInvalid(a);return false}},getErrors:function(){return[]},getActiveError:function(){return this.activeError||""},markInvalid:function(c){if(this.rendered&&!this.preventMark){c=c||this.invalidText;var a=this.getMessageHandler();if(a){a.mark(this,c)}else{if(this.msgTarget){this.el.addClass(this.invalidClass);var b=Ext.getDom(this.msgTarget);if(b){b.innerHTML=c;b.style.display=this.msgDisplay}}}}this.setActiveError(c)},clearInvalid:function(){if(this.rendered&&!this.preventMark){this.el.removeClass(this.invalidClass);var a=this.getMessageHandler();if(a){a.clear(this)}else{if(this.msgTarget){this.el.removeClass(this.invalidClass);var b=Ext.getDom(this.msgTarget);if(b){b.innerHTML="";b.style.display="none"}}}}this.unsetActiveError()},setActiveError:function(b,a){this.activeError=b;if(a!==true){this.fireEvent("invalid",this,b)}},unsetActiveError:function(a){delete this.activeError;if(a!==true){this.fireEvent("valid",this)}},getMessageHandler:function(){return Ext.form.MessageTargets[this.msgTarget]},getErrorCt:function(){return this.el.findParent(".x-form-element",5,true)||this.el.findParent(".x-form-field-wrap",5,true)},alignErrorEl:function(){this.errorEl.setWidth(this.getErrorCt().getWidth(true)-20)},alignErrorIcon:function(){this.errorIcon.alignTo(this.el,"tl-tr",[2,0])},getRawValue:function(){var a=this.rendered?this.el.getValue():Ext.value(this.value,"");if(a===this.emptyText){a=""}return a},getValue:function(){if(!this.rendered){return this.value}var a=this.el.getValue();if(a===this.emptyText||a===undefined){a=""}return a},setRawValue:function(a){return this.rendered?(this.el.dom.value=(Ext.isEmpty(a)?"":a)):""},setValue:function(a){this.value=a;if(this.rendered){this.el.dom.value=(Ext.isEmpty(a)?"":a);this.validate()}return this},append:function(a){this.setValue([this.getValue(),a].join(""))}});Ext.form.MessageTargets={qtip:{mark:function(a,b){a.el.addClass(a.invalidClass);a.el.dom.qtip=b;a.el.dom.qclass="x-form-invalid-tip";if(Ext.QuickTips){Ext.QuickTips.enable()}},clear:function(a){a.el.removeClass(a.invalidClass);a.el.dom.qtip=""}},title:{mark:function(a,b){a.el.addClass(a.invalidClass);a.el.dom.title=b},clear:function(a){a.el.dom.title=""}},under:{mark:function(b,c){b.el.addClass(b.invalidClass);if(!b.errorEl){var a=b.getErrorCt();if(!a){b.el.dom.title=c;return}b.errorEl=a.createChild({cls:"x-form-invalid-msg"});b.on("resize",b.alignErrorEl,b);b.on("destroy",function(){Ext.destroy(this.errorEl)},b)}b.alignErrorEl();b.errorEl.update(c);Ext.form.Field.msgFx[b.msgFx].show(b.errorEl,b)},clear:function(a){a.el.removeClass(a.invalidClass);if(a.errorEl){Ext.form.Field.msgFx[a.msgFx].hide(a.errorEl,a)}else{a.el.dom.title=""}}},side:{mark:function(b,c){b.el.addClass(b.invalidClass);if(!b.errorIcon){var a=b.getErrorCt();if(!a){b.el.dom.title=c;return}b.errorIcon=a.createChild({cls:"x-form-invalid-icon"});if(b.ownerCt){b.ownerCt.on("afterlayout",b.alignErrorIcon,b);b.ownerCt.on("expand",b.alignErrorIcon,b)}b.on("resize",b.alignErrorIcon,b);b.on("destroy",function(){Ext.destroy(this.errorIcon)},b)}b.alignErrorIcon();b.errorIcon.dom.qtip=c;b.errorIcon.dom.qclass="x-form-invalid-tip";b.errorIcon.show()},clear:function(a){a.el.removeClass(a.invalidClass);if(a.errorIcon){a.errorIcon.dom.qtip="";a.errorIcon.hide()}else{a.el.dom.title=""}}}};Ext.form.Field.msgFx={normal:{show:function(a,b){a.setDisplayed("block")},hide:function(a,b){a.setDisplayed(false).update("")}},slide:{show:function(a,b){a.slideIn("t",{stopFx:true})},hide:function(a,b){a.slideOut("t",{stopFx:true,useDisplay:true})}},slideRight:{show:function(a,b){a.fixDisplay();a.alignTo(b.el,"tl-tr");a.slideIn("l",{stopFx:true})},hide:function(a,b){a.slideOut("l",{stopFx:true,useDisplay:true})}}};Ext.reg("field",Ext.form.Field);Ext.form.TextField=Ext.extend(Ext.form.Field,{grow:false,growMin:30,growMax:800,vtype:null,maskRe:null,disableKeyFilter:false,allowBlank:true,minLength:0,maxLength:Number.MAX_VALUE,minLengthText:"The minimum length for this field is {0}",maxLengthText:"The maximum length for this field is {0}",selectOnFocus:false,blankText:"This field is required",validator:null,regex:null,regexText:"",emptyText:null,emptyClass:"x-form-empty-field",initComponent:function(){Ext.form.TextField.superclass.initComponent.call(this);this.addEvents("autosize","keydown","keyup","keypress")},initEvents:function(){Ext.form.TextField.superclass.initEvents.call(this);if(this.validationEvent=="keyup"){this.validationTask=new Ext.util.DelayedTask(this.validate,this);this.mon(this.el,"keyup",this.filterValidation,this)}else{if(this.validationEvent!==false&&this.validationEvent!="blur"){this.mon(this.el,this.validationEvent,this.validate,this,{buffer:this.validationDelay})}}if(this.selectOnFocus||this.emptyText){this.mon(this.el,"mousedown",this.onMouseDown,this);if(this.emptyText){this.applyEmptyText()}}if(this.maskRe||(this.vtype&&this.disableKeyFilter!==true&&(this.maskRe=Ext.form.VTypes[this.vtype+"Mask"]))){this.mon(this.el,"keypress",this.filterKeys,this)}if(this.grow){this.mon(this.el,"keyup",this.onKeyUpBuffered,this,{buffer:50});this.mon(this.el,"click",this.autoSize,this)}if(this.enableKeyEvents){this.mon(this.el,{scope:this,keyup:this.onKeyUp,keydown:this.onKeyDown,keypress:this.onKeyPress})}},onMouseDown:function(a){if(!this.hasFocus){this.mon(this.el,"mouseup",Ext.emptyFn,this,{single:true,preventDefault:true})}},processValue:function(a){if(this.stripCharsRe){var b=a.replace(this.stripCharsRe,"");if(b!==a){this.setRawValue(b);return b}}return a},filterValidation:function(a){if(!a.isNavKeyPress()){this.validationTask.delay(this.validationDelay)}},onDisable:function(){Ext.form.TextField.superclass.onDisable.call(this);if(Ext.isIE){this.el.dom.unselectable="on"}},onEnable:function(){Ext.form.TextField.superclass.onEnable.call(this);if(Ext.isIE){this.el.dom.unselectable=""}},onKeyUpBuffered:function(a){if(this.doAutoSize(a)){this.autoSize()}},doAutoSize:function(a){return !a.isNavKeyPress()},onKeyUp:function(a){this.fireEvent("keyup",this,a)},onKeyDown:function(a){this.fireEvent("keydown",this,a)},onKeyPress:function(a){this.fireEvent("keypress",this,a)},reset:function(){Ext.form.TextField.superclass.reset.call(this);this.applyEmptyText()},applyEmptyText:function(){if(this.rendered&&this.emptyText&&this.getRawValue().length<1&&!this.hasFocus){this.setRawValue(this.emptyText);this.el.addClass(this.emptyClass)}},preFocus:function(){var a=this.el,b;if(this.emptyText){if(a.dom.value==this.emptyText){this.setRawValue("");b=true}a.removeClass(this.emptyClass)}if(this.selectOnFocus||b){a.dom.select()}},postBlur:function(){this.applyEmptyText()},filterKeys:function(b){if(b.ctrlKey){return}var a=b.getKey();if(Ext.isGecko&&(b.isNavKeyPress()||a==b.BACKSPACE||(a==b.DELETE&&b.button==-1))){return}var c=String.fromCharCode(b.getCharCode());if(!Ext.isGecko&&b.isSpecialKey()&&!c){return}if(!this.maskRe.test(c)){b.stopEvent()}},setValue:function(a){if(this.emptyText&&this.el&&!Ext.isEmpty(a)){this.el.removeClass(this.emptyClass)}Ext.form.TextField.superclass.setValue.apply(this,arguments);this.applyEmptyText();this.autoSize();return this},getErrors:function(a){var d=Ext.form.TextField.superclass.getErrors.apply(this,arguments);a=Ext.isDefined(a)?a:this.processValue(this.getRawValue());if(Ext.isFunction(this.validator)){var c=this.validator(a);if(c!==true){d.push(c)}}if(a.length<1||a===this.emptyText){if(this.allowBlank){return d}else{d.push(this.blankText)}}if(!this.allowBlank&&(a.length<1||a===this.emptyText)){d.push(this.blankText)}if(a.length<this.minLength){d.push(String.format(this.minLengthText,this.minLength))}if(a.length>this.maxLength){d.push(String.format(this.maxLengthText,this.maxLength))}if(this.vtype){var b=Ext.form.VTypes;if(!b[this.vtype](a,this)){d.push(this.vtypeText||b[this.vtype+"Text"])}}if(this.regex&&!this.regex.test(a)){d.push(this.regexText)}return d},selectText:function(h,a){var c=this.getRawValue();var e=false;if(c.length>0){h=h===undefined?0:h;a=a===undefined?c.length:a;var g=this.el.dom;if(g.setSelectionRange){g.setSelectionRange(h,a)}else{if(g.createTextRange){var b=g.createTextRange();b.moveStart("character",h);b.moveEnd("character",a-c.length);b.select()}}e=Ext.isGecko||Ext.isOpera}else{e=true}if(e){this.focus()}},autoSize:function(){if(!this.grow||!this.rendered){return}if(!this.metrics){this.metrics=Ext.util.TextMetrics.createInstance(this.el)}var c=this.el;var b=c.dom.value;var e=document.createElement("div");e.appendChild(document.createTextNode(b));b=e.innerHTML;Ext.removeNode(e);e=null;b+=" ";var a=Math.min(this.growMax,Math.max(this.metrics.getWidth(b)+10,this.growMin));this.el.setWidth(a);this.fireEvent("autosize",this,a)},onDestroy:function(){if(this.validationTask){this.validationTask.cancel();this.validationTask=null}Ext.form.TextField.superclass.onDestroy.call(this)}});Ext.reg("textfield",Ext.form.TextField);Ext.form.TriggerField=Ext.extend(Ext.form.TextField,{defaultAutoCreate:{tag:"input",type:"text",size:"16",autocomplete:"off"},hideTrigger:false,editable:true,readOnly:false,wrapFocusClass:"x-trigger-wrap-focus",autoSize:Ext.emptyFn,monitorTab:true,deferHeight:true,mimicing:false,actionMode:"wrap",defaultTriggerWidth:17,onResize:function(a,c){Ext.form.TriggerField.superclass.onResize.call(this,a,c);var b=this.getTriggerWidth();if(Ext.isNumber(a)){this.el.setWidth(a-b)}this.wrap.setWidth(this.el.getWidth()+b)},getTriggerWidth:function(){var a=this.trigger.getWidth();if(!this.hideTrigger&&!this.readOnly&&a===0){a=this.defaultTriggerWidth}return a},alignErrorIcon:function(){if(this.wrap){this.errorIcon.alignTo(this.wrap,"tl-tr",[2,0])}},onRender:function(b,a){this.doc=Ext.isIE?Ext.getBody():Ext.getDoc();Ext.form.TriggerField.superclass.onRender.call(this,b,a);this.wrap=this.el.wrap({cls:"x-form-field-wrap x-form-field-trigger-wrap"});this.trigger=this.wrap.createChild(this.triggerConfig||{tag:"img",src:Ext.BLANK_IMAGE_URL,alt:"",cls:"x-form-trigger "+this.triggerClass});this.initTrigger();if(!this.width){this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth())}this.resizeEl=this.positionEl=this.wrap},getWidth:function(){return(this.el.getWidth()+this.trigger.getWidth())},updateEditState:function(){if(this.rendered){if(this.readOnly){this.el.dom.readOnly=true;this.el.addClass("x-trigger-noedit");this.mun(this.el,"click",this.onTriggerClick,this);this.trigger.setDisplayed(false)}else{if(!this.editable){this.el.dom.readOnly=true;this.el.addClass("x-trigger-noedit");this.mon(this.el,"click",this.onTriggerClick,this)}else{this.el.dom.readOnly=false;this.el.removeClass("x-trigger-noedit");this.mun(this.el,"click",this.onTriggerClick,this)}this.trigger.setDisplayed(!this.hideTrigger)}this.onResize(this.width||this.wrap.getWidth())}},setHideTrigger:function(a){if(a!=this.hideTrigger){this.hideTrigger=a;this.updateEditState()}},setEditable:function(a){if(a!=this.editable){this.editable=a;this.updateEditState()}},setReadOnly:function(a){if(a!=this.readOnly){this.readOnly=a;this.updateEditState()}},afterRender:function(){Ext.form.TriggerField.superclass.afterRender.call(this);this.updateEditState()},initTrigger:function(){this.mon(this.trigger,"click",this.onTriggerClick,this,{preventDefault:true});this.trigger.addClassOnOver("x-form-trigger-over");this.trigger.addClassOnClick("x-form-trigger-click")},onDestroy:function(){Ext.destroy(this.trigger,this.wrap);if(this.mimicing){this.doc.un("mousedown",this.mimicBlur,this)}delete this.doc;Ext.form.TriggerField.superclass.onDestroy.call(this)},onFocus:function(){Ext.form.TriggerField.superclass.onFocus.call(this);if(!this.mimicing){this.wrap.addClass(this.wrapFocusClass);this.mimicing=true;this.doc.on("mousedown",this.mimicBlur,this,{delay:10});if(this.monitorTab){this.on("specialkey",this.checkTab,this)}}},checkTab:function(a,b){if(b.getKey()==b.TAB){this.triggerBlur()}},onBlur:Ext.emptyFn,mimicBlur:function(a){if(!this.isDestroyed&&!this.wrap.contains(a.target)&&this.validateBlur(a)){this.triggerBlur()}},triggerBlur:function(){this.mimicing=false;this.doc.un("mousedown",this.mimicBlur,this);if(this.monitorTab&&this.el){this.un("specialkey",this.checkTab,this)}Ext.form.TriggerField.superclass.onBlur.call(this);if(this.wrap){this.wrap.removeClass(this.wrapFocusClass)}},beforeBlur:Ext.emptyFn,validateBlur:function(a){return true},onTriggerClick:Ext.emptyFn});Ext.form.TwinTriggerField=Ext.extend(Ext.form.TriggerField,{initComponent:function(){Ext.form.TwinTriggerField.superclass.initComponent.call(this);this.triggerConfig={tag:"span",cls:"x-form-twin-triggers",cn:[{tag:"img",src:Ext.BLANK_IMAGE_URL,alt:"",cls:"x-form-trigger "+this.trigger1Class},{tag:"img",src:Ext.BLANK_IMAGE_URL,alt:"",cls:"x-form-trigger "+this.trigger2Class}]}},getTrigger:function(a){return this.triggers[a]},afterRender:function(){Ext.form.TwinTriggerField.superclass.afterRender.call(this);var c=this.triggers,b=0,a=c.length;for(;b<a;++b){if(this["hideTrigger"+(b+1)]){c[b].hide()}}},initTrigger:function(){var a=this.trigger.select(".x-form-trigger",true),b=this;a.each(function(d,g,c){var e="Trigger"+(c+1);d.hide=function(){var h=b.wrap.getWidth();this.dom.style.display="none";b.el.setWidth(h-b.trigger.getWidth());b["hidden"+e]=true};d.show=function(){var h=b.wrap.getWidth();this.dom.style.display="";b.el.setWidth(h-b.trigger.getWidth());b["hidden"+e]=false};this.mon(d,"click",this["on"+e+"Click"],this,{preventDefault:true});d.addClassOnOver("x-form-trigger-over");d.addClassOnClick("x-form-trigger-click")},this);this.triggers=a.elements},getTriggerWidth:function(){var a=0;Ext.each(this.triggers,function(d,c){var e="Trigger"+(c+1),b=d.getWidth();if(b===0&&!this["hidden"+e]){a+=this.defaultTriggerWidth}else{a+=b}},this);return a},onDestroy:function(){Ext.destroy(this.triggers);Ext.form.TwinTriggerField.superclass.onDestroy.call(this)},onTrigger1Click:Ext.emptyFn,onTrigger2Click:Ext.emptyFn});Ext.reg("trigger",Ext.form.TriggerField);Ext.form.TextArea=Ext.extend(Ext.form.TextField,{growMin:60,growMax:1000,growAppend:" \n ",enterIsSpecial:false,preventScrollbars:false,onRender:function(b,a){if(!this.el){this.defaultAutoCreate={tag:"textarea",style:"width:100px;height:60px;",autocomplete:"off"}}Ext.form.TextArea.superclass.onRender.call(this,b,a);if(this.grow){this.textSizeEl=Ext.DomHelper.append(document.body,{tag:"pre",cls:"x-form-grow-sizer"});if(this.preventScrollbars){this.el.setStyle("overflow","hidden")}this.el.setHeight(this.growMin)}},onDestroy:function(){Ext.removeNode(this.textSizeEl);Ext.form.TextArea.superclass.onDestroy.call(this)},fireKey:function(a){if(a.isSpecialKey()&&(this.enterIsSpecial||(a.getKey()!=a.ENTER||a.hasModifier()))){this.fireEvent("specialkey",this,a)}},doAutoSize:function(a){return !a.isNavKeyPress()||a.getKey()==a.ENTER},filterValidation:function(a){if(!a.isNavKeyPress()||(!this.enterIsSpecial&&a.keyCode==a.ENTER)){this.validationTask.delay(this.validationDelay)}},autoSize:function(){if(!this.grow||!this.textSizeEl){return}var c=this.el,a=Ext.util.Format.htmlEncode(c.dom.value),d=this.textSizeEl,b;Ext.fly(d).setWidth(this.el.getWidth());if(a.length<1){a="  "}else{a+=this.growAppend;if(Ext.isIE){a=a.replace(/\n/g," <br />")}}d.innerHTML=a;b=Math.min(this.growMax,Math.max(d.offsetHeight,this.growMin));if(b!=this.lastHeight){this.lastHeight=b;this.el.setHeight(b);this.fireEvent("autosize",this,b)}}});Ext.reg("textarea",Ext.form.TextArea);Ext.form.NumberField=Ext.extend(Ext.form.TextField,{fieldClass:"x-form-field x-form-num-field",allowDecimals:true,decimalSeparator:".",decimalPrecision:2,allowNegative:true,minValue:Number.NEGATIVE_INFINITY,maxValue:Number.MAX_VALUE,minText:"The minimum value for this field is {0}",maxText:"The maximum value for this field is {0}",nanText:"{0} is not a valid number",baseChars:"0123456789",autoStripChars:false,initEvents:function(){var a=this.baseChars+"";if(this.allowDecimals){a+=this.decimalSeparator}if(this.allowNegative){a+="-"}a=Ext.escapeRe(a);this.maskRe=new RegExp("["+a+"]");if(this.autoStripChars){this.stripCharsRe=new RegExp("[^"+a+"]","gi")}Ext.form.NumberField.superclass.initEvents.call(this)},getErrors:function(b){var c=Ext.form.NumberField.superclass.getErrors.apply(this,arguments);b=Ext.isDefined(b)?b:this.processValue(this.getRawValue());if(b.length<1){return c}b=String(b).replace(this.decimalSeparator,".");if(isNaN(b)){c.push(String.format(this.nanText,b))}var a=this.parseValue(b);if(a<this.minValue){c.push(String.format(this.minText,this.minValue))}if(a>this.maxValue){c.push(String.format(this.maxText,this.maxValue))}return c},getValue:function(){return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this)))},setValue:function(a){a=this.fixPrecision(a);a=Ext.isNumber(a)?a:parseFloat(String(a).replace(this.decimalSeparator,"."));a=isNaN(a)?"":String(a).replace(".",this.decimalSeparator);return Ext.form.NumberField.superclass.setValue.call(this,a)},setMinValue:function(a){this.minValue=Ext.num(a,Number.NEGATIVE_INFINITY)},setMaxValue:function(a){this.maxValue=Ext.num(a,Number.MAX_VALUE)},parseValue:function(a){a=parseFloat(String(a).replace(this.decimalSeparator,"."));return isNaN(a)?"":a},fixPrecision:function(b){var a=isNaN(b);if(!this.allowDecimals||this.decimalPrecision==-1||a||!b){return a?"":b}return parseFloat(parseFloat(b).toFixed(this.decimalPrecision))},beforeBlur:function(){var a=this.parseValue(this.getRawValue());if(!Ext.isEmpty(a)){this.setValue(a)}}});Ext.reg("numberfield",Ext.form.NumberField);Ext.form.DateField=Ext.extend(Ext.form.TriggerField,{format:"m/d/Y",altFormats:"m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j",disabledDaysText:"Disabled",disabledDatesText:"Disabled",minText:"The date in this field must be equal to or after {0}",maxText:"The date in this field must be equal to or before {0}",invalidText:"{0} is not a valid date - it must be in the format {1}",triggerClass:"x-form-date-trigger",showToday:true,startDay:0,defaultAutoCreate:{tag:"input",type:"text",size:"10",autocomplete:"off"},initTime:"12",initTimeFormat:"H",safeParse:function(b,c){if(/[gGhH]/.test(c.replace(/(\\.)/g,""))){return Date.parseDate(b,c)}else{var a=Date.parseDate(b+" "+this.initTime,c+" "+this.initTimeFormat);if(a){return a.clearTime()}}},initComponent:function(){Ext.form.DateField.superclass.initComponent.call(this);this.addEvents("select");if(Ext.isString(this.minValue)){this.minValue=this.parseDate(this.minValue)}if(Ext.isString(this.maxValue)){this.maxValue=this.parseDate(this.maxValue)}this.disabledDatesRE=null;this.initDisabledDays()},initEvents:function(){Ext.form.DateField.superclass.initEvents.call(this);this.keyNav=new Ext.KeyNav(this.el,{down:function(a){this.onTriggerClick()},scope:this,forceKeyDown:true})},initDisabledDays:function(){if(this.disabledDates){var b=this.disabledDates,a=b.length-1,c="(?:";Ext.each(b,function(g,e){c+=Ext.isDate(g)?"^"+Ext.escapeRe(g.dateFormat(this.format))+"$":b[e];if(e!=a){c+="|"}},this);this.disabledDatesRE=new RegExp(c+")")}},setDisabledDates:function(a){this.disabledDates=a;this.initDisabledDays();if(this.menu){this.menu.picker.setDisabledDates(this.disabledDatesRE)}},setDisabledDays:function(a){this.disabledDays=a;if(this.menu){this.menu.picker.setDisabledDays(a)}},setMinValue:function(a){this.minValue=(Ext.isString(a)?this.parseDate(a):a);if(this.menu){this.menu.picker.setMinDate(this.minValue)}},setMaxValue:function(a){this.maxValue=(Ext.isString(a)?this.parseDate(a):a);if(this.menu){this.menu.picker.setMaxDate(this.maxValue)}},getErrors:function(e){var h=Ext.form.DateField.superclass.getErrors.apply(this,arguments);e=this.formatDate(e||this.processValue(this.getRawValue()));if(e.length<1){return h}var c=e;e=this.parseDate(e);if(!e){h.push(String.format(this.invalidText,c,this.format));return h}var g=e.getTime();if(this.minValue&&g<this.minValue.clearTime().getTime()){h.push(String.format(this.minText,this.formatDate(this.minValue)))}if(this.maxValue&&g>this.maxValue.clearTime().getTime()){h.push(String.format(this.maxText,this.formatDate(this.maxValue)))}if(this.disabledDays){var a=e.getDay();for(var b=0;b<this.disabledDays.length;b++){if(a===this.disabledDays[b]){h.push(this.disabledDaysText);break}}}var d=this.formatDate(e);if(this.disabledDatesRE&&this.disabledDatesRE.test(d)){h.push(String.format(this.disabledDatesText,d))}return h},validateBlur:function(){return !this.menu||!this.menu.isVisible()},getValue:function(){return this.parseDate(Ext.form.DateField.superclass.getValue.call(this))||""},setValue:function(a){return Ext.form.DateField.superclass.setValue.call(this,this.formatDate(this.parseDate(a)))},parseDate:function(g){if(!g||Ext.isDate(g)){return g}var b=this.safeParse(g,this.format),c=this.altFormats,e=this.altFormatsArray;if(!b&&c){e=e||c.split("|");for(var d=0,a=e.length;d<a&&!b;d++){b=this.safeParse(g,e[d])}}return b},onDestroy:function(){Ext.destroy(this.menu,this.keyNav);Ext.form.DateField.superclass.onDestroy.call(this)},formatDate:function(a){return Ext.isDate(a)?a.dateFormat(this.format):a},onTriggerClick:function(){if(this.disabled){return}if(this.menu==null){this.menu=new Ext.menu.DateMenu({hideOnClick:false,focusOnSelect:false})}this.onFocus();Ext.apply(this.menu.picker,{minDate:this.minValue,maxDate:this.maxValue,disabledDatesRE:this.disabledDatesRE,disabledDatesText:this.disabledDatesText,disabledDays:this.disabledDays,disabledDaysText:this.disabledDaysText,format:this.format,showToday:this.showToday,startDay:this.startDay,minText:String.format(this.minText,this.formatDate(this.minValue)),maxText:String.format(this.maxText,this.formatDate(this.maxValue))});this.menu.picker.setValue(this.getValue()||new Date());this.menu.show(this.el,"tl-bl?");this.menuEvents("on")},menuEvents:function(a){this.menu[a]("select",this.onSelect,this);this.menu[a]("hide",this.onMenuHide,this);this.menu[a]("show",this.onFocus,this)},onSelect:function(a,b){this.setValue(b);this.fireEvent("select",this,b);this.menu.hide()},onMenuHide:function(){this.focus(false,60);this.menuEvents("un")},beforeBlur:function(){var a=this.parseDate(this.getRawValue());if(a){this.setValue(a)}}});Ext.reg("datefield",Ext.form.DateField);Ext.form.DisplayField=Ext.extend(Ext.form.Field,{validationEvent:false,validateOnBlur:false,defaultAutoCreate:{tag:"div"},fieldClass:"x-form-display-field",htmlEncode:false,initEvents:Ext.emptyFn,isValid:function(){return true},validate:function(){return true},getRawValue:function(){var a=this.rendered?this.el.dom.innerHTML:Ext.value(this.value,"");if(a===this.emptyText){a=""}if(this.htmlEncode){a=Ext.util.Format.htmlDecode(a)}return a},getValue:function(){return this.getRawValue()},getName:function(){return this.name},setRawValue:function(a){if(this.htmlEncode){a=Ext.util.Format.htmlEncode(a)}return this.rendered?(this.el.dom.innerHTML=(Ext.isEmpty(a)?"":a)):(this.value=a)},setValue:function(a){this.setRawValue(a);return this}});Ext.reg("displayfield",Ext.form.DisplayField);Ext.form.ComboBox=Ext.extend(Ext.form.TriggerField,{defaultAutoCreate:{tag:"input",type:"text",size:"24",autocomplete:"off"},listClass:"",selectedClass:"x-combo-selected",listEmptyText:"",triggerClass:"x-form-arrow-trigger",shadow:"sides",listAlign:"tl-bl?",maxHeight:300,minHeight:90,triggerAction:"query",minChars:4,autoSelect:true,typeAhead:false,queryDelay:500,pageSize:0,selectOnFocus:false,queryParam:"query",loadingText:"Loading...",resizable:false,handleHeight:8,allQuery:"",mode:"remote",minListWidth:70,forceSelection:false,typeAheadDelay:250,lazyInit:true,clearFilterOnReset:true,submitValue:undefined,initComponent:function(){Ext.form.ComboBox.superclass.initComponent.call(this);this.addEvents("expand","collapse","beforeselect","select","beforequery");if(this.transform){var c=Ext.getDom(this.transform);if(!this.hiddenName){this.hiddenName=c.name}if(!this.store){this.mode="local";var k=[],e=c.options;for(var b=0,a=e.length;b<a;b++){var h=e[b],g=(h.hasAttribute?h.hasAttribute("value"):h.getAttributeNode("value").specified)?h.value:h.text;if(h.selected&&Ext.isEmpty(this.value,true)){this.value=g}k.push([g,h.text])}this.store=new Ext.data.ArrayStore({idIndex:0,fields:["value","text"],data:k,autoDestroy:true});this.valueField="value";this.displayField="text"}c.name=Ext.id();if(!this.lazyRender){this.target=true;this.el=Ext.DomHelper.insertBefore(c,this.autoCreate||this.defaultAutoCreate);this.render(this.el.parentNode,c)}Ext.removeNode(c)}else{if(this.store){this.store=Ext.StoreMgr.lookup(this.store);if(this.store.autoCreated){this.displayField=this.valueField="field1";if(!this.store.expandData){this.displayField="field2"}this.mode="local"}}}this.selectedIndex=-1;if(this.mode=="local"){if(!Ext.isDefined(this.initialConfig.queryDelay)){this.queryDelay=10}if(!Ext.isDefined(this.initialConfig.minChars)){this.minChars=0}}},onRender:function(b,a){if(this.hiddenName&&!Ext.isDefined(this.submitValue)){this.submitValue=false}Ext.form.ComboBox.superclass.onRender.call(this,b,a);if(this.hiddenName){this.hiddenField=this.el.insertSibling({tag:"input",type:"hidden",name:this.hiddenName,id:(this.hiddenId||Ext.id())},"before",true)}if(Ext.isGecko){this.el.dom.setAttribute("autocomplete","off")}if(!this.lazyInit){this.initList()}else{this.on("focus",this.initList,this,{single:true})}},initValue:function(){Ext.form.ComboBox.superclass.initValue.call(this);if(this.hiddenField){this.hiddenField.value=Ext.value(Ext.isDefined(this.hiddenValue)?this.hiddenValue:this.value,"")}},getParentZIndex:function(){var a;if(this.ownerCt){this.findParentBy(function(b){a=parseInt(b.getPositionEl().getStyle("z-index"),10);return !!a})}return a},getZIndex:function(b){b=b||Ext.getDom(this.getListParent()||Ext.getBody());var a=parseInt(Ext.fly(b).getStyle("z-index"),10);if(!a){a=this.getParentZIndex()}return(a||12000)+5},initList:function(){if(!this.list){var a="x-combo-list",c=Ext.getDom(this.getListParent()||Ext.getBody());this.list=new Ext.Layer({parentEl:c,shadow:this.shadow,cls:[a,this.listClass].join(" "),constrain:false,zindex:this.getZIndex(c)});var b=this.listWidth||Math.max(this.wrap.getWidth(),this.minListWidth);this.list.setSize(b,0);this.list.swallowEvent("mousewheel");this.assetHeight=0;if(this.syncFont!==false){this.list.setStyle("font-size",this.el.getStyle("font-size"))}if(this.title){this.header=this.list.createChild({cls:a+"-hd",html:this.title});this.assetHeight+=this.header.getHeight()}this.innerList=this.list.createChild({cls:a+"-inner"});this.mon(this.innerList,"mouseover",this.onViewOver,this);this.mon(this.innerList,"mousemove",this.onViewMove,this);this.innerList.setWidth(b-this.list.getFrameWidth("lr"));if(this.pageSize){this.footer=this.list.createChild({cls:a+"-ft"});this.pageTb=new Ext.PagingToolbar({store:this.store,pageSize:this.pageSize,renderTo:this.footer});this.assetHeight+=this.footer.getHeight()}if(!this.tpl){this.tpl='<tpl for="."><div class="'+a+'-item">{'+this.displayField+"}</div></tpl>"}this.view=new Ext.DataView({applyTo:this.innerList,tpl:this.tpl,singleSelect:true,selectedClass:this.selectedClass,itemSelector:this.itemSelector||"."+a+"-item",emptyText:this.listEmptyText,deferEmptyText:false});this.mon(this.view,{containerclick:this.onViewClick,click:this.onViewClick,scope:this});this.bindStore(this.store,true);if(this.resizable){this.resizer=new Ext.Resizable(this.list,{pinned:true,handles:"se"});this.mon(this.resizer,"resize",function(g,d,e){this.maxHeight=e-this.handleHeight-this.list.getFrameWidth("tb")-this.assetHeight;this.listWidth=d;this.innerList.setWidth(d-this.list.getFrameWidth("lr"));this.restrictHeight()},this);this[this.pageSize?"footer":"innerList"].setStyle("margin-bottom",this.handleHeight+"px")}}},getListParent:function(){return document.body},getStore:function(){return this.store},bindStore:function(a,b){if(this.store&&!b){if(this.store!==a&&this.store.autoDestroy){this.store.destroy()}else{this.store.un("beforeload",this.onBeforeLoad,this);this.store.un("load",this.onLoad,this);this.store.un("exception",this.collapse,this)}if(!a){this.store=null;if(this.view){this.view.bindStore(null)}if(this.pageTb){this.pageTb.bindStore(null)}}}if(a){if(!b){this.lastQuery=null;if(this.pageTb){this.pageTb.bindStore(a)}}this.store=Ext.StoreMgr.lookup(a);this.store.on({scope:this,beforeload:this.onBeforeLoad,load:this.onLoad,exception:this.collapse});if(this.view){this.view.bindStore(a)}}},reset:function(){if(this.clearFilterOnReset&&this.mode=="local"){this.store.clearFilter()}Ext.form.ComboBox.superclass.reset.call(this)},initEvents:function(){Ext.form.ComboBox.superclass.initEvents.call(this);this.keyNav=new Ext.KeyNav(this.el,{up:function(a){this.inKeyMode=true;this.selectPrev()},down:function(a){if(!this.isExpanded()){this.onTriggerClick()}else{this.inKeyMode=true;this.selectNext()}},enter:function(a){this.onViewClick()},esc:function(a){this.collapse()},tab:function(a){if(this.forceSelection===true){this.collapse()}else{this.onViewClick(false)}return true},scope:this,doRelay:function(c,b,a){if(a=="down"||this.scope.isExpanded()){var d=Ext.KeyNav.prototype.doRelay.apply(this,arguments);if(!Ext.isIE&&Ext.EventManager.useKeydown){this.scope.fireKey(c)}return d}return true},forceKeyDown:true,defaultEventAction:"stopEvent"});this.queryDelay=Math.max(this.queryDelay||10,this.mode=="local"?10:250);this.dqTask=new Ext.util.DelayedTask(this.initQuery,this);if(this.typeAhead){this.taTask=new Ext.util.DelayedTask(this.onTypeAhead,this)}if(!this.enableKeyEvents){this.mon(this.el,"keyup",this.onKeyUp,this)}},onDestroy:function(){if(this.dqTask){this.dqTask.cancel();this.dqTask=null}this.bindStore(null);Ext.destroy(this.resizer,this.view,this.pageTb,this.list);Ext.destroyMembers(this,"hiddenField");Ext.form.ComboBox.superclass.onDestroy.call(this)},fireKey:function(a){if(!this.isExpanded()){Ext.form.ComboBox.superclass.fireKey.call(this,a)}},onResize:function(a,b){Ext.form.ComboBox.superclass.onResize.apply(this,arguments);if(!isNaN(a)&&this.isVisible()&&this.list){this.doResize(a)}else{this.bufferSize=a}},doResize:function(a){if(!Ext.isDefined(this.listWidth)){var b=Math.max(a,this.minListWidth);this.list.setWidth(b);this.innerList.setWidth(b-this.list.getFrameWidth("lr"))}},onEnable:function(){Ext.form.ComboBox.superclass.onEnable.apply(this,arguments);if(this.hiddenField){this.hiddenField.disabled=false}},onDisable:function(){Ext.form.ComboBox.superclass.onDisable.apply(this,arguments);if(this.hiddenField){this.hiddenField.disabled=true}},onBeforeLoad:function(){if(!this.hasFocus){return}this.innerList.update(this.loadingText?'<div class="loading-indicator">'+this.loadingText+"</div>":"");this.restrictHeight();this.selectedIndex=-1},onLoad:function(){if(!this.hasFocus){return}if(this.store.getCount()>0||this.listEmptyText){this.expand();this.restrictHeight();if(this.lastQuery==this.allQuery){if(this.editable){this.el.dom.select()}if(this.autoSelect!==false&&!this.selectByValue(this.value,true)){this.select(0,true)}}else{if(this.autoSelect!==false){this.selectNext()}if(this.typeAhead&&this.lastKey!=Ext.EventObject.BACKSPACE&&this.lastKey!=Ext.EventObject.DELETE){this.taTask.delay(this.typeAheadDelay)}}}else{this.collapse()}},onTypeAhead:function(){if(this.store.getCount()>0){var b=this.store.getAt(0);var c=b.data[this.displayField];var a=c.length;var d=this.getRawValue().length;if(d!=a){this.setRawValue(c);this.selectText(d,c.length)}}},assertValue:function(){var b=this.getRawValue(),a;if(this.valueField&&Ext.isDefined(this.value)){a=this.findRecord(this.valueField,this.value)}if(!a||a.get(this.displayField)!=b){a=this.findRecord(this.displayField,b)}if(!a&&this.forceSelection){if(b.length>0&&b!=this.emptyText){this.el.dom.value=Ext.value(this.lastSelectionText,"");this.applyEmptyText()}else{this.clearValue()}}else{if(a&&this.valueField){if(this.value==b){return}b=a.get(this.valueField||this.displayField)}this.setValue(b)}},onSelect:function(a,b){if(this.fireEvent("beforeselect",this,a,b)!==false){this.setValue(a.data[this.valueField||this.displayField]);this.collapse();this.fireEvent("select",this,a,b)}},getName:function(){var a=this.hiddenField;return a&&a.name?a.name:this.hiddenName||Ext.form.ComboBox.superclass.getName.call(this)},getValue:function(){if(this.valueField){return Ext.isDefined(this.value)?this.value:""}else{return Ext.form.ComboBox.superclass.getValue.call(this)}},clearValue:function(){if(this.hiddenField){this.hiddenField.value=""}this.setRawValue("");this.lastSelectionText="";this.applyEmptyText();this.value=""},setValue:function(a){var c=a;if(this.valueField){var b=this.findRecord(this.valueField,a);if(b){c=b.data[this.displayField]}else{if(Ext.isDefined(this.valueNotFoundText)){c=this.valueNotFoundText}}}this.lastSelectionText=c;if(this.hiddenField){this.hiddenField.value=Ext.value(a,"")}Ext.form.ComboBox.superclass.setValue.call(this,c);this.value=a;return this},findRecord:function(c,b){var a;if(this.store.getCount()>0){this.store.each(function(d){if(d.data[c]==b){a=d;return false}})}return a},onViewMove:function(b,a){this.inKeyMode=false},onViewOver:function(d,b){if(this.inKeyMode){return}var c=this.view.findItemFromChild(b);if(c){var a=this.view.indexOf(c);this.select(a,false)}},onViewClick:function(b){var a=this.view.getSelectedIndexes()[0],c=this.store,d=c.getAt(a);if(d){this.onSelect(d,a)}else{this.collapse()}if(b!==false){this.el.focus()}},restrictHeight:function(){this.innerList.dom.style.height="";var b=this.innerList.dom,e=this.list.getFrameWidth("tb")+(this.resizable?this.handleHeight:0)+this.assetHeight,c=Math.max(b.clientHeight,b.offsetHeight,b.scrollHeight),a=this.getPosition()[1]-Ext.getBody().getScroll().top,g=Ext.lib.Dom.getViewHeight()-a-this.getSize().height,d=Math.max(a,g,this.minHeight||0)-this.list.shadowOffset-e-5;c=Math.min(c,d,this.maxHeight);this.innerList.setHeight(c);this.list.beginUpdate();this.list.setHeight(c+e);this.list.alignTo.apply(this.list,[this.el].concat(this.listAlign));this.list.endUpdate()},isExpanded:function(){return this.list&&this.list.isVisible()},selectByValue:function(a,c){if(!Ext.isEmpty(a,true)){var b=this.findRecord(this.valueField||this.displayField,a);if(b){this.select(this.store.indexOf(b),c);return true}}return false},select:function(a,c){this.selectedIndex=a;this.view.select(a);if(c!==false){var b=this.view.getNode(a);if(b){this.innerList.scrollChildIntoView(b,false)}}},selectNext:function(){var a=this.store.getCount();if(a>0){if(this.selectedIndex==-1){this.select(0)}else{if(this.selectedIndex<a-1){this.select(this.selectedIndex+1)}}}},selectPrev:function(){var a=this.store.getCount();if(a>0){if(this.selectedIndex==-1){this.select(0)}else{if(this.selectedIndex!==0){this.select(this.selectedIndex-1)}}}},onKeyUp:function(b){var a=b.getKey();if(this.editable!==false&&this.readOnly!==true&&(a==b.BACKSPACE||!b.isSpecialKey())){this.lastKey=a;this.dqTask.delay(this.queryDelay)}Ext.form.ComboBox.superclass.onKeyUp.call(this,b)},validateBlur:function(){return !this.list||!this.list.isVisible()},initQuery:function(){this.doQuery(this.getRawValue())},beforeBlur:function(){this.assertValue()},postBlur:function(){Ext.form.ComboBox.superclass.postBlur.call(this);this.collapse();this.inKeyMode=false},doQuery:function(c,b){c=Ext.isEmpty(c)?"":c;var a={query:c,forceAll:b,combo:this,cancel:false};if(this.fireEvent("beforequery",a)===false||a.cancel){return false}c=a.query;b=a.forceAll;if(b===true||(c.length>=this.minChars)){if(this.lastQuery!==c){this.lastQuery=c;if(this.mode=="local"){this.selectedIndex=-1;if(b){this.store.clearFilter()}else{this.store.filter(this.displayField,c)}this.onLoad()}else{this.store.baseParams[this.queryParam]=c;this.store.load({params:this.getParams(c)});this.expand()}}else{this.selectedIndex=-1;this.onLoad()}}},getParams:function(a){var b={},c=this.store.paramNames;if(this.pageSize){b[c.start]=0;b[c.limit]=this.pageSize}return b},collapse:function(){if(!this.isExpanded()){return}this.list.hide();Ext.getDoc().un("mousewheel",this.collapseIf,this);Ext.getDoc().un("mousedown",this.collapseIf,this);this.fireEvent("collapse",this)},collapseIf:function(a){if(!this.isDestroyed&&!a.within(this.wrap)&&!a.within(this.list)){this.collapse()}},expand:function(){if(this.isExpanded()||!this.hasFocus){return}if(this.title||this.pageSize){this.assetHeight=0;if(this.title){this.assetHeight+=this.header.getHeight()}if(this.pageSize){this.assetHeight+=this.footer.getHeight()}}if(this.bufferSize){this.doResize(this.bufferSize);delete this.bufferSize}this.list.alignTo.apply(this.list,[this.el].concat(this.listAlign));this.list.setZIndex(this.getZIndex());this.list.show();if(Ext.isGecko2){this.innerList.setOverflow("auto")}this.mon(Ext.getDoc(),{scope:this,mousewheel:this.collapseIf,mousedown:this.collapseIf});this.fireEvent("expand",this)},onTriggerClick:function(){if(this.readOnly||this.disabled){return}if(this.isExpanded()){this.collapse();this.el.focus()}else{this.onFocus({});if(this.triggerAction=="all"){this.doQuery(this.allQuery,true)}else{this.doQuery(this.getRawValue())}this.el.focus()}}});Ext.reg("combo",Ext.form.ComboBox);Ext.form.Checkbox=Ext.extend(Ext.form.Field,{focusClass:undefined,fieldClass:"x-form-field",checked:false,boxLabel:" ",defaultAutoCreate:{tag:"input",type:"checkbox",autocomplete:"off"},actionMode:"wrap",initComponent:function(){Ext.form.Checkbox.superclass.initComponent.call(this);this.addEvents("check")},onResize:function(){Ext.form.Checkbox.superclass.onResize.apply(this,arguments);if(!this.boxLabel&&!this.fieldLabel){this.el.alignTo(this.wrap,"c-c")}},initEvents:function(){Ext.form.Checkbox.superclass.initEvents.call(this);this.mon(this.el,{scope:this,click:this.onClick,change:this.onClick})},markInvalid:Ext.emptyFn,clearInvalid:Ext.emptyFn,onRender:function(b,a){Ext.form.Checkbox.superclass.onRender.call(this,b,a);if(this.inputValue!==undefined){this.el.dom.value=this.inputValue}this.wrap=this.el.wrap({cls:"x-form-check-wrap"});if(this.boxLabel){this.wrap.createChild({tag:"label",htmlFor:this.el.id,cls:"x-form-cb-label",html:this.boxLabel})}if(this.checked){this.setValue(true)}else{this.checked=this.el.dom.checked}if(Ext.isIE&&!Ext.isStrict){this.wrap.repaint()}this.resizeEl=this.positionEl=this.wrap},onDestroy:function(){Ext.destroy(this.wrap);Ext.form.Checkbox.superclass.onDestroy.call(this)},initValue:function(){this.originalValue=this.getValue()},getValue:function(){if(this.rendered){return this.el.dom.checked}return this.checked},onClick:function(){if(this.el.dom.checked!=this.checked){this.setValue(this.el.dom.checked)}},setValue:function(a){var c=this.checked,b=this.inputValue;this.checked=(a===true||a==="true"||a=="1"||(b?a==b:String(a).toLowerCase()=="on"));if(this.rendered){this.el.dom.checked=this.checked;this.el.dom.defaultChecked=this.checked}if(c!=this.checked){this.fireEvent("check",this,this.checked);if(this.handler){this.handler.call(this.scope||this,this,this.checked)}}return this}});Ext.reg("checkbox",Ext.form.Checkbox);Ext.form.CheckboxGroup=Ext.extend(Ext.form.Field,{columns:"auto",vertical:false,allowBlank:true,blankText:"You must select at least one item in this group",defaultType:"checkbox",groupCls:"x-form-check-group",initComponent:function(){this.addEvents("change");this.on("change",this.validate,this);Ext.form.CheckboxGroup.superclass.initComponent.call(this)},onRender:function(k,g){if(!this.el){var q={autoEl:{id:this.id},cls:this.groupCls,layout:"column",renderTo:k,bufferResize:false};var a={xtype:"container",defaultType:this.defaultType,layout:"form",defaults:{hideLabel:true,anchor:"100%"}};if(this.items[0].items){Ext.apply(q,{layoutConfig:{columns:this.items.length},defaults:this.defaults,items:this.items});for(var e=0,n=this.items.length;e<n;e++){Ext.applyIf(this.items[e],a)}}else{var d,o=[];if(typeof this.columns=="string"){this.columns=this.items.length}if(!Ext.isArray(this.columns)){var m=[];for(var e=0;e<this.columns;e++){m.push((100/this.columns)*0.01)}this.columns=m}d=this.columns.length;for(var e=0;e<d;e++){var b=Ext.apply({items:[]},a);b[this.columns[e]<=1?"columnWidth":"width"]=this.columns[e];if(this.defaults){b.defaults=Ext.apply(b.defaults||{},this.defaults)}o.push(b)}if(this.vertical){var s=Math.ceil(this.items.length/d),p=0;for(var e=0,n=this.items.length;e<n;e++){if(e>0&&e%s==0){p++}if(this.items[e].fieldLabel){this.items[e].hideLabel=false}o[p].items.push(this.items[e])}}else{for(var e=0,n=this.items.length;e<n;e++){var r=e%d;if(this.items[e].fieldLabel){this.items[e].hideLabel=false}o[r].items.push(this.items[e])}}Ext.apply(q,{layoutConfig:{columns:d},items:o})}this.panel=new Ext.Container(q);this.panel.ownerCt=this;this.el=this.panel.getEl();if(this.forId&&this.itemCls){var c=this.el.up(this.itemCls).child("label",true);if(c){c.setAttribute("htmlFor",this.forId)}}var h=this.panel.findBy(function(i){return i.isFormField},this);this.items=new Ext.util.MixedCollection();this.items.addAll(h)}Ext.form.CheckboxGroup.superclass.onRender.call(this,k,g)},initValue:function(){if(this.value){this.setValue.apply(this,this.buffered?this.value:[this.value]);delete this.buffered;delete this.value}},afterRender:function(){Ext.form.CheckboxGroup.superclass.afterRender.call(this);this.eachItem(function(a){a.on("check",this.fireChecked,this);a.inGroup=true})},doLayout:function(){if(this.rendered){this.panel.forceLayout=this.ownerCt.forceLayout;this.panel.doLayout()}},fireChecked:function(){var a=[];this.eachItem(function(b){if(b.checked){a.push(b)}});this.fireEvent("change",this,a)},getErrors:function(){var b=Ext.form.CheckboxGroup.superclass.getErrors.apply(this,arguments);if(!this.allowBlank){var a=true;this.eachItem(function(c){if(c.checked){return(a=false)}});if(a){b.push(this.blankText)}}return b},isDirty:function(){if(this.disabled||!this.rendered){return false}var a=false;this.eachItem(function(b){if(b.isDirty()){a=true;return false}});return a},setReadOnly:function(a){if(this.rendered){this.eachItem(function(b){b.setReadOnly(a)})}this.readOnly=a},onDisable:function(){this.eachItem(function(a){a.disable()})},onEnable:function(){this.eachItem(function(a){a.enable()})},onResize:function(a,b){this.panel.setSize(a,b);this.panel.doLayout()},reset:function(){if(this.originalValue){this.eachItem(function(a){if(a.setValue){a.setValue(false);a.originalValue=a.getValue()}});this.resetOriginal=true;this.setValue(this.originalValue);delete this.resetOriginal}else{this.eachItem(function(a){if(a.reset){a.reset()}})}(function(){this.clearInvalid()}).defer(50,this)},setValue:function(){if(this.rendered){this.onSetValue.apply(this,arguments)}else{this.buffered=true;this.value=arguments}return this},onSetValue:function(d,c){if(arguments.length==1){if(Ext.isArray(d)){Ext.each(d,function(h,e){if(Ext.isObject(h)&&h.setValue){h.setValue(true);if(this.resetOriginal===true){h.originalValue=h.getValue()}}else{var g=this.items.itemAt(e);if(g){g.setValue(h)}}},this)}else{if(Ext.isObject(d)){for(var a in d){var b=this.getBox(a);if(b){b.setValue(d[a])}}}else{this.setValueForItem(d)}}}else{var b=this.getBox(d);if(b){b.setValue(c)}}},beforeDestroy:function(){Ext.destroy(this.panel);if(!this.rendered){Ext.destroy(this.items)}Ext.form.CheckboxGroup.superclass.beforeDestroy.call(this)},setValueForItem:function(a){a=String(a).split(",");this.eachItem(function(b){if(a.indexOf(b.inputValue)>-1){b.setValue(true)}})},getBox:function(b){var a=null;this.eachItem(function(c){if(b==c||c.dataIndex==b||c.id==b||c.getName()==b){a=c;return false}});return a},getValue:function(){var a=[];this.eachItem(function(b){if(b.checked){a.push(b)}});return a},eachItem:function(b,a){if(this.items&&this.items.each){this.items.each(b,a||this)}},getRawValue:Ext.emptyFn,setRawValue:Ext.emptyFn});Ext.reg("checkboxgroup",Ext.form.CheckboxGroup);Ext.form.CompositeField=Ext.extend(Ext.form.Field,{defaultMargins:"0 5 0 0",skipLastItemMargin:true,isComposite:true,combineErrors:true,labelConnector:", ",initComponent:function(){var g=[],b=this.items,e;for(var d=0,c=b.length;d<c;d++){e=b[d];if(!Ext.isEmpty(e.ref)){e.ref="../"+e.ref}g.push(e.fieldLabel);Ext.applyIf(e,this.defaults);if(!(d==c-1&&this.skipLastItemMargin)){Ext.applyIf(e,{margins:this.defaultMargins})}}this.fieldLabel=this.fieldLabel||this.buildLabel(g);this.fieldErrors=new Ext.util.MixedCollection(true,function(h){return h.field});this.fieldErrors.on({scope:this,add:this.updateInvalidMark,remove:this.updateInvalidMark,replace:this.updateInvalidMark});Ext.form.CompositeField.superclass.initComponent.apply(this,arguments);this.innerCt=new Ext.Container({layout:"hbox",items:this.items,cls:"x-form-composite",defaultMargins:"0 3 0 0",ownerCt:this});this.innerCt.ownerCt=undefined;var a=this.innerCt.findBy(function(h){return h.isFormField},this);this.items=new Ext.util.MixedCollection();this.items.addAll(a)},onRender:function(c,a){if(!this.el){var d=this.innerCt;d.render(c);this.el=d.getEl();if(this.combineErrors){this.eachItem(function(e){Ext.apply(e,{markInvalid:this.onFieldMarkInvalid.createDelegate(this,[e],0),clearInvalid:this.onFieldClearInvalid.createDelegate(this,[e],0)})})}var b=this.el.parent().parent().child("label",true);if(b){b.setAttribute("for",this.items.items[0].id)}}Ext.form.CompositeField.superclass.onRender.apply(this,arguments)},onFieldMarkInvalid:function(d,c){var b=d.getName(),a={field:b,errorName:d.fieldLabel||b,error:c};this.fieldErrors.replace(b,a);d.el.addClass(d.invalidClass)},onFieldClearInvalid:function(a){this.fieldErrors.removeKey(a.getName());a.el.removeClass(a.invalidClass)},updateInvalidMark:function(){var a=Ext.isIE6&&Ext.isStrict;if(this.fieldErrors.length==0){this.clearInvalid();if(a){this.clearInvalid.defer(50,this)}}else{var b=this.buildCombinedErrorMessage(this.fieldErrors.items);this.sortErrors();this.markInvalid(b);if(a){this.markInvalid(b)}}},validateValue:function(){var a=true;this.eachItem(function(b){if(!b.isValid()){a=false}});return a},buildCombinedErrorMessage:function(e){var d=[],b;for(var c=0,a=e.length;c<a;c++){b=e[c];d.push(String.format("{0}: {1}",b.errorName,b.error))}return d.join("<br />")},sortErrors:function(){var a=this.items;this.fieldErrors.sort("ASC",function(g,d){var c=function(b){return function(i){return i.getName()==b}};var h=a.findIndexBy(c(g.field)),e=a.findIndexBy(c(d.field));return h<e?-1:1})},reset:function(){this.eachItem(function(a){a.reset()});(function(){this.clearInvalid()}).defer(50,this)},clearInvalidChildren:function(){this.eachItem(function(a){a.clearInvalid()})},buildLabel:function(a){return Ext.clean(a).join(this.labelConnector)},isDirty:function(){if(this.disabled||!this.rendered){return false}var a=false;this.eachItem(function(b){if(b.isDirty()){a=true;return false}});return a},eachItem:function(b,a){if(this.items&&this.items.each){this.items.each(b,a||this)}},onResize:function(e,c,a,d){var b=this.innerCt;if(this.rendered&&b.rendered){b.setSize(e,c)}Ext.form.CompositeField.superclass.onResize.apply(this,arguments)},doLayout:function(c,b){if(this.rendered){var a=this.innerCt;a.forceLayout=this.ownerCt.forceLayout;a.doLayout(c,b)}},beforeDestroy:function(){Ext.destroy(this.innerCt);Ext.form.CompositeField.superclass.beforeDestroy.call(this)},setReadOnly:function(a){if(a==undefined){a=true}a=!!a;if(this.rendered){this.eachItem(function(b){b.setReadOnly(a)})}this.readOnly=a},onShow:function(){Ext.form.CompositeField.superclass.onShow.call(this);this.doLayout()},onDisable:function(){this.eachItem(function(a){a.disable()})},onEnable:function(){this.eachItem(function(a){a.enable()})}});Ext.reg("compositefield",Ext.form.CompositeField);Ext.form.Radio=Ext.extend(Ext.form.Checkbox,{inputType:"radio",markInvalid:Ext.emptyFn,clearInvalid:Ext.emptyFn,getGroupValue:function(){var a=this.el.up("form")||Ext.getBody();var b=a.child("input[name="+this.el.dom.name+"]:checked",true);return b?b.value:null},setValue:function(b){var a,d,c;if(typeof b=="boolean"){Ext.form.Radio.superclass.setValue.call(this,b)}else{if(this.rendered){a=this.getCheckEl();c=a.child("input[name="+this.el.dom.name+"][value="+b+"]",true);if(c){Ext.getCmp(c.id).setValue(true)}}}if(this.rendered&&this.checked){a=a||this.getCheckEl();d=this.getCheckEl().select("input[name="+this.el.dom.name+"]");d.each(function(e){if(e.dom.id!=this.id){Ext.getCmp(e.dom.id).setValue(false)}},this)}return this},getCheckEl:function(){if(this.inGroup){return this.el.up(".x-form-radio-group")}return this.el.up("form")||Ext.getBody()}});Ext.reg("radio",Ext.form.Radio);Ext.form.RadioGroup=Ext.extend(Ext.form.CheckboxGroup,{allowBlank:true,blankText:"You must select one item in this group",defaultType:"radio",groupCls:"x-form-radio-group",getValue:function(){var a=null;this.eachItem(function(b){if(b.checked){a=b;return false}});return a},onSetValue:function(c,b){if(arguments.length>1){var a=this.getBox(c);if(a){a.setValue(b);if(a.checked){this.eachItem(function(d){if(d!==a){d.setValue(false)}})}}}else{this.setValueForItem(c)}},setValueForItem:function(a){a=String(a).split(",")[0];this.eachItem(function(b){b.setValue(a==b.inputValue)})},fireChecked:function(){if(!this.checkTask){this.checkTask=new Ext.util.DelayedTask(this.bufferChecked,this)}this.checkTask.delay(10)},bufferChecked:function(){var a=null;this.eachItem(function(b){if(b.checked){a=b;return false}});this.fireEvent("change",this,a)},onDestroy:function(){if(this.checkTask){this.checkTask.cancel();this.checkTask=null}Ext.form.RadioGroup.superclass.onDestroy.call(this)}});Ext.reg("radiogroup",Ext.form.RadioGroup);Ext.form.Hidden=Ext.extend(Ext.form.Field,{inputType:"hidden",shouldLayout:false,onRender:function(){Ext.form.Hidden.superclass.onRender.apply(this,arguments)},initEvents:function(){this.originalValue=this.getValue()},setSize:Ext.emptyFn,setWidth:Ext.emptyFn,setHeight:Ext.emptyFn,setPosition:Ext.emptyFn,setPagePosition:Ext.emptyFn,markInvalid:Ext.emptyFn,clearInvalid:Ext.emptyFn});Ext.reg("hidden",Ext.form.Hidden);Ext.form.BasicForm=Ext.extend(Ext.util.Observable,{constructor:function(b,a){Ext.apply(this,a);if(Ext.isString(this.paramOrder)){this.paramOrder=this.paramOrder.split(/[\s,|]/)}this.items=new Ext.util.MixedCollection(false,function(c){return c.getItemId()});this.addEvents("beforeaction","actionfailed","actioncomplete");if(b){this.initEl(b)}Ext.form.BasicForm.superclass.constructor.call(this)},timeout:30,paramOrder:undefined,paramsAsHash:false,waitTitle:"Please Wait...",activeAction:null,trackResetOnLoad:false,initEl:function(a){this.el=Ext.get(a);this.id=this.el.id||Ext.id();if(!this.standardSubmit){this.el.on("submit",this.onSubmit,this)}this.el.addClass("x-form")},getEl:function(){return this.el},onSubmit:function(a){a.stopEvent()},destroy:function(a){if(a!==true){this.items.each(function(b){Ext.destroy(b)});Ext.destroy(this.el)}this.items.clear();this.purgeListeners()},isValid:function(){var a=true;this.items.each(function(b){if(!b.validate()){a=false}});return a},isDirty:function(){var a=false;this.items.each(function(b){if(b.isDirty()){a=true;return false}});return a},doAction:function(b,a){if(Ext.isString(b)){b=new Ext.form.Action.ACTION_TYPES[b](this,a)}if(this.fireEvent("beforeaction",this,b)!==false){this.beforeAction(b);b.run.defer(100,b)}return this},submit:function(b){b=b||{};if(this.standardSubmit){var a=b.clientValidation===false||this.isValid();if(a){var c=this.el.dom;if(this.url&&Ext.isEmpty(c.action)){c.action=this.url}c.submit()}return a}var d=String.format("{0}submit",this.api?"direct":"");this.doAction(d,b);return this},load:function(a){var b=String.format("{0}load",this.api?"direct":"");this.doAction(b,a);return this},updateRecord:function(b){b.beginEdit();var a=b.fields,d,c;a.each(function(e){d=this.findField(e.name);if(d){c=d.getValue();if(typeof c!=undefined&&c.getGroupValue){c=c.getGroupValue()}else{if(d.eachItem){c=[];d.eachItem(function(g){c.push(g.getValue())})}}b.set(e.name,c)}},this);b.endEdit();return this},loadRecord:function(a){this.setValues(a.data);return this},beforeAction:function(a){this.items.each(function(c){if(c.isFormField&&c.syncValue){c.syncValue()}});var b=a.options;if(b.waitMsg){if(this.waitMsgTarget===true){this.el.mask(b.waitMsg,"x-mask-loading")}else{if(this.waitMsgTarget){this.waitMsgTarget=Ext.get(this.waitMsgTarget);this.waitMsgTarget.mask(b.waitMsg,"x-mask-loading")}else{Ext.MessageBox.wait(b.waitMsg,b.waitTitle||this.waitTitle)}}}},afterAction:function(a,c){this.activeAction=null;var b=a.options;if(b.waitMsg){if(this.waitMsgTarget===true){this.el.unmask()}else{if(this.waitMsgTarget){this.waitMsgTarget.unmask()}else{Ext.MessageBox.updateProgress(1);Ext.MessageBox.hide()}}}if(c){if(b.reset){this.reset()}Ext.callback(b.success,b.scope,[this,a]);this.fireEvent("actioncomplete",this,a)}else{Ext.callback(b.failure,b.scope,[this,a]);this.fireEvent("actionfailed",this,a)}},findField:function(c){var b=this.items.get(c);if(!Ext.isObject(b)){var a=function(d){if(d.isFormField){if(d.dataIndex==c||d.id==c||d.getName()==c){b=d;return false}else{if(d.isComposite){return d.items.each(a)}else{if(d instanceof Ext.form.CheckboxGroup&&d.rendered){return d.eachItem(a)}}}}};this.items.each(a)}return b||null},markInvalid:function(h){if(Ext.isArray(h)){for(var c=0,a=h.length;c<a;c++){var b=h[c];var d=this.findField(b.id);if(d){d.markInvalid(b.msg)}}}else{var e,g;for(g in h){if(!Ext.isFunction(h[g])&&(e=this.findField(g))){e.markInvalid(h[g])}}}return this},setValues:function(c){if(Ext.isArray(c)){for(var d=0,a=c.length;d<a;d++){var b=c[d];var e=this.findField(b.id);if(e){e.setValue(b.value);if(this.trackResetOnLoad){e.originalValue=e.getValue()}}}}else{var g,h;for(h in c){if(!Ext.isFunction(c[h])&&(g=this.findField(h))){g.setValue(c[h]);if(this.trackResetOnLoad){g.originalValue=g.getValue()}}}}return this},getValues:function(b){var a=Ext.lib.Ajax.serializeForm(this.el.dom);if(b===true){return a}return Ext.urlDecode(a)},getFieldValues:function(a){var d={},e,b,c;this.items.each(function(g){if(!g.disabled&&(a!==true||g.isDirty())){e=g.getName();b=d[e];c=g.getValue();if(Ext.isDefined(b)){if(Ext.isArray(b)){d[e].push(c)}else{d[e]=[b,c]}}else{d[e]=c}}});return d},clearInvalid:function(){this.items.each(function(a){a.clearInvalid()});return this},reset:function(){this.items.each(function(a){a.reset()});return this},add:function(){this.items.addAll(Array.prototype.slice.call(arguments,0));return this},remove:function(a){this.items.remove(a);return this},cleanDestroyed:function(){this.items.filterBy(function(a){return !!a.isDestroyed}).each(this.remove,this)},render:function(){this.items.each(function(a){if(a.isFormField&&!a.rendered&&document.getElementById(a.id)){a.applyToMarkup(a.id)}});return this},applyToFields:function(a){this.items.each(function(b){Ext.apply(b,a)});return this},applyIfToFields:function(a){this.items.each(function(b){Ext.applyIf(b,a)});return this},callFieldMethod:function(b,a){a=a||[];this.items.each(function(c){if(Ext.isFunction(c[b])){c[b].apply(c,a)}});return this}});Ext.BasicForm=Ext.form.BasicForm;Ext.FormPanel=Ext.extend(Ext.Panel,{minButtonWidth:75,labelAlign:"left",monitorValid:false,monitorPoll:200,layout:"form",initComponent:function(){this.form=this.createForm();Ext.FormPanel.superclass.initComponent.call(this);this.bodyCfg={tag:"form",cls:this.baseCls+"-body",method:this.method||"POST",id:this.formId||Ext.id()};if(this.fileUpload){this.bodyCfg.enctype="multipart/form-data"}this.initItems();this.addEvents("clientvalidation");this.relayEvents(this.form,["beforeaction","actionfailed","actioncomplete"])},createForm:function(){var a=Ext.applyIf({listeners:{}},this.initialConfig);return new Ext.form.BasicForm(null,a)},initFields:function(){var c=this.form;var a=this;var b=function(d){if(a.isField(d)){c.add(d)}else{if(d.findBy&&d!=a){a.applySettings(d);if(d.items&&d.items.each){d.items.each(b,this)}}}};this.items.each(b,this)},applySettings:function(b){var a=b.ownerCt;Ext.applyIf(b,{labelAlign:a.labelAlign,labelWidth:a.labelWidth,itemCls:a.itemCls})},getLayoutTarget:function(){return this.form.el},getForm:function(){return this.form},onRender:function(b,a){this.initFields();Ext.FormPanel.superclass.onRender.call(this,b,a);this.form.initEl(this.body)},beforeDestroy:function(){this.stopMonitoring();this.form.destroy(true);Ext.FormPanel.superclass.beforeDestroy.call(this)},isField:function(a){return !!a.setValue&&!!a.getValue&&!!a.markInvalid&&!!a.clearInvalid},initEvents:function(){Ext.FormPanel.superclass.initEvents.call(this);this.on({scope:this,add:this.onAddEvent,remove:this.onRemoveEvent});if(this.monitorValid){this.startMonitoring()}},onAdd:function(a){Ext.FormPanel.superclass.onAdd.call(this,a);this.processAdd(a)},onAddEvent:function(a,b){if(a!==this){this.processAdd(b)}},processAdd:function(a){if(this.isField(a)){this.form.add(a)}else{if(a.findBy){this.applySettings(a);this.form.add.apply(this.form,a.findBy(this.isField))}}},onRemove:function(a){Ext.FormPanel.superclass.onRemove.call(this,a);this.processRemove(a)},onRemoveEvent:function(a,b){if(a!==this){this.processRemove(b)}},processRemove:function(a){if(!this.destroying){if(this.isField(a)){this.form.remove(a)}else{if(a.findBy){Ext.each(a.findBy(this.isField),this.form.remove,this.form);this.form.cleanDestroyed()}}}},startMonitoring:function(){if(!this.validTask){this.validTask=new Ext.util.TaskRunner();this.validTask.start({run:this.bindHandler,interval:this.monitorPoll||200,scope:this})}},stopMonitoring:function(){if(this.validTask){this.validTask.stopAll();this.validTask=null}},load:function(){this.form.load.apply(this.form,arguments)},onDisable:function(){Ext.FormPanel.superclass.onDisable.call(this);if(this.form){this.form.items.each(function(){this.disable()})}},onEnable:function(){Ext.FormPanel.superclass.onEnable.call(this);if(this.form){this.form.items.each(function(){this.enable()})}},bindHandler:function(){var e=true;this.form.items.each(function(g){if(!g.isValid(true)){e=false;return false}});if(this.fbar){var b=this.fbar.items.items;for(var d=0,a=b.length;d<a;d++){var c=b[d];if(c.formBind===true&&c.disabled===e){c.setDisabled(!e)}}}this.fireEvent("clientvalidation",this,e)}});Ext.reg("form",Ext.FormPanel);Ext.form.FormPanel=Ext.FormPanel;Ext.form.FieldSet=Ext.extend(Ext.Panel,{baseCls:"x-fieldset",layout:"form",animCollapse:false,onRender:function(b,a){if(!this.el){this.el=document.createElement("fieldset");this.el.id=this.id;if(this.title||this.header||this.checkboxToggle){this.el.appendChild(document.createElement("legend")).className=this.baseCls+"-header"}}Ext.form.FieldSet.superclass.onRender.call(this,b,a);if(this.checkboxToggle){var c=typeof this.checkboxToggle=="object"?this.checkboxToggle:{tag:"input",type:"checkbox",name:this.checkboxName||this.id+"-checkbox"};this.checkbox=this.header.insertFirst(c);this.checkbox.dom.checked=!this.collapsed;this.mon(this.checkbox,"click",this.onCheckClick,this)}},onCollapse:function(a,b){if(this.checkbox){this.checkbox.dom.checked=false}Ext.form.FieldSet.superclass.onCollapse.call(this,a,b)},onExpand:function(a,b){if(this.checkbox){this.checkbox.dom.checked=true}Ext.form.FieldSet.superclass.onExpand.call(this,a,b)},onCheckClick:function(){this[this.checkbox.dom.checked?"expand":"collapse"]()}});Ext.reg("fieldset",Ext.form.FieldSet);Ext.form.HtmlEditor=Ext.extend(Ext.form.Field,{enableFormat:true,enableFontSize:true,enableColors:true,enableAlignments:true,enableLists:true,enableSourceEdit:true,enableLinks:true,enableFont:true,createLinkText:"Please enter the URL for the link:",defaultLinkValue:"http://",fontFamilies:["Arial","Courier New","Tahoma","Times New Roman","Verdana"],defaultFont:"tahoma",defaultValue:(Ext.isOpera||Ext.isIE6)?" ":"​",actionMode:"wrap",validationEvent:false,deferHeight:true,initialized:false,activated:false,sourceEditMode:false,onFocus:Ext.emptyFn,iframePad:3,hideMode:"offsets",defaultAutoCreate:{tag:"textarea",style:"width:500px;height:300px;",autocomplete:"off"},initComponent:function(){this.addEvents("initialize","activate","beforesync","beforepush","sync","push","editmodechange");Ext.form.HtmlEditor.superclass.initComponent.call(this)},createFontOptions:function(){var d=[],b=this.fontFamilies,c,g;for(var e=0,a=b.length;e<a;e++){c=b[e];g=c.toLowerCase();d.push('<option value="',g,'" style="font-family:',c,';"',(this.defaultFont==g?' selected="true">':">"),c,"</option>")}return d.join("")},createToolbar:function(e){var c=[];var a=Ext.QuickTips&&Ext.QuickTips.isEnabled();function d(k,h,i){return{itemId:k,cls:"x-btn-icon",iconCls:"x-edit-"+k,enableToggle:h!==false,scope:e,handler:i||e.relayBtnCmd,clickEvent:"mousedown",tooltip:a?e.buttonTips[k]||undefined:undefined,overflowText:e.buttonTips[k].title||undefined,tabIndex:-1}}if(this.enableFont&&!Ext.isSafari2){var g=new Ext.Toolbar.Item({autoEl:{tag:"select",cls:"x-font-select",html:this.createFontOptions()}});c.push(g,"-")}if(this.enableFormat){c.push(d("bold"),d("italic"),d("underline"))}if(this.enableFontSize){c.push("-",d("increasefontsize",false,this.adjustFont),d("decreasefontsize",false,this.adjustFont))}if(this.enableColors){c.push("-",{itemId:"forecolor",cls:"x-btn-icon",iconCls:"x-edit-forecolor",clickEvent:"mousedown",tooltip:a?e.buttonTips.forecolor||undefined:undefined,tabIndex:-1,menu:new Ext.menu.ColorMenu({allowReselect:true,focus:Ext.emptyFn,value:"000000",plain:true,listeners:{scope:this,select:function(i,h){this.execCmd("forecolor",Ext.isWebKit||Ext.isIE?"#"+h:h);this.deferFocus()}},clickEvent:"mousedown"})},{itemId:"backcolor",cls:"x-btn-icon",iconCls:"x-edit-backcolor",clickEvent:"mousedown",tooltip:a?e.buttonTips.backcolor||undefined:undefined,tabIndex:-1,menu:new Ext.menu.ColorMenu({focus:Ext.emptyFn,value:"FFFFFF",plain:true,allowReselect:true,listeners:{scope:this,select:function(i,h){if(Ext.isGecko){this.execCmd("useCSS",false);this.execCmd("hilitecolor",h);this.execCmd("useCSS",true);this.deferFocus()}else{this.execCmd(Ext.isOpera?"hilitecolor":"backcolor",Ext.isWebKit||Ext.isIE?"#"+h:h);this.deferFocus()}}},clickEvent:"mousedown"})})}if(this.enableAlignments){c.push("-",d("justifyleft"),d("justifycenter"),d("justifyright"))}if(!Ext.isSafari2){if(this.enableLinks){c.push("-",d("createlink",false,this.createLink))}if(this.enableLists){c.push("-",d("insertorderedlist"),d("insertunorderedlist"))}if(this.enableSourceEdit){c.push("-",d("sourceedit",true,function(h){this.toggleSourceEdit(!this.sourceEditMode)}))}}var b=new Ext.Toolbar({renderTo:this.wrap.dom.firstChild,items:c});if(g){this.fontSelect=g.el;this.mon(this.fontSelect,"change",function(){var h=this.fontSelect.dom.value;this.relayCmd("fontname",h);this.deferFocus()},this)}this.mon(b.el,"click",function(h){h.preventDefault()});this.tb=b;this.tb.doLayout()},onDisable:function(){this.wrap.mask();Ext.form.HtmlEditor.superclass.onDisable.call(this)},onEnable:function(){this.wrap.unmask();Ext.form.HtmlEditor.superclass.onEnable.call(this)},setReadOnly:function(b){Ext.form.HtmlEditor.superclass.setReadOnly.call(this,b);if(this.initialized){if(Ext.isIE){this.getEditorBody().contentEditable=!b}else{this.setDesignMode(!b)}var a=this.getEditorBody();if(a){a.style.cursor=this.readOnly?"default":"text"}this.disableItems(b)}},getDocMarkup:function(){var a=Ext.fly(this.iframe).getHeight()-this.iframePad*2;return String.format('<html><head><style type="text/css">body{border: 0; margin: 0; padding: {0}px; height: {1}px; cursor: text}</style></head><body></body></html>',this.iframePad,a)},getEditorBody:function(){var a=this.getDoc();return a.body||a.documentElement},getDoc:function(){return Ext.isIE?this.getWin().document:(this.iframe.contentDocument||this.getWin().document)},getWin:function(){return Ext.isIE?this.iframe.contentWindow:window.frames[this.iframe.name]},onRender:function(b,a){Ext.form.HtmlEditor.superclass.onRender.call(this,b,a);this.el.dom.style.border="0 none";this.el.dom.setAttribute("tabIndex",-1);this.el.addClass("x-hidden");if(Ext.isIE){this.el.applyStyles("margin-top:-1px;margin-bottom:-1px;")}this.wrap=this.el.wrap({cls:"x-html-editor-wrap",cn:{cls:"x-html-editor-tb"}});this.createToolbar(this);this.disableItems(true);this.tb.doLayout();this.createIFrame();if(!this.width){var c=this.el.getSize();this.setSize(c.width,this.height||c.height)}this.resizeEl=this.positionEl=this.wrap},createIFrame:function(){var a=document.createElement("iframe");a.name=Ext.id();a.frameBorder="0";a.style.overflow="auto";a.src=Ext.SSL_SECURE_URL;this.wrap.dom.appendChild(a);this.iframe=a;this.monitorTask=Ext.TaskMgr.start({run:this.checkDesignMode,scope:this,interval:100})},initFrame:function(){Ext.TaskMgr.stop(this.monitorTask);var b=this.getDoc();this.win=this.getWin();b.open();b.write(this.getDocMarkup());b.close();var a={run:function(){var c=this.getDoc();if(c.body||c.readyState=="complete"){Ext.TaskMgr.stop(a);this.setDesignMode(true);this.initEditor.defer(10,this)}},interval:10,duration:10000,scope:this};Ext.TaskMgr.start(a)},checkDesignMode:function(){if(this.wrap&&this.wrap.dom.offsetWidth){var a=this.getDoc();if(!a){return}if(!a.editorInitialized||this.getDesignMode()!="on"){this.initFrame()}}},setDesignMode:function(b){var a=this.getDoc();if(a){if(this.readOnly){b=false}a.designMode=(/on|true/i).test(String(b).toLowerCase())?"on":"off"}},getDesignMode:function(){var a=this.getDoc();if(!a){return""}return String(a.designMode).toLowerCase()},disableItems:function(a){if(this.fontSelect){this.fontSelect.dom.disabled=a}this.tb.items.each(function(b){if(b.getItemId()!="sourceedit"){b.setDisabled(a)}})},onResize:function(b,c){Ext.form.HtmlEditor.superclass.onResize.apply(this,arguments);if(this.el&&this.iframe){if(Ext.isNumber(b)){var e=b-this.wrap.getFrameWidth("lr");this.el.setWidth(e);this.tb.setWidth(e);this.iframe.style.width=Math.max(e,0)+"px"}if(Ext.isNumber(c)){var a=c-this.wrap.getFrameWidth("tb")-this.tb.el.getHeight();this.el.setHeight(a);this.iframe.style.height=Math.max(a,0)+"px";var d=this.getEditorBody();if(d){d.style.height=Math.max((a-(this.iframePad*2)),0)+"px"}}}},toggleSourceEdit:function(b){var d,a;if(b===undefined){b=!this.sourceEditMode}this.sourceEditMode=b===true;var c=this.tb.getComponent("sourceedit");if(c.pressed!==this.sourceEditMode){c.toggle(this.sourceEditMode);if(!c.xtbHidden){return}}if(this.sourceEditMode){this.previousSize=this.getSize();d=Ext.get(this.iframe).getHeight();this.disableItems(true);this.syncValue();this.iframe.className="x-hidden";this.el.removeClass("x-hidden");this.el.dom.removeAttribute("tabIndex");this.el.focus();this.el.dom.style.height=d+"px"}else{a=parseInt(this.el.dom.style.height,10);if(this.initialized){this.disableItems(this.readOnly)}this.pushValue();this.iframe.className="";this.el.addClass("x-hidden");this.el.dom.setAttribute("tabIndex",-1);this.deferFocus();this.setSize(this.previousSize);delete this.previousSize;this.iframe.style.height=a+"px"}this.fireEvent("editmodechange",this,this.sourceEditMode)},createLink:function(){var a=prompt(this.createLinkText,this.defaultLinkValue);if(a&&a!="http://"){this.relayCmd("createlink",a)}},initEvents:function(){this.originalValue=this.getValue()},markInvalid:Ext.emptyFn,clearInvalid:Ext.emptyFn,setValue:function(a){Ext.form.HtmlEditor.superclass.setValue.call(this,a);this.pushValue();return this},cleanHtml:function(a){a=String(a);if(Ext.isWebKit){a=a.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi,"")}if(a.charCodeAt(0)==this.defaultValue.replace(/\D/g,"")){a=a.substring(1)}return a},syncValue:function(){if(this.initialized){var d=this.getEditorBody();var c=d.innerHTML;if(Ext.isWebKit){var b=d.getAttribute("style");var a=b.match(/text-align:(.*?);/i);if(a&&a[1]){c='<div style="'+a[0]+'">'+c+"</div>"}}c=this.cleanHtml(c);if(this.fireEvent("beforesync",this,c)!==false){this.el.dom.value=c;this.fireEvent("sync",this,c)}}},getValue:function(){this[this.sourceEditMode?"pushValue":"syncValue"]();return Ext.form.HtmlEditor.superclass.getValue.call(this)},pushValue:function(){if(this.initialized){var a=this.el.dom.value;if(!this.activated&&a.length<1){a=this.defaultValue}if(this.fireEvent("beforepush",this,a)!==false){this.getEditorBody().innerHTML=a;if(Ext.isGecko){this.setDesignMode(false);this.setDesignMode(true)}this.fireEvent("push",this,a)}}},deferFocus:function(){this.focus.defer(10,this)},focus:function(){if(this.win&&!this.sourceEditMode){this.win.focus()}else{this.el.focus()}},initEditor:function(){try{var c=this.getEditorBody(),a=this.el.getStyles("font-size","font-family","background-image","background-repeat","background-color","color"),g,b;a["background-attachment"]="fixed";c.bgProperties="fixed";Ext.DomHelper.applyStyles(c,a);g=this.getDoc();if(g){try{Ext.EventManager.removeAll(g)}catch(d){}}b=this.onEditorEvent.createDelegate(this);Ext.EventManager.on(g,{mousedown:b,dblclick:b,click:b,keyup:b,buffer:100});if(Ext.isGecko){Ext.EventManager.on(g,"keypress",this.applyCommand,this)}if(Ext.isIE||Ext.isWebKit||Ext.isOpera){Ext.EventManager.on(g,"keydown",this.fixKeys,this)}g.editorInitialized=true;this.initialized=true;this.pushValue();this.setReadOnly(this.readOnly);this.fireEvent("initialize",this)}catch(d){}},beforeDestroy:function(){if(this.monitorTask){Ext.TaskMgr.stop(this.monitorTask)}if(this.rendered){Ext.destroy(this.tb);var b=this.getDoc();if(b){try{Ext.EventManager.removeAll(b);for(var c in b){delete b[c]}}catch(a){}}if(this.wrap){this.wrap.dom.innerHTML="";this.wrap.remove()}}Ext.form.HtmlEditor.superclass.beforeDestroy.call(this)},onFirstFocus:function(){this.activated=true;this.disableItems(this.readOnly);if(Ext.isGecko){this.win.focus();var a=this.win.getSelection();if(!a.focusNode||a.focusNode.nodeType!=3){var b=a.getRangeAt(0);b.selectNodeContents(this.getEditorBody());b.collapse(true);this.deferFocus()}try{this.execCmd("useCSS",true);this.execCmd("styleWithCSS",false)}catch(c){}}this.fireEvent("activate",this)},adjustFont:function(b){var d=b.getItemId()=="increasefontsize"?1:-1,c=this.getDoc(),a=parseInt(c.queryCommandValue("FontSize")||2,10);if((Ext.isSafari&&!Ext.isSafari2)||Ext.isChrome||Ext.isAir){if(a<=10){a=1+d}else{if(a<=13){a=2+d}else{if(a<=16){a=3+d}else{if(a<=18){a=4+d}else{if(a<=24){a=5+d}else{a=6+d}}}}}a=a.constrain(1,6)}else{if(Ext.isSafari){d*=2}a=Math.max(1,a+d)+(Ext.isSafari?"px":0)}this.execCmd("FontSize",a)},onEditorEvent:function(a){this.updateToolbar()},updateToolbar:function(){if(this.readOnly){return}if(!this.activated){this.onFirstFocus();return}var b=this.tb.items.map,c=this.getDoc();if(this.enableFont&&!Ext.isSafari2){var a=(c.queryCommandValue("FontName")||this.defaultFont).toLowerCase();if(a!=this.fontSelect.dom.value){this.fontSelect.dom.value=a}}if(this.enableFormat){b.bold.toggle(c.queryCommandState("bold"));b.italic.toggle(c.queryCommandState("italic"));b.underline.toggle(c.queryCommandState("underline"))}if(this.enableAlignments){b.justifyleft.toggle(c.queryCommandState("justifyleft"));b.justifycenter.toggle(c.queryCommandState("justifycenter"));b.justifyright.toggle(c.queryCommandState("justifyright"))}if(!Ext.isSafari2&&this.enableLists){b.insertorderedlist.toggle(c.queryCommandState("insertorderedlist"));b.insertunorderedlist.toggle(c.queryCommandState("insertunorderedlist"))}Ext.menu.MenuMgr.hideAll();this.syncValue()},relayBtnCmd:function(a){this.relayCmd(a.getItemId())},relayCmd:function(b,a){(function(){this.focus();this.execCmd(b,a);this.updateToolbar()}).defer(10,this)},execCmd:function(b,a){var c=this.getDoc();c.execCommand(b,false,a===undefined?null:a);this.syncValue()},applyCommand:function(b){if(b.ctrlKey){var d=b.getCharCode(),a;if(d>0){d=String.fromCharCode(d);switch(d){case"b":a="bold";break;case"i":a="italic";break;case"u":a="underline";break}if(a){this.win.focus();this.execCmd(a);this.deferFocus();b.preventDefault()}}}},insertAtCursor:function(c){if(!this.activated){return}if(Ext.isIE){this.win.focus();var b=this.getDoc(),a=b.selection.createRange();if(a){a.pasteHTML(c);this.syncValue();this.deferFocus()}}else{this.win.focus();this.execCmd("InsertHTML",c);this.deferFocus()}},fixKeys:function(){if(Ext.isIE){return function(g){var a=g.getKey(),d=this.getDoc(),b;if(a==g.TAB){g.stopEvent();b=d.selection.createRange();if(b){b.collapse(true);b.pasteHTML(" ");this.deferFocus()}}else{if(a==g.ENTER){b=d.selection.createRange();if(b){var c=b.parentElement();if(!c||c.tagName.toLowerCase()!="li"){g.stopEvent();b.pasteHTML("<br />");b.collapse(false);b.select()}}}}}}else{if(Ext.isOpera){return function(b){var a=b.getKey();if(a==b.TAB){b.stopEvent();this.win.focus();this.execCmd("InsertHTML"," ");this.deferFocus()}}}else{if(Ext.isWebKit){return function(b){var a=b.getKey();if(a==b.TAB){b.stopEvent();this.execCmd("InsertText","\t");this.deferFocus()}else{if(a==b.ENTER){b.stopEvent();this.execCmd("InsertHtml","<br /><br />");this.deferFocus()}}}}}}}(),getToolbar:function(){return this.tb},buttonTips:{bold:{title:"Bold (Ctrl+B)",text:"Make the selected text bold.",cls:"x-html-editor-tip"},italic:{title:"Italic (Ctrl+I)",text:"Make the selected text italic.",cls:"x-html-editor-tip"},underline:{title:"Underline (Ctrl+U)",text:"Underline the selected text.",cls:"x-html-editor-tip"},increasefontsize:{title:"Grow Text",text:"Increase the font size.",cls:"x-html-editor-tip"},decreasefontsize:{title:"Shrink Text",text:"Decrease the font size.",cls:"x-html-editor-tip"},backcolor:{title:"Text Highlight Color",text:"Change the background color of the selected text.",cls:"x-html-editor-tip"},forecolor:{title:"Font Color",text:"Change the color of the selected text.",cls:"x-html-editor-tip"},justifyleft:{title:"Align Text Left",text:"Align text to the left.",cls:"x-html-editor-tip"},justifycenter:{title:"Center Text",text:"Center text in the editor.",cls:"x-html-editor-tip"},justifyright:{title:"Align Text Right",text:"Align text to the right.",cls:"x-html-editor-tip"},insertunorderedlist:{title:"Bullet List",text:"Start a bulleted list.",cls:"x-html-editor-tip"},insertorderedlist:{title:"Numbered List",text:"Start a numbered list.",cls:"x-html-editor-tip"},createlink:{title:"Hyperlink",text:"Make the selected text a hyperlink.",cls:"x-html-editor-tip"},sourceedit:{title:"Source Edit",text:"Switch to source editing mode.",cls:"x-html-editor-tip"}}});Ext.reg("htmleditor",Ext.form.HtmlEditor);Ext.form.TimeField=Ext.extend(Ext.form.ComboBox,{minValue:undefined,maxValue:undefined,minText:"The time in this field must be equal to or after {0}",maxText:"The time in this field must be equal to or before {0}",invalidText:"{0} is not a valid time",format:"g:i A",altFormats:"g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A",increment:15,mode:"local",triggerAction:"all",typeAhead:false,initDate:"1/1/2008",initDateFormat:"j/n/Y",initComponent:function(){if(Ext.isDefined(this.minValue)){this.setMinValue(this.minValue,true)}if(Ext.isDefined(this.maxValue)){this.setMaxValue(this.maxValue,true)}if(!this.store){this.generateStore(true)}Ext.form.TimeField.superclass.initComponent.call(this)},setMinValue:function(b,a){this.setLimit(b,true,a);return this},setMaxValue:function(b,a){this.setLimit(b,false,a);return this},generateStore:function(b){var c=this.minValue||new Date(this.initDate).clearTime(),a=this.maxValue||new Date(this.initDate).clearTime().add("mi",(24*60)-1),d=[];while(c<=a){d.push(c.dateFormat(this.format));c=c.add("mi",this.increment)}this.bindStore(d,b)},setLimit:function(b,g,a){var e;if(Ext.isString(b)){e=this.parseDate(b)}else{if(Ext.isDate(b)){e=b}}if(e){var c=new Date(this.initDate).clearTime();c.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds());this[g?"minValue":"maxValue"]=c;if(!a){this.generateStore()}}},getValue:function(){var a=Ext.form.TimeField.superclass.getValue.call(this);return this.formatDate(this.parseDate(a))||""},setValue:function(a){return Ext.form.TimeField.superclass.setValue.call(this,this.formatDate(this.parseDate(a)))},validateValue:Ext.form.DateField.prototype.validateValue,formatDate:Ext.form.DateField.prototype.formatDate,parseDate:function(h){if(!h||Ext.isDate(h)){return h}var k=this.initDate+" ",g=this.initDateFormat+" ",b=Date.parseDate(k+h,g+this.format),c=this.altFormats;if(!b&&c){if(!this.altFormatsArray){this.altFormatsArray=c.split("|")}for(var e=0,d=this.altFormatsArray,a=d.length;e<a&&!b;e++){b=Date.parseDate(k+h,g+d[e])}}return b}});Ext.reg("timefield",Ext.form.TimeField);Ext.form.SliderField=Ext.extend(Ext.form.Field,{useTips:true,tipText:null,actionMode:"wrap",initComponent:function(){var b=Ext.copyTo({id:this.id+"-slider"},this.initialConfig,["vertical","minValue","maxValue","decimalPrecision","keyIncrement","increment","clickToChange","animate"]);if(this.useTips){var a=this.tipText?{getText:this.tipText}:{};b.plugins=[new Ext.slider.Tip(a)]}this.slider=new Ext.Slider(b);Ext.form.SliderField.superclass.initComponent.call(this)},onRender:function(b,a){this.autoCreate={id:this.id,name:this.name,type:"hidden",tag:"input"};Ext.form.SliderField.superclass.onRender.call(this,b,a);this.wrap=this.el.wrap({cls:"x-form-field-wrap"});this.resizeEl=this.positionEl=this.wrap;this.slider.render(this.wrap)},onResize:function(b,c,d,a){Ext.form.SliderField.superclass.onResize.call(this,b,c,d,a);this.slider.setSize(b,c)},initEvents:function(){Ext.form.SliderField.superclass.initEvents.call(this);this.slider.on("change",this.onChange,this)},onChange:function(b,a){this.setValue(a,undefined,true)},onEnable:function(){Ext.form.SliderField.superclass.onEnable.call(this);this.slider.enable()},onDisable:function(){Ext.form.SliderField.superclass.onDisable.call(this);this.slider.disable()},beforeDestroy:function(){Ext.destroy(this.slider);Ext.form.SliderField.superclass.beforeDestroy.call(this)},alignErrorIcon:function(){this.errorIcon.alignTo(this.slider.el,"tl-tr",[2,0])},setMinValue:function(a){this.slider.setMinValue(a);return this},setMaxValue:function(a){this.slider.setMaxValue(a);return this},setValue:function(c,b,a){if(!a){this.slider.setValue(c,b)}return Ext.form.SliderField.superclass.setValue.call(this,this.slider.getValue())},getValue:function(){return this.slider.getValue()}});Ext.reg("sliderfield",Ext.form.SliderField);Ext.form.Label=Ext.extend(Ext.BoxComponent,{onRender:function(b,a){if(!this.el){this.el=document.createElement("label");this.el.id=this.getId();this.el.innerHTML=this.text?Ext.util.Format.htmlEncode(this.text):(this.html||"");if(this.forId){this.el.setAttribute("for",this.forId)}}Ext.form.Label.superclass.onRender.call(this,b,a)},setText:function(a,b){var c=b===false;this[!c?"text":"html"]=a;delete this[c?"text":"html"];if(this.rendered){this.el.dom.innerHTML=b!==false?Ext.util.Format.htmlEncode(a):a}return this}});Ext.reg("label",Ext.form.Label);Ext.form.Action=function(b,a){this.form=b;this.options=a||{}};Ext.form.Action.CLIENT_INVALID="client";Ext.form.Action.SERVER_INVALID="server";Ext.form.Action.CONNECT_FAILURE="connect";Ext.form.Action.LOAD_FAILURE="load";Ext.form.Action.prototype={type:"default",run:function(a){},success:function(a){},handleResponse:function(a){},failure:function(a){this.response=a;this.failureType=Ext.form.Action.CONNECT_FAILURE;this.form.afterAction(this,false)},processResponse:function(a){this.response=a;if(!a.responseText&&!a.responseXML){return true}this.result=this.handleResponse(a);return this.result},getUrl:function(c){var a=this.options.url||this.form.url||this.form.el.dom.action;if(c){var b=this.getParams();if(b){a=Ext.urlAppend(a,b)}}return a},getMethod:function(){return(this.options.method||this.form.method||this.form.el.dom.method||"POST").toUpperCase()},getParams:function(){var a=this.form.baseParams;var b=this.options.params;if(b){if(typeof b=="object"){b=Ext.urlEncode(Ext.applyIf(b,a))}else{if(typeof b=="string"&&a){b+="&"+Ext.urlEncode(a)}}}else{if(a){b=Ext.urlEncode(a)}}return b},createCallback:function(a){var a=a||{};return{success:this.success,failure:this.failure,scope:this,timeout:(a.timeout*1000)||(this.form.timeout*1000),upload:this.form.fileUpload?this.success:undefined}}};Ext.form.Action.Submit=function(b,a){Ext.form.Action.Submit.superclass.constructor.call(this,b,a)};Ext.extend(Ext.form.Action.Submit,Ext.form.Action,{type:"submit",run:function(){var e=this.options,g=this.getMethod(),d=g=="GET";if(e.clientValidation===false||this.form.isValid()){if(e.submitEmptyText===false){var a=this.form.items,c=[],b=function(h){if(h.el.getValue()==h.emptyText){c.push(h);h.el.dom.value=""}if(h.isComposite&&h.rendered){h.items.each(b)}};a.each(b)}Ext.Ajax.request(Ext.apply(this.createCallback(e),{form:this.form.el.dom,url:this.getUrl(d),method:g,headers:e.headers,params:!d?this.getParams():null,isUpload:this.form.fileUpload}));if(e.submitEmptyText===false){Ext.each(c,function(h){if(h.applyEmptyText){h.applyEmptyText()}})}}else{if(e.clientValidation!==false){this.failureType=Ext.form.Action.CLIENT_INVALID;this.form.afterAction(this,false)}}},success:function(b){var a=this.processResponse(b);if(a===true||a.success){this.form.afterAction(this,true);return}if(a.errors){this.form.markInvalid(a.errors)}this.failureType=Ext.form.Action.SERVER_INVALID;this.form.afterAction(this,false)},handleResponse:function(c){if(this.form.errorReader){var b=this.form.errorReader.read(c);var g=[];if(b.records){for(var d=0,a=b.records.length;d<a;d++){var e=b.records[d];g[d]=e.data}}if(g.length<1){g=null}return{success:b.success,errors:g}}return Ext.decode(c.responseText)}});Ext.form.Action.Load=function(b,a){Ext.form.Action.Load.superclass.constructor.call(this,b,a);this.reader=this.form.reader};Ext.extend(Ext.form.Action.Load,Ext.form.Action,{type:"load",run:function(){Ext.Ajax.request(Ext.apply(this.createCallback(this.options),{method:this.getMethod(),url:this.getUrl(false),headers:this.options.headers,params:this.getParams()}))},success:function(b){var a=this.processResponse(b);if(a===true||!a.success||!a.data){this.failureType=Ext.form.Action.LOAD_FAILURE;this.form.afterAction(this,false);return}this.form.clearInvalid();this.form.setValues(a.data);this.form.afterAction(this,true)},handleResponse:function(b){if(this.form.reader){var a=this.form.reader.read(b);var c=a.records&&a.records[0]?a.records[0].data:null;return{success:a.success,data:c}}return Ext.decode(b.responseText)}});Ext.form.Action.DirectLoad=Ext.extend(Ext.form.Action.Load,{constructor:function(b,a){Ext.form.Action.DirectLoad.superclass.constructor.call(this,b,a)},type:"directload",run:function(){var a=this.getParams();a.push(this.success,this);this.form.api.load.apply(window,a)},getParams:function(){var c=[],h={};var e=this.form.baseParams;var g=this.options.params;Ext.apply(h,g,e);var b=this.form.paramOrder;if(b){for(var d=0,a=b.length;d<a;d++){c.push(h[b[d]])}}else{if(this.form.paramsAsHash){c.push(h)}}return c},processResponse:function(a){this.result=a;return a},success:function(a,b){if(b.type==Ext.Direct.exceptions.SERVER){a={}}Ext.form.Action.DirectLoad.superclass.success.call(this,a)}});Ext.form.Action.DirectSubmit=Ext.extend(Ext.form.Action.Submit,{constructor:function(b,a){Ext.form.Action.DirectSubmit.superclass.constructor.call(this,b,a)},type:"directsubmit",run:function(){var a=this.options;if(a.clientValidation===false||this.form.isValid()){this.success.params=this.getParams();this.form.api.submit(this.form.el.dom,this.success,this)}else{if(a.clientValidation!==false){this.failureType=Ext.form.Action.CLIENT_INVALID;this.form.afterAction(this,false)}}},getParams:function(){var c={};var a=this.form.baseParams;var b=this.options.params;Ext.apply(c,b,a);return c},processResponse:function(a){this.result=a;return a},success:function(a,b){if(b.type==Ext.Direct.exceptions.SERVER){a={}}Ext.form.Action.DirectSubmit.superclass.success.call(this,a)}});Ext.form.Action.ACTION_TYPES={load:Ext.form.Action.Load,submit:Ext.form.Action.Submit,directload:Ext.form.Action.DirectLoad,directsubmit:Ext.form.Action.DirectSubmit};Ext.form.VTypes=function(){var c=/^[a-zA-Z_]+$/,d=/^[a-zA-Z0-9_]+$/,b=/^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,a=/(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;return{email:function(e){return b.test(e)},emailText:'This field should be an e-mail address in the format "[email protected]"',emailMask:/[a-z0-9_\.\-@\+]/i,url:function(e){return a.test(e)},urlText:'This field should be a URL in the format "http://www.example.com"',alpha:function(e){return c.test(e)},alphaText:"This field should only contain letters and _",alphaMask:/[a-z_]/i,alphanum:function(e){return d.test(e)},alphanumText:"This field should only contain letters, numbers and _",alphanumMask:/[a-z0-9_]/i}}();Ext.grid.GridPanel=Ext.extend(Ext.Panel,{autoExpandColumn:false,autoExpandMax:1000,autoExpandMin:50,columnLines:false,ddText:"{0} selected row{1}",deferRowRender:true,enableColumnHide:true,enableColumnMove:true,enableDragDrop:false,enableHdMenu:true,loadMask:false,minColumnWidth:25,stripeRows:false,trackMouseOver:true,stateEvents:["columnmove","columnresize","sortchange","groupchange"],view:null,bubbleEvents:[],rendered:false,viewReady:false,initComponent:function(){Ext.grid.GridPanel.superclass.initComponent.call(this);if(this.columnLines){this.cls=(this.cls||"")+" x-grid-with-col-lines"}this.autoScroll=false;this.autoWidth=false;if(Ext.isArray(this.columns)){this.colModel=new Ext.grid.ColumnModel(this.columns);delete this.columns}if(this.ds){this.store=this.ds;delete this.ds}if(this.cm){this.colModel=this.cm;delete this.cm}if(this.sm){this.selModel=this.sm;delete this.sm}this.store=Ext.StoreMgr.lookup(this.store);this.addEvents("click","dblclick","contextmenu","mousedown","mouseup","mouseover","mouseout","keypress","keydown","cellmousedown","rowmousedown","headermousedown","groupmousedown","rowbodymousedown","containermousedown","cellclick","celldblclick","rowclick","rowdblclick","headerclick","headerdblclick","groupclick","groupdblclick","containerclick","containerdblclick","rowbodyclick","rowbodydblclick","rowcontextmenu","cellcontextmenu","headercontextmenu","groupcontextmenu","containercontextmenu","rowbodycontextmenu","bodyscroll","columnresize","columnmove","sortchange","groupchange","reconfigure","viewready")},onRender:function(d,a){Ext.grid.GridPanel.superclass.onRender.apply(this,arguments);var e=this.getGridEl();this.el.addClass("x-grid-panel");this.mon(e,{scope:this,mousedown:this.onMouseDown,click:this.onClick,dblclick:this.onDblClick,contextmenu:this.onContextMenu});this.relayEvents(e,["mousedown","mouseup","mouseover","mouseout","keypress","keydown"]);var b=this.getView();b.init(this);b.render();this.getSelectionModel().init(this)},initEvents:function(){Ext.grid.GridPanel.superclass.initEvents.call(this);if(this.loadMask){this.loadMask=new Ext.LoadMask(this.bwrap,Ext.apply({store:this.store},this.loadMask))}},initStateEvents:function(){Ext.grid.GridPanel.superclass.initStateEvents.call(this);this.mon(this.colModel,"hiddenchange",this.saveState,this,{delay:100})},applyState:function(a){var l=this.colModel,g=a.columns,k=this.store,n,h,m;if(g){for(var d=0,e=g.length;d<e;d++){n=g[d];h=l.getColumnById(n.id);if(h){m=l.getIndexById(n.id);l.setState(m,{hidden:n.hidden,width:n.width,sortable:n.sortable});if(m!=d){l.moveColumn(m,d)}}}}if(k){n=a.sort;if(n){k[k.remoteSort?"setDefaultSort":"sort"](n.field,n.direction)}n=a.group;if(k.groupBy){if(n){k.groupBy(n)}else{k.clearGrouping()}}}var b=Ext.apply({},a);delete b.columns;delete b.sort;Ext.grid.GridPanel.superclass.applyState.call(this,b)},getState:function(){var g={columns:[]},b=this.store,e,a;for(var d=0,h;(h=this.colModel.config[d]);d++){g.columns[d]={id:h.id,width:h.width};if(h.hidden){g.columns[d].hidden=true}if(h.sortable){g.columns[d].sortable=true}}if(b){e=b.getSortState();if(e){g.sort=e}if(b.getGroupState){a=b.getGroupState();if(a){g.group=a}}}return g},afterRender:function(){Ext.grid.GridPanel.superclass.afterRender.call(this);var a=this.view;this.on("bodyresize",a.layout,a);a.layout(true);if(this.deferRowRender){if(!this.deferRowRenderTask){this.deferRowRenderTask=new Ext.util.DelayedTask(a.afterRender,this.view)}this.deferRowRenderTask.delay(10)}else{a.afterRender()}this.viewReady=true},reconfigure:function(a,b){var c=this.rendered;if(c){if(this.loadMask){this.loadMask.destroy();this.loadMask=new Ext.LoadMask(this.bwrap,Ext.apply({},{store:a},this.initialConfig.loadMask))}}if(this.view){this.view.initData(a,b)}this.store=a;this.colModel=b;if(c){this.view.refresh(true)}this.fireEvent("reconfigure",this,a,b)},onDestroy:function(){if(this.deferRowRenderTask&&this.deferRowRenderTask.cancel){this.deferRowRenderTask.cancel()}if(this.rendered){Ext.destroy(this.view,this.loadMask)}else{if(this.store&&this.store.autoDestroy){this.store.destroy()}}Ext.destroy(this.colModel,this.selModel);this.store=this.selModel=this.colModel=this.view=this.loadMask=null;Ext.grid.GridPanel.superclass.onDestroy.call(this)},processEvent:function(a,b){this.view.processEvent(a,b)},onClick:function(a){this.processEvent("click",a)},onMouseDown:function(a){this.processEvent("mousedown",a)},onContextMenu:function(b,a){this.processEvent("contextmenu",b)},onDblClick:function(a){this.processEvent("dblclick",a)},walkCells:function(l,c,b,e,k){var i=this.colModel,g=i.getColumnCount(),a=this.store,h=a.getCount(),d=true;if(b<0){if(c<0){l--;d=false}while(l>=0){if(!d){c=g-1}d=false;while(c>=0){if(e.call(k||this,l,c,i)===true){return[l,c]}c--}l--}}else{if(c>=g){l++;d=false}while(l<h){if(!d){c=0}d=false;while(c<g){if(e.call(k||this,l,c,i)===true){return[l,c]}c++}l++}}return null},getGridEl:function(){return this.body},stopEditing:Ext.emptyFn,getSelectionModel:function(){if(!this.selModel){this.selModel=new Ext.grid.RowSelectionModel(this.disableSelection?{selectRow:Ext.emptyFn}:null)}return this.selModel},getStore:function(){return this.store},getColumnModel:function(){return this.colModel},getView:function(){if(!this.view){this.view=new Ext.grid.GridView(this.viewConfig)}return this.view},getDragDropText:function(){var a=this.selModel.getCount();return String.format(this.ddText,a,a==1?"":"s")}});Ext.reg("grid",Ext.grid.GridPanel);Ext.grid.PivotGrid=Ext.extend(Ext.grid.GridPanel,{aggregator:"sum",renderer:undefined,initComponent:function(){Ext.grid.PivotGrid.superclass.initComponent.apply(this,arguments);this.initAxes();this.enableColumnResize=false;this.viewConfig=Ext.apply(this.viewConfig||{},{forceFit:true});this.colModel=new Ext.grid.ColumnModel({})},getAggregator:function(){if(typeof this.aggregator=="string"){return Ext.grid.PivotAggregatorMgr.types[this.aggregator]}else{return this.aggregator}},setAggregator:function(a){this.aggregator=a},setMeasure:function(a){this.measure=a},setLeftAxis:function(b,a){this.leftAxis=b;if(a){this.view.refresh()}},setTopAxis:function(b,a){this.topAxis=b;if(a){this.view.refresh()}},initAxes:function(){var a=Ext.grid.PivotAxis;if(!(this.leftAxis instanceof a)){this.setLeftAxis(new a({orientation:"vertical",dimensions:this.leftAxis||[],store:this.store}))}if(!(this.topAxis instanceof a)){this.setTopAxis(new a({orientation:"horizontal",dimensions:this.topAxis||[],store:this.store}))}},extractData:function(){var c=this.store.data.items,s=c.length,q=[],h,g,e,d;if(s==0){return[]}var l=this.leftAxis.getTuples(),o=l.length,m=this.topAxis.getTuples(),a=m.length,b=this.getAggregator();for(g=0;g<s;g++){h=c[g];for(e=0;e<o;e++){q[e]=q[e]||[];if(l[e].matcher(h)===true){for(d=0;d<a;d++){q[e][d]=q[e][d]||[];if(m[d].matcher(h)){q[e][d].push(h)}}}}}var n=q.length,p,r;for(g=0;g<n;g++){r=q[g];p=r.length;for(e=0;e<p;e++){q[g][e]=b(q[g][e],this.measure)}}return q},getView:function(){if(!this.view){this.view=new Ext.grid.PivotGridView(this.viewConfig)}return this.view}});Ext.reg("pivotgrid",Ext.grid.PivotGrid);Ext.grid.PivotAggregatorMgr=new Ext.AbstractManager();Ext.grid.PivotAggregatorMgr.registerType("sum",function(a,c){var e=a.length,d=0,b;for(b=0;b<e;b++){d+=a[b].get(c)}return d});Ext.grid.PivotAggregatorMgr.registerType("avg",function(a,c){var e=a.length,d=0,b;for(b=0;b<e;b++){d+=a[b].get(c)}return(d/e)||"n/a"});Ext.grid.PivotAggregatorMgr.registerType("min",function(a,c){var e=[],d=a.length,b;for(b=0;b<d;b++){e.push(a[b].get(c))}return Math.min.apply(this,e)||"n/a"});Ext.grid.PivotAggregatorMgr.registerType("max",function(a,c){var e=[],d=a.length,b;for(b=0;b<d;b++){e.push(a[b].get(c))}return Math.max.apply(this,e)||"n/a"});Ext.grid.PivotAggregatorMgr.registerType("count",function(a,b){return a.length});Ext.grid.GridView=Ext.extend(Ext.util.Observable,{deferEmptyText:true,scrollOffset:undefined,autoFill:false,forceFit:false,sortClasses:["sort-asc","sort-desc"],sortAscText:"Sort Ascending",sortDescText:"Sort Descending",columnsText:"Columns",selectedRowClass:"x-grid3-row-selected",borderWidth:2,tdClass:"x-grid3-cell",hdCls:"x-grid3-hd",markDirty:true,cellSelectorDepth:4,rowSelectorDepth:10,rowBodySelectorDepth:10,cellSelector:"td.x-grid3-cell",rowSelector:"div.x-grid3-row",rowBodySelector:"div.x-grid3-row-body",firstRowCls:"x-grid3-row-first",lastRowCls:"x-grid3-row-last",rowClsRe:/(?:^|\s+)x-grid3-row-(first|last|alt)(?:\s+|$)/g,headerMenuOpenCls:"x-grid3-hd-menu-open",rowOverCls:"x-grid3-row-over",constructor:function(a){Ext.apply(this,a);this.addEvents("beforerowremoved","beforerowsinserted","beforerefresh","rowremoved","rowsinserted","rowupdated","refresh");Ext.grid.GridView.superclass.constructor.call(this)},masterTpl:new Ext.Template('<div class="x-grid3" hidefocus="true">','<div class="x-grid3-viewport">','<div class="x-grid3-header">','<div class="x-grid3-header-inner">','<div class="x-grid3-header-offset" style="{ostyle}">{header}</div>',"</div>",'<div class="x-clear"></div>',"</div>",'<div class="x-grid3-scroller">','<div class="x-grid3-body" style="{bstyle}">{body}</div>','<a href="#" class="x-grid3-focus" tabIndex="-1"></a>',"</div>","</div>",'<div class="x-grid3-resize-marker"> </div>','<div class="x-grid3-resize-proxy"> </div>',"</div>"),headerTpl:new Ext.Template('<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',"<thead>",'<tr class="x-grid3-hd-row">{cells}</tr>',"</thead>","</table>"),bodyTpl:new Ext.Template("{rows}"),cellTpl:new Ext.Template('<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>','<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>',"</td>"),initTemplates:function(){var c=this.templates||{},d,b,g=new Ext.Template('<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id} {css}" style="{style}">','<div {tooltip} {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">',this.grid.enableHdMenu?'<a class="x-grid3-hd-btn" href="#"></a>':"","{value}",'<img alt="" class="x-grid3-sort-icon" src="',Ext.BLANK_IMAGE_URL,'" />',"</div>","</td>"),a=['<tr class="x-grid3-row-body-tr" style="{bodyStyle}">','<td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on">','<div class="x-grid3-row-body">{body}</div>',"</td>","</tr>"].join(""),e=['<table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',"<tbody>","<tr>{cells}</tr>",this.enableRowBody?a:"","</tbody>","</table>"].join("");Ext.applyIf(c,{hcell:g,cell:this.cellTpl,body:this.bodyTpl,header:this.headerTpl,master:this.masterTpl,row:new Ext.Template('<div class="x-grid3-row {alt}" style="{tstyle}">'+e+"</div>"),rowInner:new Ext.Template(e)});for(b in c){d=c[b];if(d&&Ext.isFunction(d.compile)&&!d.compiled){d.disableFormats=true;d.compile()}}this.templates=c;this.colRe=new RegExp("x-grid3-td-([^\\s]+)","")},fly:function(a){if(!this._flyweight){this._flyweight=new Ext.Element.Flyweight(document.body)}this._flyweight.dom=a;return this._flyweight},getEditorParent:function(){return this.scroller.dom},initElements:function(){var b=Ext.Element,d=Ext.get(this.grid.getGridEl().dom.firstChild),e=new b(d.child("div.x-grid3-viewport")),c=new b(e.child("div.x-grid3-header")),a=new b(e.child("div.x-grid3-scroller"));if(this.grid.hideHeaders){c.setDisplayed(false)}if(this.forceFit){a.setStyle("overflow-x","hidden")}Ext.apply(this,{el:d,mainWrap:e,scroller:a,mainHd:c,innerHd:c.child("div.x-grid3-header-inner").dom,mainBody:new b(b.fly(a).child("div.x-grid3-body")),focusEl:new b(b.fly(a).child("a")),resizeMarker:new b(d.child("div.x-grid3-resize-marker")),resizeProxy:new b(d.child("div.x-grid3-resize-proxy"))});this.focusEl.swallowEvent("click",true)},getRows:function(){return this.hasRows()?this.mainBody.dom.childNodes:[]},findCell:function(a){if(!a){return false}return this.fly(a).findParent(this.cellSelector,this.cellSelectorDepth)},findCellIndex:function(d,c){var b=this.findCell(d),a;if(b){a=this.fly(b).hasClass(c);if(!c||a){return this.getCellIndex(b)}}return false},getCellIndex:function(b){if(b){var a=b.className.match(this.colRe);if(a&&a[1]){return this.cm.getIndexById(a[1])}}return false},findHeaderCell:function(b){var a=this.findCell(b);return a&&this.fly(a).hasClass(this.hdCls)?a:null},findHeaderIndex:function(a){return this.findCellIndex(a,this.hdCls)},findRow:function(a){if(!a){return false}return this.fly(a).findParent(this.rowSelector,this.rowSelectorDepth)},findRowIndex:function(a){var b=this.findRow(a);return b?b.rowIndex:false},findRowBody:function(a){if(!a){return false}return this.fly(a).findParent(this.rowBodySelector,this.rowBodySelectorDepth)},getRow:function(a){return this.getRows()[a]},getCell:function(b,a){return Ext.fly(this.getRow(b)).query(this.cellSelector)[a]},getHeaderCell:function(a){return this.mainHd.dom.getElementsByTagName("td")[a]},addRowClass:function(b,a){var c=this.getRow(b);if(c){this.fly(c).addClass(a)}},removeRowClass:function(c,a){var b=this.getRow(c);if(b){this.fly(b).removeClass(a)}},removeRow:function(a){Ext.removeNode(this.getRow(a));this.syncFocusEl(a)},removeRows:function(c,a){var b=this.mainBody.dom,d;for(d=c;d<=a;d++){Ext.removeNode(b.childNodes[c])}this.syncFocusEl(c)},getScrollState:function(){var a=this.scroller.dom;return{left:a.scrollLeft,top:a.scrollTop}},restoreScroll:function(a){var b=this.scroller.dom;b.scrollLeft=a.left;b.scrollTop=a.top},scrollToTop:function(){var a=this.scroller.dom;a.scrollTop=0;a.scrollLeft=0},syncScroll:function(){this.syncHeaderScroll();var a=this.scroller.dom;this.grid.fireEvent("bodyscroll",a.scrollLeft,a.scrollTop)},syncHeaderScroll:function(){var a=this.innerHd,b=this.scroller.dom.scrollLeft;a.scrollLeft=b;a.scrollLeft=b},updateSortIcon:function(d,c){var a=this.sortClasses,b=a[c=="DESC"?1:0],e=this.mainHd.select("td").removeClass(a);e.item(d).addClass(b)},updateAllColumnWidths:function(){var e=this.getTotalWidth(),k=this.cm.getColumnCount(),m=this.getRows(),g=m.length,b=[],l,a,h,d,c;for(d=0;d<k;d++){b[d]=this.getColumnWidth(d);this.getHeaderCell(d).style.width=b[d]}this.updateHeaderWidth();for(d=0;d<g;d++){l=m[d];l.style.width=e;a=l.firstChild;if(a){a.style.width=e;h=a.rows[0];for(c=0;c<k;c++){h.childNodes[c].style.width=b[c]}}}this.onAllColumnWidthsUpdated(b,e)},updateColumnWidth:function(d,b){var c=this.getColumnWidth(d),k=this.getTotalWidth(),h=this.getHeaderCell(d),a=this.getRows(),e=a.length,m,g,l;this.updateHeaderWidth();h.style.width=c;for(g=0;g<e;g++){m=a[g];l=m.firstChild;m.style.width=k;if(l){l.style.width=k;l.rows[0].childNodes[d].style.width=c}}this.onColumnWidthUpdated(d,c,k)},updateColumnHidden:function(b,k){var h=this.getTotalWidth(),l=k?"none":"",g=this.getHeaderCell(b),a=this.getRows(),d=a.length,m,c,e;this.updateHeaderWidth();g.style.display=l;for(e=0;e<d;e++){m=a[e];m.style.width=h;c=m.firstChild;if(c){c.style.width=h;c.rows[0].childNodes[b].style.display=l}}this.onColumnHiddenUpdated(b,k,h);delete this.lastViewWidth;this.layout()},doRender:function(d,v,m,a,r,t){var h=this.templates,c=h.cell,y=h.row,o=r-1,b="width:"+this.getTotalWidth()+";",k=[],l=[],n={tstyle:b},q={},w=v.length,x,g,e,u,s,p;for(s=0;s<w;s++){e=v[s];l=[];p=s+a;for(u=0;u<r;u++){g=d[u];q.id=g.id;q.css=u===0?"x-grid3-cell-first ":(u==o?"x-grid3-cell-last ":"");q.attr=q.cellAttr="";q.style=g.style;q.value=g.renderer.call(g.scope,e.data[g.name],q,e,p,u,m);if(Ext.isEmpty(q.value)){q.value=" "}if(this.markDirty&&e.dirty&&typeof e.modified[g.name]!="undefined"){q.css+=" x-grid3-dirty-cell"}l[l.length]=c.apply(q)}x=[];if(t&&((p+1)%2===0)){x[0]="x-grid3-row-alt"}if(e.dirty){x[1]=" x-grid3-dirty-row"}n.cols=r;if(this.getRowClass){x[2]=this.getRowClass(e,p,n,m)}n.alt=x.join(" ");n.cells=l.join("");k[k.length]=y.apply(n)}return k.join("")},processRows:function(a,g){if(!this.ds||this.ds.getCount()<1){return}var d=this.getRows(),c=d.length,e,b;g=g||!this.grid.stripeRows;a=a||0;for(b=0;b<c;b++){e=d[b];if(e){e.rowIndex=b;if(!g){e.className=e.className.replace(this.rowClsRe," ");if((b+1)%2===0){e.className+=" x-grid3-row-alt"}}}}if(a===0){Ext.fly(d[0]).addClass(this.firstRowCls)}Ext.fly(d[c-1]).addClass(this.lastRowCls)},afterRender:function(){if(!this.ds||!this.cm){return}this.mainBody.dom.innerHTML=this.renderBody()||" ";this.processRows(0,true);if(this.deferEmptyText!==true){this.applyEmptyText()}this.grid.fireEvent("viewready",this.grid)},afterRenderUI:function(){var a=this.grid;this.initElements();Ext.fly(this.innerHd).on("click",this.handleHdDown,this);this.mainHd.on({scope:this,mouseover:this.handleHdOver,mouseout:this.handleHdOut,mousemove:this.handleHdMove});this.scroller.on("scroll",this.syncScroll,this);if(a.enableColumnResize!==false){this.splitZone=new Ext.grid.GridView.SplitDragZone(a,this.mainHd.dom)}if(a.enableColumnMove){this.columnDrag=new Ext.grid.GridView.ColumnDragZone(a,this.innerHd);this.columnDrop=new Ext.grid.HeaderDropZone(a,this.mainHd.dom)}if(a.enableHdMenu!==false){this.hmenu=new Ext.menu.Menu({id:a.id+"-hctx"});this.hmenu.add({itemId:"asc",text:this.sortAscText,cls:"xg-hmenu-sort-asc"},{itemId:"desc",text:this.sortDescText,cls:"xg-hmenu-sort-desc"});if(a.enableColumnHide!==false){this.colMenu=new Ext.menu.Menu({id:a.id+"-hcols-menu"});this.colMenu.on({scope:this,beforeshow:this.beforeColMenuShow,itemclick:this.handleHdMenuClick});this.hmenu.add("-",{itemId:"columns",hideOnClick:false,text:this.columnsText,menu:this.colMenu,iconCls:"x-cols-icon"})}this.hmenu.on("itemclick",this.handleHdMenuClick,this)}if(a.trackMouseOver){this.mainBody.on({scope:this,mouseover:this.onRowOver,mouseout:this.onRowOut})}if(a.enableDragDrop||a.enableDrag){this.dragZone=new Ext.grid.GridDragZone(a,{ddGroup:a.ddGroup||"GridDD"})}this.updateHeaderSortState()},renderUI:function(){var a=this.templates;return a.master.apply({body:a.body.apply({rows:" "}),header:this.renderHeaders(),ostyle:"width:"+this.getOffsetWidth()+";",bstyle:"width:"+this.getTotalWidth()+";"})},processEvent:function(b,h){var i=h.getTarget(),a=this.grid,d=this.findHeaderIndex(i),l,k,c,g;a.fireEvent(b,h);if(d!==false){a.fireEvent("header"+b,a,d,h)}else{l=this.findRowIndex(i);if(l!==false){k=this.findCellIndex(i);if(k!==false){c=a.colModel.getColumnAt(k);if(a.fireEvent("cell"+b,a,l,k,h)!==false){if(!c||(c.processEvent&&(c.processEvent(b,h,a,l,k)!==false))){a.fireEvent("row"+b,a,l,h)}}}else{if(a.fireEvent("row"+b,a,l,h)!==false){(g=this.findRowBody(i))&&a.fireEvent("rowbody"+b,a,l,h)}}}else{a.fireEvent("container"+b,a,h)}}},layout:function(k){if(!this.mainBody){return}var a=this.grid,d=a.getGridEl(),c=d.getSize(true),i=c.width,b=c.height,h=this.scroller,g,e,l;if(i<20||b<20){return}if(a.autoHeight){g=h.dom.style;g.overflow="visible";if(Ext.isWebKit){g.position="static"}}else{this.el.setSize(i,b);e=this.mainHd.getHeight();l=b-e;h.setSize(i,l);if(this.innerHd){this.innerHd.style.width=(i)+"px"}}if(this.forceFit||(k===true&&this.autoFill)){if(this.lastViewWidth!=i){this.fitColumns(false,false);this.lastViewWidth=i}}else{this.autoExpand();this.syncHeaderScroll()}this.onLayout(i,l)},onLayout:function(a,b){},onColumnWidthUpdated:function(c,a,b){},onAllColumnWidthsUpdated:function(a,b){},onColumnHiddenUpdated:function(b,c,a){},updateColumnText:function(a,b){},afterMove:function(a){},init:function(a){this.grid=a;this.initTemplates();this.initData(a.store,a.colModel);this.initUI(a)},getColumnId:function(a){return this.cm.getColumnId(a)},getOffsetWidth:function(){return(this.cm.getTotalWidth()+this.getScrollOffset())+"px"},getScrollOffset:function(){return Ext.num(this.scrollOffset,Ext.getScrollBarWidth())},renderHeaders:function(){var e=this.cm,g=this.templates,a=g.hcell,d={},h=e.getColumnCount(),k=h-1,l=[],c,b;for(c=0;c<h;c++){if(c==0){b="x-grid3-cell-first "}else{b=c==k?"x-grid3-cell-last ":""}d={id:e.getColumnId(c),value:e.getColumnHeader(c)||"",style:this.getColumnStyle(c,true),css:b,tooltip:this.getColumnTooltip(c)};if(e.config[c].align=="right"){d.istyle="padding-right: 16px;"}else{delete d.istyle}l[c]=a.apply(d)}return g.header.apply({cells:l.join(""),tstyle:String.format("width: {0};",this.getTotalWidth())})},getColumnTooltip:function(a){var b=this.cm.getColumnTooltip(a);if(b){if(Ext.QuickTips.isEnabled()){return'ext:qtip="'+b+'"'}else{return'title="'+b+'"'}}return""},beforeUpdate:function(){this.grid.stopEditing(true)},updateHeaders:function(){this.innerHd.firstChild.innerHTML=this.renderHeaders();this.updateHeaderWidth(false)},updateHeaderWidth:function(c){var b=this.innerHd.firstChild,a=this.getTotalWidth();b.style.width=this.getOffsetWidth();b.firstChild.style.width=a;if(c!==false){this.mainBody.dom.style.width=a}},focusRow:function(a){this.focusCell(a,0,false)},focusCell:function(d,b,c){this.syncFocusEl(this.ensureVisible(d,b,c));var a=this.focusEl;if(Ext.isGecko){a.focus()}else{a.focus.defer(1,a)}},resolveCell:function(h,d,g){if(!Ext.isNumber(h)){h=h.rowIndex}if(!this.ds){return null}if(h<0||h>=this.ds.getCount()){return null}d=(d!==undefined?d:0);var c=this.getRow(h),b=this.cm,e=b.getColumnCount(),a;if(!(g===false&&d===0)){while(d<e&&b.isHidden(d)){d++}a=this.getCell(h,d)}return{row:c,cell:a}},getResolvedXY:function(b){if(!b){return null}var a=b.cell,c=b.row;if(a){return Ext.fly(a).getXY()}else{return[this.el.getX(),Ext.fly(c).getY()]}},syncFocusEl:function(d,a,c){var b=d;if(!Ext.isArray(b)){d=Math.min(d,Math.max(0,this.getRows().length-1));if(isNaN(d)){return}b=this.getResolvedXY(this.resolveCell(d,a,c))}this.focusEl.setXY(b||this.scroller.getXY())},ensureVisible:function(u,g,e){var s=this.resolveCell(u,g,e);if(!s||!s.row){return null}var l=s.row,h=s.cell,o=this.scroller.dom,d=l,t=0,q=this.el.dom;while(d&&d!=q){t+=d.offsetTop;d=d.offsetParent}t-=this.mainHd.dom.offsetHeight;q=parseInt(o.scrollTop,10);var r=t+l.offsetHeight,a=o.clientHeight,n=q+a;if(t<q){o.scrollTop=t}else{if(r>n){o.scrollTop=r-a}}if(e!==false){var m=parseInt(h.offsetLeft,10),k=m+h.offsetWidth,i=parseInt(o.scrollLeft,10),b=i+o.clientWidth;if(m<i){o.scrollLeft=m}else{if(k>b){o.scrollLeft=k-o.clientWidth}}}return this.getResolvedXY(s)},insertRows:function(a,i,e,h){var d=a.getCount()-1;if(!h&&i===0&&e>=d){this.fireEvent("beforerowsinserted",this,i,e);this.refresh();this.fireEvent("rowsinserted",this,i,e)}else{if(!h){this.fireEvent("beforerowsinserted",this,i,e)}var b=this.renderRows(i,e),g=this.getRow(i);if(g){if(i===0){Ext.fly(this.getRow(0)).removeClass(this.firstRowCls)}Ext.DomHelper.insertHtml("beforeBegin",g,b)}else{var c=this.getRow(d-1);if(c){Ext.fly(c).removeClass(this.lastRowCls)}Ext.DomHelper.insertHtml("beforeEnd",this.mainBody.dom,b)}if(!h){this.processRows(i);this.fireEvent("rowsinserted",this,i,e)}else{if(i===0||i>=d){Ext.fly(this.getRow(i)).addClass(i===0?this.firstRowCls:this.lastRowCls)}}}this.syncFocusEl(i)},deleteRows:function(a,c,b){if(a.getRowCount()<1){this.refresh()}else{this.fireEvent("beforerowsdeleted",this,c,b);this.removeRows(c,b);this.processRows(c);this.fireEvent("rowsdeleted",this,c,b)}},getColumnStyle:function(b,d){var a=this.cm,g=a.config,c=d?"":g[b].css||"",e=g[b].align;c+=String.format("width: {0};",this.getColumnWidth(b));if(a.isHidden(b)){c+="display: none; "}if(e){c+=String.format("text-align: {0};",e)}return c},getColumnWidth:function(b){var c=this.cm.getColumnWidth(b),a=this.borderWidth;if(Ext.isNumber(c)){if(Ext.isBorderBox||(Ext.isWebKit&&!Ext.isSafari2)){return c+"px"}else{return Math.max(c-a,0)+"px"}}else{return c}},getTotalWidth:function(){return this.cm.getTotalWidth()+"px"},fitColumns:function(g,k,h){var a=this.grid,m=this.cm,t=m.getTotalWidth(false),r=this.getGridInnerWidth(),s=r-t,c=[],p=0,o=0,v,d,q;if(r<20||s===0){return false}var e=m.getColumnCount(true),n=m.getColumnCount(false),b=e-(Ext.isNumber(h)?1:0);if(b===0){b=1;h=undefined}for(q=0;q<n;q++){if(!m.isFixed(q)&&q!==h){v=m.getColumnWidth(q);c.push(q,v);if(!m.isHidden(q)){p=q;o+=v}}}d=(r-m.getTotalWidth())/o;while(c.length){v=c.pop();q=c.pop();m.setColumnWidth(q,Math.max(a.minColumnWidth,Math.floor(v+v*d)),true)}t=m.getTotalWidth(false);if(t>r){var u=(b==e)?p:h,l=Math.max(1,m.getColumnWidth(u)-(t-r));m.setColumnWidth(u,l,true)}if(g!==true){this.updateAllColumnWidths()}return true},autoExpand:function(l){var a=this.grid,i=this.cm,e=this.getGridInnerWidth(),c=i.getTotalWidth(false),g=a.autoExpandColumn;if(!this.userResized&&g){if(e!=c){var k=i.getIndexById(g),b=i.getColumnWidth(k),h=e-c+b,d=Math.min(Math.max(h,a.autoExpandMin),a.autoExpandMax);if(b!=d){i.setColumnWidth(k,d,true);if(l!==true){this.updateColumnWidth(k,d)}}}}},getGridInnerWidth:function(){return this.grid.getGridEl().getWidth(true)-this.getScrollOffset()},getColumnData:function(){var e=[],c=this.cm,g=c.getColumnCount(),a=this.ds.fields,d,b;for(d=0;d<g;d++){b=c.getDataIndex(d);e[d]={name:Ext.isDefined(b)?b:(a.get(d)?a.get(d).name:undefined),renderer:c.getRenderer(d),scope:c.getRendererScope(d),id:c.getColumnId(d),style:this.getColumnStyle(d)}}return e},renderRows:function(i,c){var a=this.grid,g=a.store,k=a.stripeRows,e=a.colModel,h=e.getColumnCount(),d=g.getCount(),b;if(d<1){return""}i=i||0;c=Ext.isDefined(c)?c:d-1;b=g.getRange(i,c);return this.doRender(this.getColumnData(),b,g,i,h,k)},renderBody:function(){var a=this.renderRows()||" ";return this.templates.body.apply({rows:a})},refreshRow:function(g){var m=this.ds,n=this.cm.getColumnCount(),c=this.getColumnData(),o=n-1,q=["x-grid3-row"],e={tstyle:String.format("width: {0};",this.getTotalWidth())},a=[],l=this.templates.cell,k,r,b,p,h,d;if(Ext.isNumber(g)){k=g;g=m.getAt(k)}else{k=m.indexOf(g)}if(!g||k<0){return}for(d=0;d<n;d++){b=c[d];if(d==0){h="x-grid3-cell-first"}else{h=(d==o)?"x-grid3-cell-last ":""}p={id:b.id,style:b.style,css:h,attr:"",cellAttr:""};p.value=b.renderer.call(b.scope,g.data[b.name],p,g,k,d,m);if(Ext.isEmpty(p.value)){p.value=" "}if(this.markDirty&&g.dirty&&typeof g.modified[b.name]!="undefined"){p.css+=" x-grid3-dirty-cell"}a[d]=l.apply(p)}r=this.getRow(k);r.className="";if(this.grid.stripeRows&&((k+1)%2===0)){q.push("x-grid3-row-alt")}if(this.getRowClass){e.cols=n;q.push(this.getRowClass(g,k,e,m))}this.fly(r).addClass(q).setStyle(e.tstyle);e.cells=a.join("");r.innerHTML=this.templates.rowInner.apply(e);this.fireEvent("rowupdated",this,k,g)},refresh:function(b){this.fireEvent("beforerefresh",this);this.grid.stopEditing(true);var a=this.renderBody();this.mainBody.update(a).setWidth(this.getTotalWidth());if(b===true){this.updateHeaders();this.updateHeaderSortState()}this.processRows(0,true);this.layout();this.applyEmptyText();this.fireEvent("refresh",this)},applyEmptyText:function(){if(this.emptyText&&!this.hasRows()){this.mainBody.update('<div class="x-grid-empty">'+this.emptyText+"</div>")}},updateHeaderSortState:function(){var b=this.ds.getSortState();if(!b){return}if(!this.sortState||(this.sortState.field!=b.field||this.sortState.direction!=b.direction)){this.grid.fireEvent("sortchange",this.grid,b)}this.sortState=b;var c=this.cm.findColumnIndex(b.field);if(c!=-1){var a=b.direction;this.updateSortIcon(c,a)}},clearHeaderSortState:function(){if(!this.sortState){return}this.grid.fireEvent("sortchange",this.grid,null);this.mainHd.select("td").removeClass(this.sortClasses);delete this.sortState},destroy:function(){var k=this,a=k.grid,d=a.getGridEl(),i=k.dragZone,g=k.splitZone,h=k.columnDrag,e=k.columnDrop,l=k.scrollToTopTask,c,b;if(l&&l.cancel){l.cancel()}Ext.destroyMembers(k,"colMenu","hmenu");k.initData(null,null);k.purgeListeners();Ext.fly(k.innerHd).un("click",k.handleHdDown,k);if(a.enableColumnMove){c=h.dragData;b=h.proxy;Ext.destroy(h.el,b.ghost,b.el,e.el,e.proxyTop,e.proxyBottom,c.ddel,c.header);if(b.anim){Ext.destroy(b.anim)}delete b.ghost;delete c.ddel;delete c.header;h.destroy();delete Ext.dd.DDM.locationCache[h.id];delete h._domRef;delete e.proxyTop;delete e.proxyBottom;e.destroy();delete Ext.dd.DDM.locationCache["gridHeader"+d.id];delete e._domRef;delete Ext.dd.DDM.ids[e.ddGroup]}if(g){g.destroy();delete g._domRef;delete Ext.dd.DDM.ids["gridSplitters"+d.id]}Ext.fly(k.innerHd).removeAllListeners();Ext.removeNode(k.innerHd);delete k.innerHd;Ext.destroy(k.el,k.mainWrap,k.mainHd,k.scroller,k.mainBody,k.focusEl,k.resizeMarker,k.resizeProxy,k.activeHdBtn,k._flyweight,i,g);delete a.container;if(i){i.destroy()}Ext.dd.DDM.currentTarget=null;delete Ext.dd.DDM.locationCache[d.id];Ext.EventManager.removeResizeListener(k.onWindowResize,k)},onDenyColumnHide:function(){},render:function(){if(this.autoFill){var a=this.grid.ownerCt;if(a&&a.getLayout()){a.on("afterlayout",function(){this.fitColumns(true,true);this.updateHeaders();this.updateHeaderSortState()},this,{single:true})}}else{if(this.forceFit){this.fitColumns(true,false)}else{if(this.grid.autoExpandColumn){this.autoExpand(true)}}}this.grid.getGridEl().dom.innerHTML=this.renderUI();this.afterRenderUI()},initData:function(a,e){var b=this;if(b.ds){var d=b.ds;d.un("add",b.onAdd,b);d.un("load",b.onLoad,b);d.un("clear",b.onClear,b);d.un("remove",b.onRemove,b);d.un("update",b.onUpdate,b);d.un("datachanged",b.onDataChange,b);if(d!==a&&d.autoDestroy){d.destroy()}}if(a){a.on({scope:b,load:b.onLoad,add:b.onAdd,remove:b.onRemove,update:b.onUpdate,clear:b.onClear,datachanged:b.onDataChange})}if(b.cm){var c=b.cm;c.un("configchange",b.onColConfigChange,b);c.un("widthchange",b.onColWidthChange,b);c.un("headerchange",b.onHeaderChange,b);c.un("hiddenchange",b.onHiddenChange,b);c.un("columnmoved",b.onColumnMove,b)}if(e){delete b.lastViewWidth;e.on({scope:b,configchange:b.onColConfigChange,widthchange:b.onColWidthChange,headerchange:b.onHeaderChange,hiddenchange:b.onHiddenChange,columnmoved:b.onColumnMove})}b.ds=a;b.cm=e},onDataChange:function(){this.refresh(true);this.updateHeaderSortState();this.syncFocusEl(0)},onClear:function(){this.refresh();this.syncFocusEl(0)},onUpdate:function(b,a){this.refreshRow(a)},onAdd:function(b,a,c){this.insertRows(b,c,c+(a.length-1))},onRemove:function(b,a,c,d){if(d!==true){this.fireEvent("beforerowremoved",this,c,a)}this.removeRow(c);if(d!==true){this.processRows(c);this.applyEmptyText();this.fireEvent("rowremoved",this,c,a)}},onLoad:function(){if(Ext.isGecko){if(!this.scrollToTopTask){this.scrollToTopTask=new Ext.util.DelayedTask(this.scrollToTop,this)}this.scrollToTopTask.delay(1)}else{this.scrollToTop()}},onColWidthChange:function(a,b,c){this.updateColumnWidth(b,c)},onHeaderChange:function(a,b,c){this.updateHeaders()},onHiddenChange:function(a,b,c){this.updateColumnHidden(b,c)},onColumnMove:function(a,c,b){this.indexMap=null;this.refresh(true);this.restoreScroll(this.getScrollState());this.afterMove(b);this.grid.fireEvent("columnmove",c,b)},onColConfigChange:function(){delete this.lastViewWidth;this.indexMap=null;this.refresh(true)},initUI:function(a){a.on("headerclick",this.onHeaderClick,this)},initEvents:Ext.emptyFn,onHeaderClick:function(b,a){if(this.headersDisabled||!this.cm.isSortable(a)){return}b.stopEditing(true);b.store.sort(this.cm.getDataIndex(a))},onRowOver:function(b,a){var c=this.findRowIndex(a);if(c!==false){this.addRowClass(c,this.rowOverCls)}},onRowOut:function(b,a){var c=this.findRowIndex(a);if(c!==false&&!b.within(this.getRow(c),true)){this.removeRowClass(c,this.rowOverCls)}},onRowSelect:function(a){this.addRowClass(a,this.selectedRowClass)},onRowDeselect:function(a){this.removeRowClass(a,this.selectedRowClass)},onCellSelect:function(c,b){var a=this.getCell(c,b);if(a){this.fly(a).addClass("x-grid3-cell-selected")}},onCellDeselect:function(c,b){var a=this.getCell(c,b);if(a){this.fly(a).removeClass("x-grid3-cell-selected")}},handleWheel:function(a){a.stopPropagation()},onColumnSplitterMoved:function(a,b){this.userResized=true;this.grid.colModel.setColumnWidth(a,b,true);if(this.forceFit){this.fitColumns(true,false,a);this.updateAllColumnWidths()}else{this.updateColumnWidth(a,b);this.syncHeaderScroll()}this.grid.fireEvent("columnresize",a,b)},beforeColMenuShow:function(){var b=this.cm,d=b.getColumnCount(),a=this.colMenu,c;a.removeAll();for(c=0;c<d;c++){if(b.config[c].hideable!==false){a.add(new Ext.menu.CheckItem({text:b.getColumnHeader(c),itemId:"col-"+b.getColumnId(c),checked:!b.isHidden(c),disabled:b.config[c].hideable===false,hideOnClick:false}))}}},handleHdMenuClick:function(c){var a=this.ds,b=this.cm.getDataIndex(this.hdCtxIndex);switch(c.getItemId()){case"asc":a.sort(b,"ASC");break;case"desc":a.sort(b,"DESC");break;default:this.handleHdMenuClickDefault(c)}return true},handleHdMenuClickDefault:function(c){var b=this.cm,d=c.getItemId(),a=b.getIndexById(d.substr(4));if(a!=-1){if(c.checked&&b.getColumnsBy(this.isHideableColumn,this).length<=1){this.onDenyColumnHide();return}b.setHidden(a,c.checked)}},handleHdDown:function(i,k){if(Ext.fly(k).hasClass("x-grid3-hd-btn")){i.stopEvent();var l=this.cm,g=this.findHeaderCell(k),h=this.getCellIndex(g),d=l.isSortable(h),c=this.hmenu,b=c.items,a=this.headerMenuOpenCls;this.hdCtxIndex=h;Ext.fly(g).addClass(a);b.get("asc").setDisabled(!d);b.get("desc").setDisabled(!d);c.on("hide",function(){Ext.fly(g).removeClass(a)},this,{single:true});c.show(k,"tl-bl?")}},handleHdMove:function(l){var i=this.findHeaderCell(this.activeHdRef);if(i&&!this.headersDisabled){var m=this.splitHandleWidth||5,k=this.activeHdRegion,q=i.style,n=this.cm,p="",g=l.getPageX();if(this.grid.enableColumnResize!==false){var a=this.activeHdIndex,b=this.getPreviousVisible(a),o=n.isResizable(a),c=b&&n.isResizable(b),d=g-k.left<=m,h=k.right-g<=(!this.activeHdBtn?m:2);if(d&&c){p=Ext.isAir?"move":Ext.isWebKit?"e-resize":"col-resize"}else{if(h&&o){p=Ext.isAir?"move":Ext.isWebKit?"w-resize":"col-resize"}}}q.cursor=p}},getPreviousVisible:function(a){while(a>0){if(!this.cm.isHidden(a-1)){return a}a--}return undefined},handleHdOver:function(c,b){var d=this.findHeaderCell(b);if(d&&!this.headersDisabled){var a=this.fly(d);this.activeHdRef=b;this.activeHdIndex=this.getCellIndex(d);this.activeHdRegion=a.getRegion();if(!this.isMenuDisabled(this.activeHdIndex,a)){a.addClass("x-grid3-hd-over");this.activeHdBtn=a.child(".x-grid3-hd-btn");if(this.activeHdBtn){this.activeHdBtn.dom.style.height=(d.firstChild.offsetHeight-1)+"px"}}}},handleHdOut:function(b,a){var c=this.findHeaderCell(a);if(c&&(!Ext.isIE||!b.within(c,true))){this.activeHdRef=null;this.fly(c).removeClass("x-grid3-hd-over");c.style.cursor=""}},isMenuDisabled:function(a,b){return this.cm.isMenuDisabled(a)},hasRows:function(){var a=this.mainBody.dom.firstChild;return a&&a.nodeType==1&&a.className!="x-grid-empty"},isHideableColumn:function(a){return !a.hidden},bind:function(a,b){this.initData(a,b)}});Ext.grid.GridView.SplitDragZone=Ext.extend(Ext.dd.DDProxy,{constructor:function(a,b){this.grid=a;this.view=a.getView();this.marker=this.view.resizeMarker;this.proxy=this.view.resizeProxy;Ext.grid.GridView.SplitDragZone.superclass.constructor.call(this,b,"gridSplitters"+this.grid.getGridEl().id,{dragElId:Ext.id(this.proxy.dom),resizeFrame:false});this.scroll=false;this.hw=this.view.splitHandleWidth||5},b4StartDrag:function(a,e){this.dragHeadersDisabled=this.view.headersDisabled;this.view.headersDisabled=true;var d=this.view.mainWrap.getHeight();this.marker.setHeight(d);this.marker.show();this.marker.alignTo(this.view.getHeaderCell(this.cellIndex),"tl-tl",[-2,0]);this.proxy.setHeight(d);var b=this.cm.getColumnWidth(this.cellIndex),c=Math.max(b-this.grid.minColumnWidth,0);this.resetConstraints();this.setXConstraint(c,1000);this.setYConstraint(0,0);this.minX=a-c;this.maxX=a+1000;this.startPos=a;Ext.dd.DDProxy.prototype.b4StartDrag.call(this,a,e)},allowHeaderDrag:function(a){return true},handleMouseDown:function(a){var h=this.view.findHeaderCell(a.getTarget());if(h&&this.allowHeaderDrag(a)){var l=this.view.fly(h).getXY(),c=l[0],i=a.getXY(),b=i[0],g=h.offsetWidth,d=false;if((b-c)<=this.hw){d=-1}else{if((c+g)-b<=this.hw){d=0}}if(d!==false){this.cm=this.grid.colModel;var k=this.view.getCellIndex(h);if(d==-1){if(k+d<0){return}while(this.cm.isHidden(k+d)){--d;if(k+d<0){return}}}this.cellIndex=k+d;this.split=h.dom;if(this.cm.isResizable(this.cellIndex)&&!this.cm.isFixed(this.cellIndex)){Ext.grid.GridView.SplitDragZone.superclass.handleMouseDown.apply(this,arguments)}}else{if(this.view.columnDrag){this.view.columnDrag.callHandleMouseDown(a)}}}},endDrag:function(g){this.marker.hide();var a=this.view,c=Math.max(this.minX,g.getPageX()),d=c-this.startPos,b=this.dragHeadersDisabled;a.onColumnSplitterMoved(this.cellIndex,this.cm.getColumnWidth(this.cellIndex)+d);setTimeout(function(){a.headersDisabled=b},50)},autoOffset:function(){this.setDelta(0,0)}});Ext.grid.PivotGridView=Ext.extend(Ext.grid.GridView,{colHeaderCellCls:"grid-hd-group-cell",title:"",getColumnHeaders:function(){return this.grid.topAxis.buildHeaders()},getRowHeaders:function(){return this.grid.leftAxis.buildHeaders()},renderRows:function(a,r){var b=this.grid,n=b.extractData(),o=n.length,e=this.templates,q=b.renderer,h=typeof q=="function",t=this.getCellCls,m=typeof t=="function",d=e.cell,u=e.row,k=[],p={},c="width:"+this.getGridInnerWidth()+"px;",l,g,s;a=a||0;r=Ext.isDefined(r)?r:o-1;for(s=0;s<o;s++){row=n[s];colCount=row.length;l=[];rowIndex=a+s;for(j=0;j<colCount;j++){cell=row[j];p.css=j===0?"x-grid3-cell-first ":(j==(colCount-1)?"x-grid3-cell-last ":"");p.attr=p.cellAttr="";p.value=cell;if(Ext.isEmpty(p.value)){p.value=" "}if(h){p.value=q(p.value)}if(m){p.css+=t(p.value)+" "}l[l.length]=d.apply(p)}k[k.length]=u.apply({tstyle:c,cols:colCount,cells:l.join(""),alt:""})}return k.join("")},masterTpl:new Ext.Template('<div class="x-grid3 x-pivotgrid" hidefocus="true">','<div class="x-grid3-viewport">','<div class="x-grid3-header">','<div class="x-grid3-header-title"><span>{title}</span></div>','<div class="x-grid3-header-inner">','<div class="x-grid3-header-offset" style="{ostyle}"></div>',"</div>",'<div class="x-clear"></div>',"</div>",'<div class="x-grid3-scroller">','<div class="x-grid3-row-headers"></div>','<div class="x-grid3-body" style="{bstyle}">{body}</div>','<a href="#" class="x-grid3-focus" tabIndex="-1"></a>',"</div>","</div>",'<div class="x-grid3-resize-marker"> </div>','<div class="x-grid3-resize-proxy"> </div>',"</div>"),initTemplates:function(){Ext.grid.PivotGridView.superclass.initTemplates.apply(this,arguments);var a=this.templates||{};if(!a.gcell){a.gcell=new Ext.XTemplate('<td class="x-grid3-hd x-grid3-gcell x-grid3-td-{id} ux-grid-hd-group-row-{row} '+this.colHeaderCellCls+'" style="{style}">','<div {tooltip} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">',this.grid.enableHdMenu?'<a class="x-grid3-hd-btn" href="#"></a>':"","{value}","</div>","</td>")}this.templates=a;this.hrowRe=new RegExp("ux-grid-hd-group-row-(\\d+)","")},initElements:function(){Ext.grid.PivotGridView.superclass.initElements.apply(this,arguments);this.rowHeadersEl=new Ext.Element(this.scroller.child("div.x-grid3-row-headers"));this.headerTitleEl=new Ext.Element(this.mainHd.child("div.x-grid3-header-title"))},getGridInnerWidth:function(){var a=Ext.grid.PivotGridView.superclass.getGridInnerWidth.apply(this,arguments);return a-this.getTotalRowHeaderWidth()},getTotalRowHeaderWidth:function(){var d=this.getRowHeaders(),c=d.length,b=0,a;for(a=0;a<c;a++){b+=d[a].width}return b},getTotalColumnHeaderHeight:function(){return this.getColumnHeaders().length*21},renderUI:function(){var b=this.templates,a=this.getGridInnerWidth();return b.master.apply({body:b.body.apply({rows:" "}),ostyle:"width:"+a+"px",bstyle:"width:"+a+"px"})},onLayout:function(b,a){Ext.grid.PivotGridView.superclass.onLayout.apply(this,arguments);var b=this.getGridInnerWidth();this.resizeColumnHeaders(b);this.resizeAllRows(b)},refresh:function(b){this.fireEvent("beforerefresh",this);this.grid.stopEditing(true);var a=this.renderBody();this.mainBody.update(a).setWidth(this.getGridInnerWidth());if(b===true){this.updateHeaders();this.updateHeaderSortState()}this.processRows(0,true);this.layout();this.applyEmptyText();this.fireEvent("refresh",this)},renderHeaders:Ext.emptyFn,fitColumns:Ext.emptyFn,resizeColumnHeaders:function(b){var a=this.grid.topAxis;if(a.rendered){a.el.setWidth(b)}},resizeRowHeaders:function(){var a=this.getTotalRowHeaderWidth(),b=String.format("margin-left: {0}px;",a);this.rowHeadersEl.setWidth(a);this.mainBody.applyStyles(b);Ext.fly(this.innerHd).applyStyles(b);this.headerTitleEl.setWidth(a);this.headerTitleEl.setHeight(this.getTotalColumnHeaderHeight())},resizeAllRows:function(b){var d=this.getRows(),c=d.length,a;for(a=0;a<c;a++){Ext.fly(d[a]).setWidth(b);Ext.fly(d[a]).child("table").setWidth(b)}},updateHeaders:function(){this.renderGroupRowHeaders();this.renderGroupColumnHeaders()},renderGroupRowHeaders:function(){var a=this.grid.leftAxis;this.resizeRowHeaders();a.rendered=false;a.render(this.rowHeadersEl);this.setTitle(this.title)},setTitle:function(a){this.headerTitleEl.child("span").dom.innerHTML=a},renderGroupColumnHeaders:function(){var a=this.grid.topAxis;a.rendered=false;a.render(this.innerHd.firstChild)},isMenuDisabled:function(a,b){return true}});Ext.grid.PivotAxis=Ext.extend(Ext.Component,{orientation:"horizontal",defaultHeaderWidth:80,paddingWidth:7,setDimensions:function(a){this.dimensions=a},onRender:function(b,a){var c=this.orientation=="horizontal"?this.renderHorizontalRows():this.renderVerticalRows();this.el=Ext.DomHelper.overwrite(b.dom,{tag:"table",cn:c},true)},renderHorizontalRows:function(){var k=this.buildHeaders(),a=k.length,g=[],c,h,e,d,b;for(d=0;d<a;d++){c=[];h=k[d].items;e=h.length;for(b=0;b<e;b++){c.push({tag:"td",html:h[b].header,colspan:h[b].span})}g[d]={tag:"tr",cn:c}}return g},renderVerticalRows:function(){var b=this.buildHeaders(),k=b.length,a=[],m=[],h,c,l,g,e,d;for(e=0;e<k;e++){c=b[e];g=c.width||80;h=c.items.length;for(d=0;d<h;d++){l=c.items[d];a[l.start]=a[l.start]||[];a[l.start].push({tag:"td",html:l.header,rowspan:l.span,width:Ext.isBorderBox?g:g-this.paddingWidth})}}h=a.length;for(e=0;e<h;e++){m[e]={tag:"tr",cn:a[e]}}return m},getTuples:function(){var b=new Ext.data.Store({});b.data=this.store.data.clone();b.fields=this.store.fields;var m=[],a=this.dimensions,c=a.length,k;for(k=0;k<c;k++){m.push({field:a[k].dataIndex,direction:a[k].direction||"ASC"})}b.sort(m);var e=b.data.items,o=[],l=[],p,h,d,g,n;c=e.length;for(k=0;k<c;k++){d=this.getRecordInfo(e[k]);g=d.data;h="";for(n in g){h+=g[n]+"---"}if(o.indexOf(h)==-1){o.push(h);l.push(d)}}b.destroy();return l},getRecordInfo:function(a){var e=this.dimensions,d=e.length,h={},k,c,b;for(b=0;b<d;b++){k=e[b];c=k.dataIndex;h[c]=a.get(c)}var g=function(i){return function(l){for(var m in i){if(l.get(m)!=i[m]){return false}}return true}};return{data:h,matcher:g(h)}},buildHeaders:function(){var k=this.getTuples(),l=k.length,a=this.dimensions,q=a.length,c=[],n,r,m,p,o,b,h,g,e,d;for(e=0;e<q;e++){dimension=a[e];r=[];o=0;b=0;for(d=0;d<l;d++){n=k[d];h=d==(l-1);m=n.data[dimension.dataIndex];g=p!=undefined&&p!=m;if(e>0&&d>0){g=g||n.data[a[e-1].dataIndex]!=k[d-1].data[a[e-1].dataIndex]}if(g){r.push({header:p,span:o,start:b});b+=o;o=0}if(h){r.push({header:m,span:o+1,start:b});b+=o;o=0}p=m;o++}c.push({items:r,width:dimension.width||this.defaultHeaderWidth});p=undefined}return c}});Ext.grid.HeaderDragZone=Ext.extend(Ext.dd.DragZone,{maxDragWidth:120,constructor:function(a,c,b){this.grid=a;this.view=a.getView();this.ddGroup="gridHeader"+this.grid.getGridEl().id;Ext.grid.HeaderDragZone.superclass.constructor.call(this,c);if(b){this.setHandleElId(Ext.id(c));this.setOuterHandleElId(Ext.id(b))}this.scroll=false},getDragData:function(c){var a=Ext.lib.Event.getTarget(c),b=this.view.findHeaderCell(a);if(b){return{ddel:b.firstChild,header:b}}return false},onInitDrag:function(a){this.dragHeadersDisabled=this.view.headersDisabled;this.view.headersDisabled=true;var b=this.dragData.ddel.cloneNode(true);b.id=Ext.id();b.style.width=Math.min(this.dragData.header.offsetWidth,this.maxDragWidth)+"px";this.proxy.update(b);return true},afterValidDrop:function(){this.completeDrop()},afterInvalidDrop:function(){this.completeDrop()},completeDrop:function(){var a=this.view,b=this.dragHeadersDisabled;setTimeout(function(){a.headersDisabled=b},50)}});Ext.grid.HeaderDropZone=Ext.extend(Ext.dd.DropZone,{proxyOffsets:[-4,-9],fly:Ext.Element.fly,constructor:function(a,c,b){this.grid=a;this.view=a.getView();this.proxyTop=Ext.DomHelper.append(document.body,{cls:"col-move-top",html:" "},true);this.proxyBottom=Ext.DomHelper.append(document.body,{cls:"col-move-bottom",html:" "},true);this.proxyTop.hide=this.proxyBottom.hide=function(){this.setLeftTop(-100,-100);this.setStyle("visibility","hidden")};this.ddGroup="gridHeader"+this.grid.getGridEl().id;Ext.grid.HeaderDropZone.superclass.constructor.call(this,a.getGridEl().dom)},getTargetFromEvent:function(c){var a=Ext.lib.Event.getTarget(c),b=this.view.findCellIndex(a);if(b!==false){return this.view.getHeaderCell(b)}},nextVisible:function(c){var b=this.view,a=this.grid.colModel;c=c.nextSibling;while(c){if(!a.isHidden(b.getCellIndex(c))){return c}c=c.nextSibling}return null},prevVisible:function(c){var b=this.view,a=this.grid.colModel;c=c.prevSibling;while(c){if(!a.isHidden(b.getCellIndex(c))){return c}c=c.prevSibling}return null},positionIndicator:function(d,l,k){var a=Ext.lib.Event.getPageX(k),g=Ext.lib.Dom.getRegion(l.firstChild),c,i,b=g.top+this.proxyOffsets[1];if((g.right-a)<=(g.right-g.left)/2){c=g.right+this.view.borderWidth;i="after"}else{c=g.left;i="before"}if(this.grid.colModel.isFixed(this.view.getCellIndex(l))){return false}c+=this.proxyOffsets[0];this.proxyTop.setLeftTop(c,b);this.proxyTop.show();if(!this.bottomOffset){this.bottomOffset=this.view.mainHd.getHeight()}this.proxyBottom.setLeftTop(c,b+this.proxyTop.dom.offsetHeight+this.bottomOffset);this.proxyBottom.show();return i},onNodeEnter:function(d,a,c,b){if(b.header!=d){this.positionIndicator(b.header,d,c)}},onNodeOver:function(g,b,d,c){var a=false;if(c.header!=g){a=this.positionIndicator(c.header,g,d)}if(!a){this.proxyTop.hide();this.proxyBottom.hide()}return a?this.dropAllowed:this.dropNotAllowed},onNodeOut:function(d,a,c,b){this.proxyTop.hide();this.proxyBottom.hide()},onNodeDrop:function(b,o,g,c){var d=c.header;if(d!=b){var l=this.grid.colModel,k=Ext.lib.Event.getPageX(g),a=Ext.lib.Dom.getRegion(b.firstChild),p=(a.right-k)<=((a.right-a.left)/2)?"after":"before",i=this.view.getCellIndex(d),m=this.view.getCellIndex(b);if(p=="after"){m++}if(i<m){m--}l.moveColumn(i,m);return true}return false}});Ext.grid.GridView.ColumnDragZone=Ext.extend(Ext.grid.HeaderDragZone,{constructor:function(a,b){Ext.grid.GridView.ColumnDragZone.superclass.constructor.call(this,a,b,null);this.proxy.el.addClass("x-grid3-col-dd")},handleMouseDown:function(a){},callHandleMouseDown:function(a){Ext.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this,a)}});Ext.grid.SplitDragZone=Ext.extend(Ext.dd.DDProxy,{fly:Ext.Element.fly,constructor:function(a,c,b){this.grid=a;this.view=a.getView();this.proxy=this.view.resizeProxy;Ext.grid.SplitDragZone.superclass.constructor.call(this,c,"gridSplitters"+this.grid.getGridEl().id,{dragElId:Ext.id(this.proxy.dom),resizeFrame:false});this.setHandleElId(Ext.id(c));this.setOuterHandleElId(Ext.id(b));this.scroll=false},b4StartDrag:function(a,d){this.view.headersDisabled=true;this.proxy.setHeight(this.view.mainWrap.getHeight());var b=this.cm.getColumnWidth(this.cellIndex);var c=Math.max(b-this.grid.minColumnWidth,0);this.resetConstraints();this.setXConstraint(c,1000);this.setYConstraint(0,0);this.minX=a-c;this.maxX=a+1000;this.startPos=a;Ext.dd.DDProxy.prototype.b4StartDrag.call(this,a,d)},handleMouseDown:function(c){var b=Ext.EventObject.setEvent(c);var a=this.fly(b.getTarget());if(a.hasClass("x-grid-split")){this.cellIndex=this.view.getCellIndex(a.dom);this.split=a.dom;this.cm=this.grid.colModel;if(this.cm.isResizable(this.cellIndex)&&!this.cm.isFixed(this.cellIndex)){Ext.grid.SplitDragZone.superclass.handleMouseDown.apply(this,arguments)}}},endDrag:function(c){this.view.headersDisabled=false;var a=Math.max(this.minX,Ext.lib.Event.getPageX(c));var b=a-this.startPos;this.view.onColumnSplitterMoved(this.cellIndex,this.cm.getColumnWidth(this.cellIndex)+b)},autoOffset:function(){this.setDelta(0,0)}});Ext.grid.GridDragZone=function(b,a){this.view=b.getView();Ext.grid.GridDragZone.superclass.constructor.call(this,this.view.mainBody.dom,a);this.scroll=false;this.grid=b;this.ddel=document.createElement("div");this.ddel.className="x-grid-dd-wrap"};Ext.extend(Ext.grid.GridDragZone,Ext.dd.DragZone,{ddGroup:"GridDD",getDragData:function(b){var a=Ext.lib.Event.getTarget(b);var d=this.view.findRowIndex(a);if(d!==false){var c=this.grid.selModel;if(!c.isSelected(d)||b.hasModifier()){c.handleMouseDown(this.grid,d,b)}return{grid:this.grid,ddel:this.ddel,rowIndex:d,selections:c.getSelections()}}return false},onInitDrag:function(b){var a=this.dragData;this.ddel.innerHTML=this.grid.getDragDropText();this.proxy.update(this.ddel)},afterRepair:function(){this.dragging=false},getRepairXY:function(b,a){return false},onEndDrag:function(a,b){},onValidDrop:function(a,b,c){this.hideProxy()},beforeInvalidDrop:function(a,b){}});Ext.grid.ColumnModel=Ext.extend(Ext.util.Observable,{defaultWidth:100,defaultSortable:false,constructor:function(a){if(a.columns){Ext.apply(this,a);this.setConfig(a.columns,true)}else{this.setConfig(a,true)}this.addEvents("widthchange","headerchange","hiddenchange","columnmoved","configchange");Ext.grid.ColumnModel.superclass.constructor.call(this)},getColumnId:function(a){return this.config[a].id},getColumnAt:function(a){return this.config[a]},setConfig:function(d,b){var e,h,a;if(!b){delete this.totalWidth;for(e=0,a=this.config.length;e<a;e++){h=this.config[e];if(h.setEditor){h.setEditor(null)}}}this.defaults=Ext.apply({width:this.defaultWidth,sortable:this.defaultSortable},this.defaults);this.config=d;this.lookup={};for(e=0,a=d.length;e<a;e++){h=Ext.applyIf(d[e],this.defaults);if(Ext.isEmpty(h.id)){h.id=e}if(!h.isColumn){var g=Ext.grid.Column.types[h.xtype||"gridcolumn"];h=new g(h);d[e]=h}this.lookup[h.id]=h}if(!b){this.fireEvent("configchange",this)}},getColumnById:function(a){return this.lookup[a]},getIndexById:function(c){for(var b=0,a=this.config.length;b<a;b++){if(this.config[b].id==c){return b}}return -1},moveColumn:function(e,b){var a=this.config,d=a[e];a.splice(e,1);a.splice(b,0,d);this.dataMap=null;this.fireEvent("columnmoved",this,e,b)},getColumnCount:function(b){var d=this.config.length,e=0,a;if(b===true){for(a=0;a<d;a++){if(!this.isHidden(a)){e++}}return e}return d},getColumnsBy:function(g,e){var b=this.config,h=b.length,a=[],d,k;for(d=0;d<h;d++){k=b[d];if(g.call(e||this,k,d)===true){a[a.length]=k}}return a},isSortable:function(a){return !!this.config[a].sortable},isMenuDisabled:function(a){return !!this.config[a].menuDisabled},getRenderer:function(a){return this.config[a].renderer||Ext.grid.ColumnModel.defaultRenderer},getRendererScope:function(a){return this.config[a].scope},setRenderer:function(a,b){this.config[a].renderer=b},getColumnWidth:function(a){var b=this.config[a].width;if(typeof b!="number"){b=this.defaultWidth}return b},setColumnWidth:function(b,c,a){this.config[b].width=c;this.totalWidth=null;if(!a){this.fireEvent("widthchange",this,b,c)}},getTotalWidth:function(b){if(!this.totalWidth){this.totalWidth=0;for(var c=0,a=this.config.length;c<a;c++){if(b||!this.isHidden(c)){this.totalWidth+=this.getColumnWidth(c)}}}return this.totalWidth},getColumnHeader:function(a){return this.config[a].header},setColumnHeader:function(a,b){this.config[a].header=b;this.fireEvent("headerchange",this,a,b)},getColumnTooltip:function(a){return this.config[a].tooltip},setColumnTooltip:function(a,b){this.config[a].tooltip=b},getDataIndex:function(a){return this.config[a].dataIndex},setDataIndex:function(a,b){this.config[a].dataIndex=b},findColumnIndex:function(d){var e=this.config;for(var b=0,a=e.length;b<a;b++){if(e[b].dataIndex==d){return b}}return -1},isCellEditable:function(b,e){var d=this.config[b],a=d.editable;return !!(a||(!Ext.isDefined(a)&&d.editor))},getCellEditor:function(a,b){return this.config[a].getCellEditor(b)},setEditable:function(a,b){this.config[a].editable=b},isHidden:function(a){return !!this.config[a].hidden},isFixed:function(a){return !!this.config[a].fixed},isResizable:function(a){return a>=0&&this.config[a].resizable!==false&&this.config[a].fixed!==true},setHidden:function(a,b){var d=this.config[a];if(d.hidden!==b){d.hidden=b;this.totalWidth=null;this.fireEvent("hiddenchange",this,a,b)}},setEditor:function(a,b){this.config[a].setEditor(b)},destroy:function(){var b=this.config.length,a=0;for(;a<b;a++){this.config[a].destroy()}delete this.config;delete this.lookup;this.purgeListeners()},setState:function(a,b){b=Ext.applyIf(b,this.defaults);Ext.apply(this.config[a],b)}});Ext.grid.ColumnModel.defaultRenderer=function(a){if(typeof a=="string"&&a.length<1){return" "}return a};Ext.grid.AbstractSelectionModel=Ext.extend(Ext.util.Observable,{constructor:function(){this.locked=false;Ext.grid.AbstractSelectionModel.superclass.constructor.call(this)},init:function(a){this.grid=a;if(this.lockOnInit){delete this.lockOnInit;this.locked=false;this.lock()}this.initEvents()},lock:function(){if(!this.locked){this.locked=true;var a=this.grid;if(a){a.getView().on({scope:this,beforerefresh:this.sortUnLock,refresh:this.sortLock})}else{this.lockOnInit=true}}},sortLock:function(){this.locked=true},sortUnLock:function(){this.locked=false},unlock:function(){if(this.locked){this.locked=false;var a=this.grid,b;if(a){b=a.getView();b.un("beforerefresh",this.sortUnLock,this);b.un("refresh",this.sortLock,this)}else{delete this.lockOnInit}}},isLocked:function(){return this.locked},destroy:function(){this.unlock();this.purgeListeners()}});Ext.grid.RowSelectionModel=Ext.extend(Ext.grid.AbstractSelectionModel,{singleSelect:false,constructor:function(a){Ext.apply(this,a);this.selections=new Ext.util.MixedCollection(false,function(b){return b.id});this.last=false;this.lastActive=false;this.addEvents("selectionchange","beforerowselect","rowselect","rowdeselect");Ext.grid.RowSelectionModel.superclass.constructor.call(this)},initEvents:function(){if(!this.grid.enableDragDrop&&!this.grid.enableDrag){this.grid.on("rowmousedown",this.handleMouseDown,this)}this.rowNav=new Ext.KeyNav(this.grid.getGridEl(),{up:this.onKeyPress,down:this.onKeyPress,scope:this});this.grid.getView().on({scope:this,refresh:this.onRefresh,rowupdated:this.onRowUpdated,rowremoved:this.onRemove})},onKeyPress:function(g,b){var a=b=="up",h=a?"selectPrevious":"selectNext",d=a?-1:1,c;if(!g.shiftKey||this.singleSelect){this[h](false)}else{if(this.last!==false&&this.lastActive!==false){c=this.last;this.selectRange(this.last,this.lastActive+d);this.grid.getView().focusRow(this.lastActive);if(c!==false){this.last=c}}else{this.selectFirstRow()}}},onRefresh:function(){var g=this.grid.store,d=this.getSelections(),c=0,a=d.length,b,e;this.silent=true;this.clearSelections(true);for(;c<a;c++){e=d[c];if((b=g.indexOfId(e.id))!=-1){this.selectRow(b,true)}}if(d.length!=this.selections.getCount()){this.fireEvent("selectionchange",this)}this.silent=false},onRemove:function(a,b,c){if(this.selections.remove(c)!==false){this.fireEvent("selectionchange",this)}},onRowUpdated:function(a,b,c){if(this.isSelected(c)){a.onRowSelect(b)}},selectRecords:function(b,e){if(!e){this.clearSelections()}var d=this.grid.store,c=0,a=b.length;for(;c<a;c++){this.selectRow(d.indexOf(b[c]),true)}},getCount:function(){return this.selections.length},selectFirstRow:function(){this.selectRow(0)},selectLastRow:function(a){this.selectRow(this.grid.store.getCount()-1,a)},selectNext:function(a){if(this.hasNext()){this.selectRow(this.last+1,a);this.grid.getView().focusRow(this.last);return true}return false},selectPrevious:function(a){if(this.hasPrevious()){this.selectRow(this.last-1,a);this.grid.getView().focusRow(this.last);return true}return false},hasNext:function(){return this.last!==false&&(this.last+1)<this.grid.store.getCount()},hasPrevious:function(){return !!this.last},getSelections:function(){return[].concat(this.selections.items)},getSelected:function(){return this.selections.itemAt(0)},each:function(e,d){var c=this.getSelections(),b=0,a=c.length;for(;b<a;b++){if(e.call(d||this,c[b],b)===false){return false}}return true},clearSelections:function(a){if(this.isLocked()){return}if(a!==true){var c=this.grid.store,b=this.selections;b.each(function(d){this.deselectRow(c.indexOfId(d.id))},this);b.clear()}else{this.selections.clear()}this.last=false},selectAll:function(){if(this.isLocked()){return}this.selections.clear();for(var b=0,a=this.grid.store.getCount();b<a;b++){this.selectRow(b,true)}},hasSelection:function(){return this.selections.length>0},isSelected:function(a){var b=Ext.isNumber(a)?this.grid.store.getAt(a):a;return(b&&this.selections.key(b.id)?true:false)},isIdSelected:function(a){return(this.selections.key(a)?true:false)},handleMouseDown:function(d,i,h){if(h.button!==0||this.isLocked()){return}var a=this.grid.getView();if(h.shiftKey&&!this.singleSelect&&this.last!==false){var c=this.last;this.selectRange(c,i,h.ctrlKey);this.last=c;a.focusRow(i)}else{var b=this.isSelected(i);if(h.ctrlKey&&b){this.deselectRow(i)}else{if(!b||this.getCount()>1){this.selectRow(i,h.ctrlKey||h.shiftKey);a.focusRow(i)}}}},selectRows:function(c,d){if(!d){this.clearSelections()}for(var b=0,a=c.length;b<a;b++){this.selectRow(c[b],true)}},selectRange:function(b,a,d){var c;if(this.isLocked()){return}if(!d){this.clearSelections()}if(b<=a){for(c=b;c<=a;c++){this.selectRow(c,true)}}else{for(c=b;c>=a;c--){this.selectRow(c,true)}}},deselectRange:function(c,b,a){if(this.isLocked()){return}for(var d=c;d<=b;d++){this.deselectRow(d,a)}},selectRow:function(b,d,a){if(this.isLocked()||(b<0||b>=this.grid.store.getCount())||(d&&this.isSelected(b))){return}var c=this.grid.store.getAt(b);if(c&&this.fireEvent("beforerowselect",this,b,d,c)!==false){if(!d||this.singleSelect){this.clearSelections()}this.selections.add(c);this.last=this.lastActive=b;if(!a){this.grid.getView().onRowSelect(b)}if(!this.silent){this.fireEvent("rowselect",this,b,c);this.fireEvent("selectionchange",this)}}},deselectRow:function(b,a){if(this.isLocked()){return}if(this.last==b){this.last=false}if(this.lastActive==b){this.lastActive=false}var c=this.grid.store.getAt(b);if(c){this.selections.remove(c);if(!a){this.grid.getView().onRowDeselect(b)}this.fireEvent("rowdeselect",this,b,c);this.fireEvent("selectionchange",this)}},acceptsNav:function(c,b,a){return !a.isHidden(b)&&a.isCellEditable(b,c)},onEditorKey:function(o,m){var d=m.getKey(),h,i=this.grid,q=i.lastEdit,l=i.activeEditor,b=m.shiftKey,p,q,a,n;if(d==m.TAB){m.stopEvent();l.completeEdit();if(b){h=i.walkCells(l.row,l.col-1,-1,this.acceptsNav,this)}else{h=i.walkCells(l.row,l.col+1,1,this.acceptsNav,this)}}else{if(d==m.ENTER){if(this.moveEditorOnEnter!==false){if(b){h=i.walkCells(q.row-1,q.col,-1,this.acceptsNav,this)}else{h=i.walkCells(q.row+1,q.col,1,this.acceptsNav,this)}}}}if(h){a=h[0];n=h[1];this.onEditorSelect(a,q.row);if(i.isEditor&&i.editing){p=i.activeEditor;if(p&&p.field.triggerBlur){p.field.triggerBlur()}}i.startEditing(a,n)}},onEditorSelect:function(b,a){if(a!=b){this.selectRow(b)}},destroy:function(){Ext.destroy(this.rowNav);this.rowNav=null;Ext.grid.RowSelectionModel.superclass.destroy.call(this)}});Ext.grid.Column=Ext.extend(Ext.util.Observable,{isColumn:true,constructor:function(b){Ext.apply(this,b);if(Ext.isString(this.renderer)){this.renderer=Ext.util.Format[this.renderer]}else{if(Ext.isObject(this.renderer)){this.scope=this.renderer.scope;this.renderer=this.renderer.fn}}if(!this.scope){this.scope=this}var a=this.editor;delete this.editor;this.setEditor(a);this.addEvents("click","contextmenu","dblclick","mousedown");Ext.grid.Column.superclass.constructor.call(this)},processEvent:function(b,d,c,g,a){return this.fireEvent(b,this,c,g,d)},destroy:function(){if(this.setEditor){this.setEditor(null)}this.purgeListeners()},renderer:function(a){return a},getEditor:function(a){return this.editable!==false?this.editor:null},setEditor:function(b){var a=this.editor;if(a){if(a.gridEditor){a.gridEditor.destroy();delete a.gridEditor}else{a.destroy()}}this.editor=null;if(b){if(!b.isXType){b=Ext.create(b,"textfield")}this.editor=b}},getCellEditor:function(b){var a=this.getEditor(b);if(a){if(!a.startEdit){if(!a.gridEditor){a.gridEditor=new Ext.grid.GridEditor(a)}a=a.gridEditor}}return a}});Ext.grid.BooleanColumn=Ext.extend(Ext.grid.Column,{trueText:"true",falseText:"false",undefinedText:" ",constructor:function(a){Ext.grid.BooleanColumn.superclass.constructor.call(this,a);var c=this.trueText,d=this.falseText,b=this.undefinedText;this.renderer=function(e){if(e===undefined){return b}if(!e||e==="false"){return d}return c}}});Ext.grid.NumberColumn=Ext.extend(Ext.grid.Column,{format:"0,000.00",constructor:function(a){Ext.grid.NumberColumn.superclass.constructor.call(this,a);this.renderer=Ext.util.Format.numberRenderer(this.format)}});Ext.grid.DateColumn=Ext.extend(Ext.grid.Column,{format:"m/d/Y",constructor:function(a){Ext.grid.DateColumn.superclass.constructor.call(this,a);this.renderer=Ext.util.Format.dateRenderer(this.format)}});Ext.grid.TemplateColumn=Ext.extend(Ext.grid.Column,{constructor:function(a){Ext.grid.TemplateColumn.superclass.constructor.call(this,a);var b=(!Ext.isPrimitive(this.tpl)&&this.tpl.compile)?this.tpl:new Ext.XTemplate(this.tpl);this.renderer=function(d,e,c){return b.apply(c.data)};this.tpl=b}});Ext.grid.ActionColumn=Ext.extend(Ext.grid.Column,{header:" ",actionIdRe:/x-action-col-(\d+)/,altText:"",constructor:function(b){var g=this,c=b.items||(g.items=[g]),a=c.length,d,e;Ext.grid.ActionColumn.superclass.constructor.call(g,b);g.renderer=function(h,i){h=Ext.isFunction(b.renderer)?b.renderer.apply(this,arguments)||"":"";i.css+=" x-action-col-cell";for(d=0;d<a;d++){e=c[d];h+='<img alt="'+g.altText+'" src="'+(e.icon||Ext.BLANK_IMAGE_URL)+'" class="x-action-col-icon x-action-col-'+String(d)+" "+(e.iconCls||"")+" "+(Ext.isFunction(e.getClass)?e.getClass.apply(e.scope||this.scope||this,arguments):"")+'"'+((e.tooltip)?' ext:qtip="'+e.tooltip+'"':"")+" />"}return h}},destroy:function(){delete this.items;delete this.renderer;return Ext.grid.ActionColumn.superclass.destroy.apply(this,arguments)},processEvent:function(c,i,d,k,b){var a=i.getTarget().className.match(this.actionIdRe),h,g;if(a&&(h=this.items[parseInt(a[1],10)])){if(c=="click"){(g=h.handler||this.handler)&&g.call(h.scope||this.scope||this,d,k,b,h,i)}else{if((c=="mousedown")&&(h.stopSelection!==false)){return false}}}return Ext.grid.ActionColumn.superclass.processEvent.apply(this,arguments)}});Ext.grid.Column.types={gridcolumn:Ext.grid.Column,booleancolumn:Ext.grid.BooleanColumn,numbercolumn:Ext.grid.NumberColumn,datecolumn:Ext.grid.DateColumn,templatecolumn:Ext.grid.TemplateColumn,actioncolumn:Ext.grid.ActionColumn};Ext.grid.RowNumberer=Ext.extend(Object,{header:"",width:23,sortable:false,constructor:function(a){Ext.apply(this,a);if(this.rowspan){this.renderer=this.renderer.createDelegate(this)}},fixed:true,hideable:false,menuDisabled:true,dataIndex:"",id:"numberer",rowspan:undefined,renderer:function(b,c,a,d){if(this.rowspan){c.cellAttr='rowspan="'+this.rowspan+'"'}return d+1}});Ext.grid.CheckboxSelectionModel=Ext.extend(Ext.grid.RowSelectionModel,{header:'<div class="x-grid3-hd-checker"> </div>',width:20,sortable:false,menuDisabled:true,fixed:true,hideable:false,dataIndex:"",id:"checker",isColumn:true,constructor:function(){Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this,arguments);if(this.checkOnly){this.handleMouseDown=Ext.emptyFn}},initEvents:function(){Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this);this.grid.on("render",function(){Ext.fly(this.grid.getView().innerHd).on("mousedown",this.onHdMouseDown,this)},this)},processEvent:function(b,d,c,g,a){if(b=="mousedown"){this.onMouseDown(d,d.getTarget());return false}else{return Ext.grid.Column.prototype.processEvent.apply(this,arguments)}},onMouseDown:function(c,b){if(c.button===0&&b.className=="x-grid3-row-checker"){c.stopEvent();var d=c.getTarget(".x-grid3-row");if(d){var a=d.rowIndex;if(this.isSelected(a)){this.deselectRow(a)}else{this.selectRow(a,true);this.grid.getView().focusRow(a)}}}},onHdMouseDown:function(c,a){if(a.className=="x-grid3-hd-checker"){c.stopEvent();var b=Ext.fly(a.parentNode);var d=b.hasClass("x-grid3-hd-checker-on");if(d){b.removeClass("x-grid3-hd-checker-on");this.clearSelections()}else{b.addClass("x-grid3-hd-checker-on");this.selectAll()}}},renderer:function(b,c,a){return'<div class="x-grid3-row-checker"> </div>'},onEditorSelect:function(b,a){if(a!=b&&!this.checkOnly){this.selectRow(b)}}});Ext.grid.CellSelectionModel=Ext.extend(Ext.grid.AbstractSelectionModel,{constructor:function(a){Ext.apply(this,a);this.selection=null;this.addEvents("beforecellselect","cellselect","selectionchange");Ext.grid.CellSelectionModel.superclass.constructor.call(this)},initEvents:function(){this.grid.on("cellmousedown",this.handleMouseDown,this);this.grid.on(Ext.EventManager.getKeyEvent(),this.handleKeyDown,this);this.grid.getView().on({scope:this,refresh:this.onViewChange,rowupdated:this.onRowUpdated,beforerowremoved:this.clearSelections,beforerowsinserted:this.clearSelections});if(this.grid.isEditor){this.grid.on("beforeedit",this.beforeEdit,this)}},beforeEdit:function(a){this.select(a.row,a.column,false,true,a.record)},onRowUpdated:function(a,b,c){if(this.selection&&this.selection.record==c){a.onCellSelect(b,this.selection.cell[1])}},onViewChange:function(){this.clearSelections(true)},getSelectedCell:function(){return this.selection?this.selection.cell:null},clearSelections:function(b){var a=this.selection;if(a){if(b!==true){this.grid.view.onCellDeselect(a.cell[0],a.cell[1])}this.selection=null;this.fireEvent("selectionchange",this,null)}},hasSelection:function(){return this.selection?true:false},handleMouseDown:function(b,d,a,c){if(c.button!==0||this.isLocked()){return}this.select(d,a)},select:function(g,c,b,e,d){if(this.fireEvent("beforecellselect",this,g,c)!==false){this.clearSelections();d=d||this.grid.store.getAt(g);this.selection={record:d,cell:[g,c]};if(!b){var a=this.grid.getView();a.onCellSelect(g,c);if(e!==true){a.focusCell(g,c)}}this.fireEvent("cellselect",this,g,c);this.fireEvent("selectionchange",this,this.selection)}},isSelectable:function(c,b,a){return !a.isHidden(b)},onEditorKey:function(b,a){if(a.getKey()==a.TAB){this.handleKeyDown(a)}},handleKeyDown:function(l){if(!l.isNavKeyPress()){return}var d=l.getKey(),i=this.grid,q=this.selection,b=this,n=function(g,c,e){return i.walkCells(g,c,e,i.isEditor&&i.editing?b.acceptsNav:b.isSelectable,b)},p,h,a,m,o;switch(d){case l.ESC:case l.PAGE_UP:case l.PAGE_DOWN:break;default:l.stopEvent();break}if(!q){p=n(0,0,1);if(p){this.select(p[0],p[1])}return}p=q.cell;a=p[0];m=p[1];switch(d){case l.TAB:if(l.shiftKey){h=n(a,m-1,-1)}else{h=n(a,m+1,1)}break;case l.DOWN:h=n(a+1,m,1);break;case l.UP:h=n(a-1,m,-1);break;case l.RIGHT:h=n(a,m+1,1);break;case l.LEFT:h=n(a,m-1,-1);break;case l.ENTER:if(i.isEditor&&!i.editing){i.startEditing(a,m);return}break}if(h){a=h[0];m=h[1];this.select(a,m);if(i.isEditor&&i.editing){o=i.activeEditor;if(o&&o.field.triggerBlur){o.field.triggerBlur()}i.startEditing(a,m)}}},acceptsNav:function(c,b,a){return !a.isHidden(b)&&a.isCellEditable(b,c)}});Ext.grid.EditorGridPanel=Ext.extend(Ext.grid.GridPanel,{clicksToEdit:2,forceValidation:false,isEditor:true,detectEdit:false,autoEncode:false,trackMouseOver:false,initComponent:function(){Ext.grid.EditorGridPanel.superclass.initComponent.call(this);if(!this.selModel){this.selModel=new Ext.grid.CellSelectionModel()}this.activeEditor=null;this.addEvents("beforeedit","afteredit","validateedit")},initEvents:function(){Ext.grid.EditorGridPanel.superclass.initEvents.call(this);this.getGridEl().on("mousewheel",this.stopEditing.createDelegate(this,[true]),this);this.on("columnresize",this.stopEditing,this,[true]);if(this.clicksToEdit==1){this.on("cellclick",this.onCellDblClick,this)}else{var a=this.getView();if(this.clicksToEdit=="auto"&&a.mainBody){a.mainBody.on("mousedown",this.onAutoEditClick,this)}this.on("celldblclick",this.onCellDblClick,this)}},onResize:function(){Ext.grid.EditorGridPanel.superclass.onResize.apply(this,arguments);var a=this.activeEditor;if(this.editing&&a){a.realign(true)}},onCellDblClick:function(b,c,a){this.startEditing(c,a)},onAutoEditClick:function(c,b){if(c.button!==0){return}var g=this.view.findRowIndex(b),a=this.view.findCellIndex(b);if(g!==false&&a!==false){this.stopEditing();if(this.selModel.getSelectedCell){var d=this.selModel.getSelectedCell();if(d&&d[0]===g&&d[1]===a){this.startEditing(g,a)}}else{if(this.selModel.isSelected(g)){this.startEditing(g,a)}}}},onEditComplete:function(b,d,a){this.editing=false;this.lastActiveEditor=this.activeEditor;this.activeEditor=null;var c=b.record,h=this.colModel.getDataIndex(b.col);d=this.postEditValue(d,a,c,h);if(this.forceValidation===true||String(d)!==String(a)){var g={grid:this,record:c,field:h,originalValue:a,value:d,row:b.row,column:b.col,cancel:false};if(this.fireEvent("validateedit",g)!==false&&!g.cancel&&String(d)!==String(a)){c.set(h,g.value);delete g.cancel;this.fireEvent("afteredit",g)}}this.view.focusCell(b.row,b.col)},startEditing:function(i,c){this.stopEditing();if(this.colModel.isCellEditable(c,i)){this.view.ensureVisible(i,c,true);var d=this.store.getAt(i),h=this.colModel.getDataIndex(c),g={grid:this,record:d,field:h,value:d.data[h],row:i,column:c,cancel:false};if(this.fireEvent("beforeedit",g)!==false&&!g.cancel){this.editing=true;var b=this.colModel.getCellEditor(c,i);if(!b){return}if(!b.rendered){b.parentEl=this.view.getEditorParent(b);b.on({scope:this,render:{fn:function(e){e.field.focus(false,true)},single:true,scope:this},specialkey:function(l,k){this.getSelectionModel().onEditorKey(l,k)},complete:this.onEditComplete,canceledit:this.stopEditing.createDelegate(this,[true])})}Ext.apply(b,{row:i,col:c,record:d});this.lastEdit={row:i,col:c};this.activeEditor=b;b.selectSameEditor=(this.activeEditor==this.lastActiveEditor);var a=this.preEditValue(d,h);b.startEdit(this.view.getCell(i,c).firstChild,Ext.isDefined(a)?a:"");(function(){delete b.selectSameEditor}).defer(50)}}},preEditValue:function(a,c){var b=a.data[c];return this.autoEncode&&Ext.isString(b)?Ext.util.Format.htmlDecode(b):b},postEditValue:function(c,a,b,d){return this.autoEncode&&Ext.isString(c)?Ext.util.Format.htmlEncode(c):c},stopEditing:function(b){if(this.editing){var a=this.lastActiveEditor=this.activeEditor;if(a){a[b===true?"cancelEdit":"completeEdit"]();this.view.focusCell(a.row,a.col)}this.activeEditor=null}this.editing=false}});Ext.reg("editorgrid",Ext.grid.EditorGridPanel);Ext.grid.GridEditor=function(b,a){Ext.grid.GridEditor.superclass.constructor.call(this,b,a);b.monitorTab=false};Ext.extend(Ext.grid.GridEditor,Ext.Editor,{alignment:"tl-tl",autoSize:"width",hideEl:false,cls:"x-small-editor x-grid-editor",shim:false,shadow:false});Ext.grid.PropertyRecord=Ext.data.Record.create([{name:"name",type:"string"},"value"]);Ext.grid.PropertyStore=Ext.extend(Ext.util.Observable,{constructor:function(a,b){this.grid=a;this.store=new Ext.data.Store({recordType:Ext.grid.PropertyRecord});this.store.on("update",this.onUpdate,this);if(b){this.setSource(b)}Ext.grid.PropertyStore.superclass.constructor.call(this)},setSource:function(c){this.source=c;this.store.removeAll();var b=[];for(var a in c){if(this.isEditableValue(c[a])){b.push(new Ext.grid.PropertyRecord({name:a,value:c[a]},a))}}this.store.loadRecords({records:b},{},true)},onUpdate:function(e,a,d){if(d==Ext.data.Record.EDIT){var b=a.data.value;var c=a.modified.value;if(this.grid.fireEvent("beforepropertychange",this.source,a.id,b,c)!==false){this.source[a.id]=b;a.commit();this.grid.fireEvent("propertychange",this.source,a.id,b,c)}else{a.reject()}}},getProperty:function(a){return this.store.getAt(a)},isEditableValue:function(a){return Ext.isPrimitive(a)||Ext.isDate(a)},setValue:function(d,c,a){var b=this.getRec(d);if(b){b.set("value",c);this.source[d]=c}else{if(a){this.source[d]=c;b=new Ext.grid.PropertyRecord({name:d,value:c},d);this.store.add(b)}}},remove:function(b){var a=this.getRec(b);if(a){this.store.remove(a);delete this.source[b]}},getRec:function(a){return this.store.getById(a)},getSource:function(){return this.source}});Ext.grid.PropertyColumnModel=Ext.extend(Ext.grid.ColumnModel,{nameText:"Name",valueText:"Value",dateFormat:"m/j/Y",trueText:"true",falseText:"false",constructor:function(c,b){var d=Ext.grid,e=Ext.form;this.grid=c;d.PropertyColumnModel.superclass.constructor.call(this,[{header:this.nameText,width:50,sortable:true,dataIndex:"name",id:"name",menuDisabled:true},{header:this.valueText,width:50,resizable:false,dataIndex:"value",id:"value",menuDisabled:true}]);this.store=b;var a=new e.Field({autoCreate:{tag:"select",children:[{tag:"option",value:"true",html:this.trueText},{tag:"option",value:"false",html:this.falseText}]},getValue:function(){return this.el.dom.value=="true"}});this.editors={date:new d.GridEditor(new e.DateField({selectOnFocus:true})),string:new d.GridEditor(new e.TextField({selectOnFocus:true})),number:new d.GridEditor(new e.NumberField({selectOnFocus:true,style:"text-align:left;"})),"boolean":new d.GridEditor(a,{autoSize:"both"})};this.renderCellDelegate=this.renderCell.createDelegate(this);this.renderPropDelegate=this.renderProp.createDelegate(this)},renderDate:function(a){return a.dateFormat(this.dateFormat)},renderBool:function(a){return this[a?"trueText":"falseText"]},isCellEditable:function(a,b){return a==1},getRenderer:function(a){return a==1?this.renderCellDelegate:this.renderPropDelegate},renderProp:function(a){return this.getPropertyName(a)},renderCell:function(d,b,c){var a=this.grid.customRenderers[c.get("name")];if(a){return a.apply(this,arguments)}var e=d;if(Ext.isDate(d)){e=this.renderDate(d)}else{if(typeof d=="boolean"){e=this.renderBool(d)}}return Ext.util.Format.htmlEncode(e)},getPropertyName:function(b){var a=this.grid.propertyNames;return a&&a[b]?a[b]:b},getCellEditor:function(a,e){var b=this.store.getProperty(e),d=b.data.name,c=b.data.value;if(this.grid.customEditors[d]){return this.grid.customEditors[d]}if(Ext.isDate(c)){return this.editors.date}else{if(typeof c=="number"){return this.editors.number}else{if(typeof c=="boolean"){return this.editors["boolean"]}else{return this.editors.string}}}},destroy:function(){Ext.grid.PropertyColumnModel.superclass.destroy.call(this);this.destroyEditors(this.editors);this.destroyEditors(this.grid.customEditors)},destroyEditors:function(b){for(var a in b){Ext.destroy(b[a])}}});Ext.grid.PropertyGrid=Ext.extend(Ext.grid.EditorGridPanel,{enableColumnMove:false,stripeRows:false,trackMouseOver:false,clicksToEdit:1,enableHdMenu:false,viewConfig:{forceFit:true},initComponent:function(){this.customRenderers=this.customRenderers||{};this.customEditors=this.customEditors||{};this.lastEditRow=null;var b=new Ext.grid.PropertyStore(this);this.propStore=b;var a=new Ext.grid.PropertyColumnModel(this,b);b.store.sort("name","ASC");this.addEvents("beforepropertychange","propertychange");this.cm=a;this.ds=b.store;Ext.grid.PropertyGrid.superclass.initComponent.call(this);this.mon(this.selModel,"beforecellselect",function(e,d,c){if(c===0){this.startEditing.defer(200,this,[d,1]);return false}},this)},onRender:function(){Ext.grid.PropertyGrid.superclass.onRender.apply(this,arguments);this.getGridEl().addClass("x-props-grid")},afterRender:function(){Ext.grid.PropertyGrid.superclass.afterRender.apply(this,arguments);if(this.source){this.setSource(this.source)}},setSource:function(a){this.propStore.setSource(a)},getSource:function(){return this.propStore.getSource()},setProperty:function(c,b,a){this.propStore.setValue(c,b,a)},removeProperty:function(a){this.propStore.remove(a)}});Ext.reg("propertygrid",Ext.grid.PropertyGrid);Ext.grid.GroupingView=Ext.extend(Ext.grid.GridView,{groupByText:"Group By This Field",showGroupsText:"Show in Groups",hideGroupedColumn:false,showGroupName:true,startCollapsed:false,enableGrouping:true,enableGroupingMenu:true,enableNoGroups:true,emptyGroupText:"(None)",ignoreAdd:false,groupTextTpl:"{text}",groupMode:"value",cancelEditOnToggle:true,initTemplates:function(){Ext.grid.GroupingView.superclass.initTemplates.call(this);this.state={};var a=this.grid.getSelectionModel();a.on(a.selectRow?"beforerowselect":"beforecellselect",this.onBeforeRowSelect,this);if(!this.startGroup){this.startGroup=new Ext.XTemplate('<div id="{groupId}" class="x-grid-group {cls}">','<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div class="x-grid-group-title">',this.groupTextTpl,"</div></div>",'<div id="{groupId}-bd" class="x-grid-group-body">')}this.startGroup.compile();if(!this.endGroup){this.endGroup="</div></div>"}},findGroup:function(a){return Ext.fly(a).up(".x-grid-group",this.mainBody.dom)},getGroups:function(){return this.hasRows()?this.mainBody.dom.childNodes:[]},onAdd:function(d,a,b){if(this.canGroup()&&!this.ignoreAdd){var c=this.getScrollState();this.fireEvent("beforerowsinserted",d,b,b+(a.length-1));this.refresh();this.restoreScroll(c);this.fireEvent("rowsinserted",d,b,b+(a.length-1))}else{if(!this.canGroup()){Ext.grid.GroupingView.superclass.onAdd.apply(this,arguments)}}},onRemove:function(e,a,b,d){Ext.grid.GroupingView.superclass.onRemove.apply(this,arguments);var c=document.getElementById(a._groupId);if(c&&c.childNodes[1].childNodes.length<1){Ext.removeNode(c)}this.applyEmptyText()},refreshRow:function(a){if(this.ds.getCount()==1){this.refresh()}else{this.isUpdating=true;Ext.grid.GroupingView.superclass.refreshRow.apply(this,arguments);this.isUpdating=false}},beforeMenuShow:function(){var c,a=this.hmenu.items,b=this.cm.config[this.hdCtxIndex].groupable===false;if((c=a.get("groupBy"))){c.setDisabled(b)}if((c=a.get("showGroups"))){c.setDisabled(b);c.setChecked(this.canGroup(),true)}},renderUI:function(){var a=Ext.grid.GroupingView.superclass.renderUI.call(this);if(this.enableGroupingMenu&&this.hmenu){this.hmenu.add("-",{itemId:"groupBy",text:this.groupByText,handler:this.onGroupByClick,scope:this,iconCls:"x-group-by-icon"});if(this.enableNoGroups){this.hmenu.add({itemId:"showGroups",text:this.showGroupsText,checked:true,checkHandler:this.onShowGroupsClick,scope:this})}this.hmenu.on("beforeshow",this.beforeMenuShow,this)}return a},processEvent:function(b,i){Ext.grid.GroupingView.superclass.processEvent.call(this,b,i);var h=i.getTarget(".x-grid-group-hd",this.mainBody);if(h){var g=this.getGroupField(),d=this.getPrefix(g),a=h.id.substring(d.length),c=new RegExp("gp-"+Ext.escapeRe(g)+"--hd");a=a.substr(0,a.length-3);if(a||c.test(h.id)){this.grid.fireEvent("group"+b,this.grid,g,a,i)}if(b=="mousedown"&&i.button==0){this.toggleGroup(h.parentNode)}}},onGroupByClick:function(){var a=this.grid;this.enableGrouping=true;a.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));a.fireEvent("groupchange",a,a.store.getGroupState());this.beforeMenuShow();this.refresh()},onShowGroupsClick:function(a,b){this.enableGrouping=b;if(b){this.onGroupByClick()}else{this.grid.store.clearGrouping();this.grid.fireEvent("groupchange",this,null)}},toggleRowIndex:function(c,a){if(!this.canGroup()){return}var b=this.getRow(c);if(b){this.toggleGroup(this.findGroup(b),a)}},toggleGroup:function(c,b){var a=Ext.get(c);b=Ext.isDefined(b)?b:a.hasClass("x-grid-group-collapsed");if(this.state[a.id]!==b){if(this.cancelEditOnToggle!==false){this.grid.stopEditing(true)}this.state[a.id]=b;a[b?"removeClass":"addClass"]("x-grid-group-collapsed")}},toggleAllGroups:function(c){var b=this.getGroups();for(var d=0,a=b.length;d<a;d++){this.toggleGroup(b[d],c)}},expandAllGroups:function(){this.toggleAllGroups(true)},collapseAllGroups:function(){this.toggleAllGroups(false)},getGroup:function(a,e,i,k,b,h){var c=this.cm.config[b],d=i?i.call(c.scope,a,{},e,k,b,h):String(a);if(d===""||d===" "){d=c.emptyGroupText||this.emptyGroupText}return d},getGroupField:function(){return this.grid.store.getGroupState()},afterRender:function(){if(!this.ds||!this.cm){return}Ext.grid.GroupingView.superclass.afterRender.call(this);if(this.grid.deferRowRender){this.updateGroupWidths()}},afterRenderUI:function(){Ext.grid.GroupingView.superclass.afterRenderUI.call(this);if(this.enableGroupingMenu&&this.hmenu){this.hmenu.add("-",{itemId:"groupBy",text:this.groupByText,handler:this.onGroupByClick,scope:this,iconCls:"x-group-by-icon"});if(this.enableNoGroups){this.hmenu.add({itemId:"showGroups",text:this.showGroupsText,checked:true,checkHandler:this.onShowGroupsClick,scope:this})}this.hmenu.on("beforeshow",this.beforeMenuShow,this)}},renderRows:function(){var a=this.getGroupField();var e=!!a;if(this.hideGroupedColumn){var b=this.cm.findColumnIndex(a),d=Ext.isDefined(this.lastGroupField);if(!e&&d){this.mainBody.update("");this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField),false);delete this.lastGroupField}else{if(e&&!d){this.lastGroupField=a;this.cm.setHidden(b,true)}else{if(e&&d&&a!==this.lastGroupField){this.mainBody.update("");var c=this.cm.findColumnIndex(this.lastGroupField);this.cm.setHidden(c,false);this.lastGroupField=a;this.cm.setHidden(b,true)}}}}return Ext.grid.GroupingView.superclass.renderRows.apply(this,arguments)},doRender:function(c,h,s,a,q,t){if(h.length<1){return""}if(!this.canGroup()||this.isUpdating){return Ext.grid.GroupingView.superclass.doRender.apply(this,arguments)}var A=this.getGroupField(),p=this.cm.findColumnIndex(A),x,k="width:"+this.getTotalWidth()+";",e=this.cm.config[p],b=e.groupRenderer||e.renderer,u=this.showGroupName?(e.groupName||e.header)+": ":"",z=[],m,v,w,o;for(v=0,w=h.length;v<w;v++){var l=a+v,n=h[v],d=n.data[A];x=this.getGroup(d,n,b,l,p,s);if(!m||m.group!=x){o=this.constructId(d,A,p);this.state[o]=!(Ext.isDefined(this.state[o])?!this.state[o]:this.startCollapsed);m={group:x,gvalue:d,text:u+x,groupId:o,startRow:l,rs:[n],cls:this.state[o]?"":"x-grid-group-collapsed",style:k};z.push(m)}else{m.rs.push(n)}n._groupId=o}var y=[];for(v=0,w=z.length;v<w;v++){x=z[v];this.doGroupStart(y,x,c,s,q);y[y.length]=Ext.grid.GroupingView.superclass.doRender.call(this,c,x.rs,s,x.startRow,q,t);this.doGroupEnd(y,x,c,s,q)}return y.join("")},getGroupId:function(a){var b=this.getGroupField();return this.constructId(a,b,this.cm.findColumnIndex(b))},constructId:function(c,e,a){var b=this.cm.config[a],d=b.groupRenderer||b.renderer,g=(this.groupMode=="value")?c:this.getGroup(c,{data:{}},d,0,a,this.ds);return this.getPrefix(e)+Ext.util.Format.htmlEncode(g)},canGroup:function(){return this.enableGrouping&&!!this.getGroupField()},getPrefix:function(a){return this.grid.getGridEl().id+"-gp-"+a+"-"},doGroupStart:function(a,d,b,e,c){a[a.length]=this.startGroup.apply(d)},doGroupEnd:function(a,d,b,e,c){a[a.length]=this.endGroup},getRows:function(){if(!this.canGroup()){return Ext.grid.GroupingView.superclass.getRows.call(this)}var k=[],c=this.getGroups(),h,e=0,a=c.length,d,b;for(;e<a;++e){h=c[e].childNodes[1];if(h){h=h.childNodes;for(d=0,b=h.length;d<b;++d){k[k.length]=h[d]}}}return k},updateGroupWidths:function(){if(!this.canGroup()||!this.hasRows()){return}var c=Math.max(this.cm.getTotalWidth(),this.el.dom.offsetWidth-this.getScrollOffset())+"px";var b=this.getGroups();for(var d=0,a=b.length;d<a;d++){b[d].firstChild.style.width=c}},onColumnWidthUpdated:function(c,a,b){Ext.grid.GroupingView.superclass.onColumnWidthUpdated.call(this,c,a,b);this.updateGroupWidths()},onAllColumnWidthsUpdated:function(a,b){Ext.grid.GroupingView.superclass.onAllColumnWidthsUpdated.call(this,a,b);this.updateGroupWidths()},onColumnHiddenUpdated:function(b,c,a){Ext.grid.GroupingView.superclass.onColumnHiddenUpdated.call(this,b,c,a);this.updateGroupWidths()},onLayout:function(){this.updateGroupWidths()},onBeforeRowSelect:function(b,a){this.toggleRowIndex(a,true)}});Ext.grid.GroupingView.GROUP_ID=1000; |
src/components/Entities/EntitiesContainer.js | stevenhauser/i-have-to-return-some-videotapes | import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import immutableToJs from 'utils/immutableToJs';
import level from 'state/models/level';
import Tiles from 'components/Tiles/Tiles';
import 'components/Entities/Entity.scss';
function mapStateToProps(state) {
return {
block: 'entity',
tiles: level.getEntities(state).toArray().map(immutableToJs)
};
}
function mapDispatchToProps(dispatch) {
return {};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Tiles);
|
react-redux-books/src/index.js | majalcmaj/ReactJSCourse | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware()(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
|
app/store/configureStore.production.js | jhen0409/electron-react-boilerplate | // @flow
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { hashHistory } from 'react-router';
import { routerMiddleware } from 'react-router-redux';
import rootReducer from '../reducers';
import type { counterStateType } from '../reducers/counter';
const router = routerMiddleware(hashHistory);
const enhancer = applyMiddleware(thunk, router);
export default function configureStore(initialState?: counterStateType) {
return createStore(rootReducer, initialState, enhancer); // eslint-disable-line
}
|
__tests__/share/date-range.js | mvolkmann/starter | import React from 'react';
import DateRange from '../../src/share/date-range';
import moment from 'moment';
import {shallow} from 'enzyme';
import TestUtils from 'react-addons-test-utils';
// This cannot be tested like "normal" create components because
// it renders the date picker popup outside of the parent component,
// like a modal.
describe('DateRange', () => {
it('should render', () => {
const noop = () => null;
const component = shallow(
<DateRange className="form"
endDate={moment()}
onEndDateChanged={noop}
onStartDateChanged={noop}
startDate={moment()}
/>);
expect(component.text()).toMatchSnapshot();
});
it('should handle clicks', () => {
const ms = 1489530013846; // March 14, 2017 5:20PM
const date = moment(ms);
/* eslint-disable no-empty-function */
const startDate = date;
const endDate = date;
const onStartDateChanged = () => {};
const onEndDateChanged = () => {};
const jsx =
<DateRange
startDate={startDate}
endDate={endDate}
onStartDateChanged={onStartDateChanged}
onEndDateChanged={onEndDateChanged}
/>;
const renderer = TestUtils.createRenderer();
renderer.render(jsx);
const output = renderer.getRenderOutput();
expect(output).toBeDefined();
expect(output.type).toBe('span');
const [startGroup, endGroup] = output.props.children;
const [startLabel, startPicker] = startGroup.props.children;
const [endLabel, endPicker] = endGroup.props.children;
expect(startLabel.type).toBe('label');
expect(startLabel.props.children).toBe('Start');
expect(typeof startPicker.type).toBe('function');
expect(startPicker.type.displayName).toBe('DatePicker');
expect(endLabel.type).toBe('label');
expect(endLabel.props.children).toBe('End');
expect(typeof endPicker.type).toBe('function');
expect(endPicker.type.displayName).toBe('DatePicker');
const dateRange = TestUtils.renderIntoDocument(jsx);
const inputs =
TestUtils.scryRenderedDOMComponentsWithTag(dateRange, 'input');
expect(inputs.length).toBe(2);
const [startInput, endInput] = inputs;
TestUtils.Simulate.click(startInput);
TestUtils.Simulate.click(endInput);
//TODO: This isn't finding the days on the picker.
//const days = TestUtils.scryRenderedDOMComponentsWithClass(
// dateRange, 'react-datepicker__day');
//console.log('date-range.jsx x: days =', days);
});
});
|
index.js | intrepion/blog-spa-reactjs | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
ajax/libs/forerunnerdb/1.3.791/fdb-core.js | dakshshah96/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
ShimIE8 = _dereq_('../lib/Shim.IE8');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/Core":6,"../lib/Shim.IE8":30}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
sharedPathSolver = new Path();
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (primaryKey !== undefined) { this.primaryKey(primaryKey); }
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'primaryKey');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
if (this.debug()) {
console.log('Setting index', index, sharedPathSolver.parse(index, true));
}
// Convert the index object to an array of key val objects
this.keys(sharedPathSolver.parse(index, true));
}
return this.$super.call(this, index);
});
/**
* Remove all data from the binary tree.
*/
BinaryTree.prototype.clear = function () {
delete this._data;
delete this._left;
delete this._right;
this._store = [];
};
/**
* Sets this node's data object. All further inserted documents that
* match this node's key and value will be pushed via the push()
* method into the this._store array. When deciding if a new data
* should be created left, right or middle (pushed) of this node the
* new data is checked against the data set via this method.
* @param val
* @returns {*}
*/
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.value === 1) {
result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (this.debug()) {
console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result);
}
if (result !== 0) {
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
}
}
if (this.debug()) {
console.log('Retuning result %d', result);
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.path];
}
return hash;*/
return obj[this._keys[0].path];
};
/**
* Removes (deletes reference to) either left or right child if the passed
* node matches one of them.
* @param {BinaryTree} node The node to remove.
*/
BinaryTree.prototype.removeChildNode = function (node) {
if (this._left === node) {
// Remove left
delete this._left;
} else if (this._right === node) {
// Remove right
delete this._right;
}
};
/**
* Returns the branch this node matches (left or right).
* @param node
* @returns {String}
*/
BinaryTree.prototype.nodeBranch = function (node) {
if (this._left === node) {
return 'left';
} else if (this._right === node) {
return 'right';
}
};
/**
* Inserts a document into the binary tree.
* @param data
* @returns {*}
*/
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (this.debug()) {
console.log('Inserting', data);
}
if (!this._data) {
if (this.debug()) {
console.log('Node has no data, setting data', data);
}
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
if (this.debug()) {
console.log('Data is equal (currrent, new)', this._data, data);
}
//this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
if (result === -1) {
if (this.debug()) {
console.log('Data is greater (currrent, new)', this._data, data);
}
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._right._parent = this;
}
return true;
}
if (result === 1) {
if (this.debug()) {
console.log('Data is less (currrent, new)', this._data, data);
}
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc);
this._left._parent = this;
}
return true;
}
return false;
};
BinaryTree.prototype.remove = function (data) {
var pk = this.primaryKey(),
result,
removed,
i;
if (data instanceof Array) {
// Insert array of data
removed = [];
for (i = 0; i < data.length; i++) {
if (this.remove(data[i])) {
removed.push(data[i]);
}
}
return removed;
}
if (this.debug()) {
console.log('Removing', data);
}
if (this._data[pk] === data[pk]) {
// Remove this node
return this._remove(this);
}
// Compare the data to work out which branch to send the remove command down
result = this._compareFunc(this._data, data);
if (result === -1 && this._right) {
return this._right.remove(data);
}
if (result === 1 && this._left) {
return this._left.remove(data);
}
return false;
};
BinaryTree.prototype._remove = function (node) {
var leftNode,
rightNode;
if (this._left) {
// Backup branch data
leftNode = this._left;
rightNode = this._right;
// Copy data from left node
this._left = leftNode._left;
this._right = leftNode._right;
this._data = leftNode._data;
this._store = leftNode._store;
if (rightNode) {
// Attach the rightNode data to the right-most node
// of the leftNode
leftNode.rightMost()._right = rightNode;
}
} else if (this._right) {
// Backup branch data
rightNode = this._right;
// Copy data from right node
this._left = rightNode._left;
this._right = rightNode._right;
this._data = rightNode._data;
this._store = rightNode._store;
} else {
this.clear();
}
return true;
};
BinaryTree.prototype.leftMost = function () {
if (!this._left) {
return this;
} else {
return this._left.leftMost();
}
};
BinaryTree.prototype.rightMost = function () {
if (!this._right) {
return this;
} else {
return this._right.rightMost();
}
};
/**
* Searches the binary tree for all matching documents based on the data
* passed (query).
* @param {Object} data The data / document to use for lookups.
* @param {Object} options An options object.
* @param {Operation} op An optional operation instance. Pass undefined
* if not being used.
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.lookup = function (data, options, op, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, options, op, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, options, op, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, options, op, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, options, op, resultArr); }
}
return resultArr;
};
/**
* Returns the entire binary tree ordered.
* @param {String} type
* @param resultArr
* @returns {*|Array}
*/
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/**
* Searches the binary tree for all matching documents based on the regular
* expression passed.
* @param path
* @param val
* @param regex
* @param {Array=} resultArr The results passed between recursive calls.
* Do not pass anything into this argument when calling externally.
* @returns {*|Array}
*/
BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) {
var reTest,
thisDataPathVal = sharedPathSolver.get(this._data, path),
thisDataPathValSubStr = thisDataPathVal.substr(0, val.length),
result;
//regex = regex || new RegExp('^' + val);
resultArr = resultArr || [];
if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; }
resultArr._visitedCount++;
resultArr._visitedNodes = resultArr._visitedNodes || [];
resultArr._visitedNodes.push(thisDataPathVal);
result = this.sortAsc(thisDataPathValSubStr, val);
reTest = thisDataPathValSubStr === val;
if (result === 0) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === -1) {
if (reTest) { resultArr.push(this._data); }
if (this._right) { this._right.startsWith(path, val, regex, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.startsWith(path, val, regex, resultArr); }
if (reTest) { resultArr.push(this._data); }
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
/**
* Determines if the passed query and options object will be served
* by this index successfully or not and gives a score so that the
* DB search system can determine how useful this index is in comparison
* to other indexes on the same collection.
* @param query
* @param queryOptions
* @param matchOptions
* @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}}
*/
BinaryTree.prototype.match = function (query, queryOptions, matchOptions) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = sharedPathSolver.parseArr(this._index, {
verbose: true
});
queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return sharedPathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":26,"./Shared":29}],3:[function(_dereq_,module,exports){
"use strict";
var crcTable,
checksum;
crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
/**
* Returns a checksum of a string.
* @param {String} str The string to checksum.
* @return {Number} The checksum generated.
*/
checksum = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
module.exports = checksum;
},{}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Index2d,
Overload,
ReactorIO,
Condition,
sharedPathSolver;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name, options) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this.sharedPathSolver = sharedPathSolver;
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
if (this._options.db) {
this.db(this._options.db);
}
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
async: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
this._deferredCalls = true;
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Index2d = _dereq_('./Index2d');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
Condition = _dereq_('./Condition');
sharedPathSolver = new Path();
/**
* Gets / sets the deferred calls flag. If set to true (default)
* then operations on large data sets can be broken up and done
* over multiple CPU cycles (creating an async state). For purely
* synchronous behaviour set this to false.
* @param {Boolean=} val The value to set.
* @returns {Boolean}
*/
Shared.synthesize(Collection.prototype, 'deferredCalls');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
* @param {Object=} val The data to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Gets / sets boolean to determine if the collection should be
* capped or not.
* @param {Boolean=} val The value to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'capped');
/**
* Gets / sets capped collection size. This is the maximum number
* of records that the capped collection will store.
* @param {Number=} val The value to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'cappedSize');
/**
* Adds a job id to the async queue to signal to other parts
* of the application that some async work is currently being
* done.
* @param {String} key The id of the async job.
* @private
*/
Collection.prototype._asyncPending = function (key) {
this._deferQueue.async.push(key);
};
/**
* Removes a job id from the async queue to signal to other
* parts of the application that some async work has been
* completed. If no further async jobs exist on the queue then
* the "ready" event is emitted from this collection instance.
* @param {String} key The id of the async job.
* @private
*/
Collection.prototype._asyncComplete = function (key) {
// Remove async flag for this type
var index = this._deferQueue.async.indexOf(key);
while (index > -1) {
this._deferQueue.async.splice(index, 1);
index = this._deferQueue.async.indexOf(key);
}
if (this._deferQueue.async.length === 0) {
this.deferEmit('ready');
}
};
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @param {Function=} callback A callback method to call once the
* operation has completed.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._data;
delete this._metrics;
delete this._listeners;
if (callback) { callback.call(this, false, true); }
return true;
}
} else {
if (callback) { callback.call(this, false, true); }
return true;
}
if (callback) { callback.call(this, false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', {
keyName: keyName,
oldData: oldKey
});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection by updating the
* lastChange timestamp on the collection's metaData. This
* only happens if the changeTimestamp option is enabled
* on the collection (it is disabled by default).
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = this.serialiser.convert(new Date());
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
Collection.prototype.setData = new Overload('Collection.prototype.setData', {
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
*/
'*': function (data) {
return this.$main.call(this, data, {});
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Object} options Optional options object.
*/
'*, object': function (data, options) {
return this.$main.call(this, data, options);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Function} callback Optional callback function.
*/
'*, function': function (data, callback) {
return this.$main.call(this, data, {}, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {*} options Optional options object.
* @param {Function} callback Optional callback function.
*/
'*, *, function': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {*} options Optional options object.
* @param {*} callback Optional callback function.
*/
'*, *, *': function (data, options, callback) {
return this.$main.call(this, data, options, callback);
},
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set via the remove() method, and the remove event will
* fire as well.
* @name setData
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param {Object} options Optional options object.
* @param {Function} callback Optional callback function.
*/
'$main': function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var deferredSetting = this.deferredCalls(),
oldData = [].concat(this._data);
// Switch off deferred calls since setData should be
// a synchronous call
this.deferredCalls(false);
options = this.options(options);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
// Remove all items from the collection
this.remove({});
// Insert the new data
this.insert(data);
// Switch deferred calls back to previous settings
this.deferredCalls(deferredSetting);
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback.call(this); }
return this;
}
});
/**
* Drops and rebuilds the primary key index for all documents
* in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a hash string
jString = this.hash(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This should use remove so that chain reactor events are properly
// TODO: handled, but ensure that chunking is switched off
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.emit('immediateChange', {type: 'truncate'});
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Inserts a new document or updates an existing document in a
* collection depending on if a matching primary key exists in
* the collection already or not.
*
* If the document contains a primary key field (based on the
* collections's primary key) then the database will search for
* an existing document with a matching id. If a matching
* document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with
* new data. Any keys that do not currently exist on the document
* will be added to the document.
*
* If the document does not contain an id or the id passed does
* not match an existing document, an insert is performed instead.
* If no id is present a new primary key id is provided for the
* document and the document is inserted.
*
* @param {Object} obj The document object to upsert or an array
* containing documents to upsert.
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains
* either "insert" or "update" depending on the type of operation
* that was performed and "result" contains the return data from
* the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert,
returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (this._deferredCalls && obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
this._asyncPending('upsert');
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback.call(this); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj, callback);
break;
case 'update':
returnData.result = this.update(query, obj, {}, callback);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback.call(this); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection.
* This will update all matches for 'query' with the data held
* in 'update'. It will not overwrite the matched documents
* with the update document.
*
* @param {Object} query The query that must be matched for a
* document to be operated on.
* @param {Object} update The object containing updated
* key/values. Any keys that match keys on the existing document
* will be overwritten with this data. Any keys that do not
* currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when
* the update is complete.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
} else {
// Decouple the update data
update = this.decouple(update);
}
// Handle transform
update = this.transformIn(update);
return this._handleUpdate(query, update, options, callback);
};
/**
* Handles the update operation that was initiated by a call to update().
* @param {Object} query The query that must be matched for a
* document to be operated on.
* @param {Object} update The object containing updated
* key/values. Any keys that match keys on the existing document
* will be overwritten with this data. Any keys that do not
* currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @param {Function=} callback The callback method to call when
* the update is complete.
* @returns {Array} The items that were updated.
* @private
*/
Collection.prototype._handleUpdate = function (query, update, options, callback) {
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Updated some data');
}
op.time('Resolve chains');
if (this.chainWillSend()) {
this.chainSend('update', {
query: query,
update: update,
dataSet: this.decouple(updated)
}, options);
}
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
if (callback) { callback.call(this); }
this.emit('immediateChange', {type: 'update', data: updated});
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references. It does this by removing existing keys
* from the base object and then adding the passed object's keys to
* the existing base object, thereby maintaining any references to
* the existing base object but effectively replacing the object with
* the new one.
* @param {Object} currentObj The base object to alter.
* @param {Object} newObj The new object to overwrite the existing one
* with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document via it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to
* update to.
* @returns {Object} The document that was updated or undefined
* if no document was updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update)[0];
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update
* the document with.
* @param {Object} query The query object that we need to match to
* perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform,
* if none is specified default is to set new data against matching
* fields.
* @returns {Boolean} True if the document was updated with new /
* changed data or false if it was not updated because the data was
* the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
tempKey,
replaceObj,
pk,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
case '$replace':
operation = true;
replaceObj = update.$replace;
pk = this.primaryKey();
// Loop the existing item properties and compare with
// the replacement (never remove primary key)
for (tempKey in doc) {
if (doc.hasOwnProperty(tempKey) && tempKey !== pk) {
if (replaceObj[tempKey] === undefined) {
// The new document doesn't have this field, remove it from the doc
this._updateUnset(doc, tempKey);
updated = true;
}
}
}
// Loop the new item props and update the doc
for (tempKey in replaceObj) {
if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) {
this._updateOverwrite(doc, tempKey, replaceObj[tempKey]);
updated = true;
}
}
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark
* (a dollar at the end of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search
* query key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
} else {
returnArr = [];
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
returnArr.push(dataItem);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
if (returnArr.length) {
//op.time('Resolve chains');
self.chainSend('remove', {
query: query,
dataSet: returnArr
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
this._onChange();
this.emit('immediateChange', {type: 'remove', data: returnArr});
this.deferEmit('change', {type: 'remove', data: returnArr});
}
}
if (callback) { callback.call(this, false, returnArr); }
return returnArr;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Object} The document that was removed or undefined if
* nothing was removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj)[0];
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback.call(this, resultObj); }
this._asyncComplete(type);
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.deferEmit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Collection~insertCallback=} callback Optional callback called
* once the insert is complete.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* The insert operation's callback.
* @callback Collection~insertCallback
* @param {Object} result The result object will contain two arrays (inserted
* and failed) which represent the documents that did get inserted and those
* that didn't for some reason (usually index violation). Failed items also
* contain a reason. Inspect the failed array for further information.
*
* A third field called "deferred" is a boolean value to indicate if the
* insert operation was deferred across more than one CPU cycle (to avoid
* blocking the main thread).
*/
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Collection~insertCallback=} callback Optional callback called
* once the insert is complete.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (this._deferredCalls && data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
this._asyncPending('insert');
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback.call(this, resultObj); }
this._onChange();
this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed});
this.deferEmit('change', {type: 'insert', data: inserted, failed: failed});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc,
capped = this.capped(),
cappedSize = this.cappedSize();
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
// Check capped collection status and remove first record
// if we are over the threshold
if (capped && self._data.length > cappedSize) {
// Remove the first item in the data array
self.removeById(self._data[0][self._primaryKey]);
}
//op.time('Resolve chains');
if (self.chainWillSend()) {
self.chainSend('insert', {
dataSet: self.decouple([doc])
}, {
index: index
});
}
//op.time('Resolve chains');
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return 'Trigger cancelled operation';
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
hash = this.hash(doc),
pk = this._primaryKey;
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[pk], doc);
this._primaryCrc.uniqueSet(doc[pk], hash);
this._crcLookup.uniqueSet(hash, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
hash = this.hash(doc),
pk = this._primaryKey;
// Remove from primary key index
this._primaryIndex.unSet(doc[pk]);
this._primaryCrc.unSet(doc[pk]);
this._crcLookup.unSet(hash);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options),
coll;
coll = new Collection();
coll.db(this._db);
coll.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
return coll;
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param {String} search The string to search for. Case sensitive.
* @param {Object=} options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.call(this, query, options, callback);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinIndex,
joinSource = {},
joinQuery,
joinPath,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinSourceData,
resultRemove = [],
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
pathSolver,
waterfallCollection,
matcher;
if (!(options instanceof Array)) {
options = this.options(options);
}
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Check if the query is an array (multi-operation waterfall query)
if (query instanceof Array) {
waterfallCollection = this;
// Loop the query operations
for (i = 0; i < query.length; i++) {
// Execute each operation and pass the result into the next
// query operation
waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {});
}
return waterfallCollection.find();
}
// Pre-process any data-changing query operators first
if (query.$findSub) {
// Check we have all the parts we need
if (!query.$findSub.$path) {
throw('$findSub missing $path property!');
}
return this.findSub(
query.$findSub.$query,
query.$findSub.$path,
query.$findSub.$subQuery,
query.$findSub.$subOptions
);
}
if (query.$findSubOne) {
// Check we have all the parts we need
if (!query.$findSubOne.$path) {
throw('$findSubOne missing $path property!');
}
return this.findSubOne(
query.$findSubOne.$query,
query.$findSubOne.$path,
query.$findSubOne.$subQuery,
query.$findSubOne.$subOptions
);
}
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
// Check if the query tries to limit by data that would only exist after
// the join operation has been completed
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get references to the join sources
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinSourceData = analysis.joinsOn[joinIndex];
joinSourceKey = joinSourceData.key;
joinSourceType = joinSourceData.type;
joinSourceIdentifier = joinSourceData.id;
joinPath = new Path(analysis.joinQueries[joinSourceKey]);
joinQuery = joinPath.value(query)[0];
joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinSourceKey]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource));
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
this.spliceArrayByIndexList(resultArr, resultRemove);
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
if (!options.$aggregate) {
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
}
// Process aggregation
if (options.$aggregate) {
op.data('flag.aggregate', true);
op.time('aggregate');
pathSolver = new Path(options.$aggregate);
resultArr = pathSolver.value(resultArr);
op.time('aggregate');
}
// Now process any $groupBy clause
if (options.$groupBy) {
op.data('flag.group', true);
op.time('group');
resultArr = this.group(options.$groupBy, resultArr);
op.time('group');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformIn(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [],
transformResult,
i;
for (i = 0; i < data.length; i++) {
transformResult = this._transformOut(data[i]);
// Support transforms returning multiple items
if (transformResult instanceof Array) {
finalArr = finalArr.concat(transformResult);
} else {
finalArr.push(transformResult);
}
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Convert the index object to an array of key val objects
var self = this,
keys = sharedPathSolver.parse(sortObj, true);
if (keys.length) {
// Execute sort
arr.sort(function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < keys.length; i++) {
indexData = keys[i];
if (indexData.value === 1) {
result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
} else if (indexData.value === -1) {
result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path));
}
if (result !== 0) {
return result;
}
}
return result;
});
}
return arr;
};
/**
* Groups an array of documents into multiple array fields, named by the value
* of the given group path.
* @param {*} groupObj The key path the array objects should be grouped by.
* @param {Array} arr The array of documents to group.
* @returns {Object}
*/
Collection.prototype.group = function (groupObj, arr) {
// Convert the index object to an array of key val objects
var keys = sharedPathSolver.parse(groupObj, true),
groupPathSolver = new Path(),
groupValue,
groupResult = {},
keyIndex,
i;
if (keys.length) {
for (keyIndex = 0; keyIndex < keys.length; keyIndex++) {
groupPathSolver.path(keys[keyIndex].path);
// Execute group
for (i = 0; i < arr.length; i++) {
groupValue = groupPathSolver.get(arr[i]);
groupResult[groupValue] = groupResult[groupValue] || [];
groupResult[groupValue].push(arr[i]);
}
}
}
return groupResult;
};
// Commented as we have a new method that was originally implemented for binary trees.
// This old method actually has problems with nested sort objects
/*Collection.prototype.sortold = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};*/
/**
* REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
/*Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};*/
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
/*Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};*/
/**
* Sorts array by individual sort path.
* @param {String} key The path to sort by.
* @param {Array} arr The array of objects to sort.
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Internal method that takes a search query and options and
* returns an object containing details about the query which
* can be used to optimise the search.
*
* @param {Object} query The search query to analyse.
* @param {Object} options The query options object.
* @param {Operation} op The instance of the Operation class that
* this operation is using to track things like performance and steps
* taken etc.
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinSourceIndex,
joinSourceKey,
joinSourceType,
joinSourceIdentifier,
joinMatch,
joinSources = [],
joinSourceReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
pkQueryType,
lookupResult,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
}).length;
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Check suitability of querying key value index
pkQueryType = typeof query[this._primaryKey];
if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
lookupResult = this._primaryIndex.lookup(query, options, op);
analysis.indexMatch.push({
lookup: lookupResult,
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options, op);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) {
// Loop the join sources and keep a reference to them
for (joinSourceKey in options.$join[joinSourceIndex]) {
if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
joinMatch = options.$join[joinSourceIndex][joinSourceKey];
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
joinSources.push({
id: joinSourceIdentifier,
type: joinSourceType,
key: joinSourceKey
});
// Check if the join uses an $as operator
if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) {
joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as);
} else {
joinSourceReferences.push(joinSourceKey);
}
}
}
}
// Loop the join source references and determine if the query references
// any of the sources that are used in the join. If there no queries against
// joined sources the find method can use a code path optimised for this.
// Queries against joined sources requires the joined sources to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinSourceReferences.length; index++) {
// Check if the query references any source data that the join will create
queryPath = this._queryReferencesSource(query, joinSourceReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinSources[index].key] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinSources;
analysis.queriesOn = analysis.queriesOn.concat(joinSources);
}
return analysis;
};
/**
* Checks if the passed query references a source object (such
* as a collection) by name.
* @param {Object} query The query object to scan.
* @param {String} sourceName The source name to scan for in the query.
* @param {String=} path The path to scan from.
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesSource = function (query, sourceName, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === sourceName) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesSource(query[i], sourceName, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching
* parent documents from which the sub-documents are queried.
* @param {String} path The path string used to identify the
* key in which sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching
* which sub-documents to return.
* @param {Object=} subDocOptions The options object to use
* when querying for sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
return this._findSub(this.find(match), path, subDocQuery, subDocOptions);
};
Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
};
/**
* Finds the first sub-document from the collection's documents
* that matches the subDocQuery parameter.
* @param {Object} match The query object to use when matching
* parent documents from which the sub-documents are queried.
* @param {String} path The path string used to identify the
* key in which sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching
* which sub-documents to return.
* @param {Object=} subDocOptions The options object to use
* when querying for sub-documents.
* @returns {Object}
*/
Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) {
return this.findSub(match, path, subDocQuery, subDocOptions)[0];
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
if (options.type) {
// Check if the specified type is available
if (Shared.index[options.type]) {
// We found the type, generate it
index = new Shared.index[options.type](keys, options, this);
} else {
throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)');
}
} else {
// Create default index type
index = new IndexHashMap(keys, options, this);
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
/*if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}*/
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pk = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pk !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pk])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pk])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', {
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data.dataSet);
self.update({}, obj1);
} else {
self.insert(packet.data.dataSet);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data.dataSet);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
/**
* Creates a condition handler that will react to changes in data on the
* collection.
* @example Create a condition handler that reacts when data changes.
* var coll = db.collection('test'),
* condition = coll.when({_id: 'test1', val: 1})
* .then(function () {
* console.log('Condition met!');
* })
* .else(function () {
* console.log('Condition un-met');
* });
*
* coll.insert({_id: 'test1', val: 1});
*
* @see Condition
* @param {Object} query The query that will trigger the condition's then()
* callback.
* @returns {Condition}
*/
Collection.prototype.when = function (query) {
var queryId = JSON.stringify(query);
this._when = this._when || {};
this._when[queryId] = this._when[queryId] || new Condition(this, query);
return this._when[queryId];
};
Db.prototype.collection = new Overload('Db.prototype.collection', {
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the
* primary key field on the collection objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the
* primary key field on the collection objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other
* variants and handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var self = this,
name = options.name;
if (name) {
if (this._collection[name]) {
return this._collection[name];
} else {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
return undefined;
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
if (options.capped !== undefined) {
// Check we have a size
if (options.size !== undefined) {
this._collection[name].capped(options.capped);
this._collection[name].cappedSize(options.size);
} else {
throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!');
}
}
// Listen for events on this collection so we can fire global events
// on the database in response to it
self._collection[name].on('change', function () {
self.emit('change', self._collection[name], 'collection', name);
});
self.emit('create', self._collection[name], 'collection', name);
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or
* regular expression to use to match collection names against.
* @returns {Array} An array of objects containing details of each
* collection the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Condition":5,"./Index2d":9,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],5:[function(_dereq_,module,exports){
"use strict";
/**
* The condition class monitors a data source and updates it's internal
* state depending on clauses that it has been given. When all clauses
* are satisfied the then() callback is fired. If conditions were met
* but data changed that made them un-met, the else() callback is fired.
*/
var Shared,
Condition;
Shared = _dereq_('./Shared');
/**
* Create a constructor method that calls the instance's init method.
* This allows the constructor to be overridden by other modules because
* they can override the init method with their own.
*/
Condition = function () {
this.init.apply(this, arguments);
};
Condition.prototype.init = function (dataSource, clause) {
this._dataSource = dataSource;
this._query = [clause];
this._started = false;
this._state = [false];
this._satisfied = false;
// Set this to true by default for faster performance
this.earlyExit(true);
};
// Tell ForerunnerDB about our new module
Shared.addModule('Condition', Condition);
// Mixin some commonly used methods
Shared.mixin(Condition.prototype, 'Mixin.Common');
Shared.mixin(Condition.prototype, 'Mixin.ChainReactor');
Shared.synthesize(Condition.prototype, 'then');
Shared.synthesize(Condition.prototype, 'else');
Shared.synthesize(Condition.prototype, 'earlyExit');
/**
* Adds a new clause to the condition.
* @param {Object} clause The query clause to add to the condition.
* @returns {Condition}
*/
Condition.prototype.and = function (clause) {
this._query.push(clause);
this._state.push(false);
return this;
};
/**
* Starts the condition so that changes to data will call callback
* methods according to clauses being met.
* @returns {Condition}
*/
Condition.prototype.start = function () {
if (!this._started) {
var self = this;
// Resolve the current state
this._updateStates();
self._onChange = function () {
self._updateStates();
};
// Create a chain reactor link to the data source so we start receiving CRUD ops from it
this._dataSource.on('change', self._onChange);
this._started = true;
}
return this;
};
/**
* Updates the internal status of all the clauses against the underlying
* data source.
* @private
*/
Condition.prototype._updateStates = function () {
var satisfied = true,
i;
for (i = 0; i < this._query.length; i++) {
this._state[i] = this._dataSource.count(this._query[i]) > 0;
if (!this._state[i]) {
satisfied = false;
// Early exit since we have found a state that is not true
if (this._earlyExit) {
break;
}
}
}
if (this._satisfied !== satisfied) {
// Our state has changed, fire the relevant operation
if (satisfied) {
// Fire the "then" operation
if (this._then) {
this._then();
}
} else {
// Fire the "else" operation
if (this._else) {
this._else();
}
}
this._satisfied = satisfied;
}
};
/**
* Stops the condition so that callbacks will no longer fire.
* @returns {Condition}
*/
Condition.prototype.stop = function () {
if (this._started) {
this._dataSource.off('change', this._onChange);
delete this._onChange;
this._started = false;
}
return this;
};
// Tell ForerunnerDB that our module has finished loading
Shared.finishModule('Condition');
module.exports = Condition;
},{"./Shared":29}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (val) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":7,"./Metrics.js":13,"./Overload":25,"./Shared":29}],7:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Checksum,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Checksum = _dereq_('./Checksum.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.Checksum = Checksum;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._listeners;
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[function(_dereq_,module,exports){
// geohash.js
// Geohash library for Javascript
// (c) 2008 David Troy
// Distributed under the MIT License
// Original at: https://github.com/davetroy/geohash-js
// Modified by Irrelon Software Limited (http://www.irrelon.com)
// to clean up and modularise the code using Node.js-style exports
// and add a few helper methods.
// @by Rob Evans - [email protected]
"use strict";
/*
Define some shared constants that will be used by all instances
of the module.
*/
var bits,
base32,
neighbors,
borders,
PI180 = Math.PI / 180,
PI180R = 180 / Math.PI,
earthRadius = 6371; // mean radius of the earth
bits = [16, 8, 4, 2, 1];
base32 = "0123456789bcdefghjkmnpqrstuvwxyz";
neighbors = {
right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"},
left: {even: "238967debc01fg45kmstqrwxuvhjyznp"},
top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"},
bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"}
};
borders = {
right: {even: "bcfguvyz"},
left: {even: "0145hjnp"},
top: {even: "prxz"},
bottom: {even: "028b"}
};
neighbors.bottom.odd = neighbors.left.even;
neighbors.top.odd = neighbors.right.even;
neighbors.left.odd = neighbors.bottom.even;
neighbors.right.odd = neighbors.top.even;
borders.bottom.odd = borders.left.even;
borders.top.odd = borders.right.even;
borders.left.odd = borders.bottom.even;
borders.right.odd = borders.top.even;
var GeoHash = function () {};
/**
* Converts degrees to radians.
* @param {Number} degrees
* @return {Number} radians
*/
GeoHash.prototype.radians = function radians (degrees) {
return degrees * PI180;
};
/**
* Converts radians to degrees.
* @param {Number} radians
* @return {Number} degrees
*/
GeoHash.prototype.degrees = function (radians) {
return radians * PI180R;
};
GeoHash.prototype.refineInterval = function (interval, cd, mask) {
if (cd & mask) { //jshint ignore: line
interval[0] = (interval[0] + interval[1]) / 2;
} else {
interval[1] = (interval[0] + interval[1]) / 2;
}
};
/**
* Calculates all surrounding neighbours of a hash and returns them.
* @param {String} centerHash The hash at the center of the grid.
* @param options
* @returns {*}
*/
GeoHash.prototype.calculateNeighbours = function (centerHash, options) {
var response;
if (!options || options.type === 'object') {
response = {
center: centerHash,
left: this.calculateAdjacent(centerHash, 'left'),
right: this.calculateAdjacent(centerHash, 'right'),
top: this.calculateAdjacent(centerHash, 'top'),
bottom: this.calculateAdjacent(centerHash, 'bottom')
};
response.topLeft = this.calculateAdjacent(response.left, 'top');
response.topRight = this.calculateAdjacent(response.right, 'top');
response.bottomLeft = this.calculateAdjacent(response.left, 'bottom');
response.bottomRight = this.calculateAdjacent(response.right, 'bottom');
} else {
response = [];
response[4] = centerHash;
response[3] = this.calculateAdjacent(centerHash, 'left');
response[5] = this.calculateAdjacent(centerHash, 'right');
response[1] = this.calculateAdjacent(centerHash, 'top');
response[7] = this.calculateAdjacent(centerHash, 'bottom');
response[0] = this.calculateAdjacent(response[3], 'top');
response[2] = this.calculateAdjacent(response[5], 'top');
response[6] = this.calculateAdjacent(response[3], 'bottom');
response[8] = this.calculateAdjacent(response[5], 'bottom');
}
return response;
};
/**
* Calculates a new lat/lng by travelling from the center point in the
* bearing specified for the distance specified.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param {Number} distanceKm The distance to travel in kilometers.
* @param {Number} bearing The bearing to travel in degrees (zero is
* north).
* @returns {{lat: Number, lng: Number}}
*/
GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) {
var curLon = centerPoint[1],
curLat = centerPoint[0],
destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))),
tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)),
destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º
return {
lat: this.degrees(destLat),
lng: this.degrees(destLon)
};
};
/**
* Calculates the extents of a bounding box around the center point which
* encompasses the radius in kilometers passed.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param radiusKm Radius in kilometers.
* @returns {{lat: Array, lng: Array}}
*/
GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) {
var maxWest,
maxEast,
maxNorth,
maxSouth,
lat = [],
lng = [];
maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0);
maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90);
maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180);
maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270);
lat[0] = maxNorth.lat;
lat[1] = maxSouth.lat;
lng[0] = maxWest.lng;
lng[1] = maxEast.lng;
return {
lat: lat,
lng: lng
};
};
/**
* Calculates all the geohashes that make up the bounding box that surrounds
* the circle created from the center point and radius passed.
* @param {Array} centerPoint An array with latitude at index 0 and
* longitude at index 1.
* @param {Number} radiusKm The radius in kilometers to encompass.
* @param {Number} precision The number of characters to limit the returned
* geohash strings to.
* @returns {Array} The array of geohashes that encompass the bounding box.
*/
GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) {
var extent = this.calculateExtentByRadius(centerPoint, radiusKm),
northWest = [extent.lat[0], extent.lng[0]],
northEast = [extent.lat[0], extent.lng[1]],
southWest = [extent.lat[1], extent.lng[0]],
northWestHash = this.encode(northWest[0], northWest[1], precision),
northEastHash = this.encode(northEast[0], northEast[1], precision),
southWestHash = this.encode(southWest[0], southWest[1], precision),
hash,
widthCount = 0,
heightCount = 0,
widthIndex,
heightIndex,
hashArray = [];
hash = northWestHash;
hashArray.push(hash);
// Walk from north west to north east until we find the north east geohash
while (hash !== northEastHash) {
hash = this.calculateAdjacent(hash, 'right');
widthCount++;
hashArray.push(hash);
}
hash = northWestHash;
// Walk from north west to south west until we find the south west geohash
while (hash !== southWestHash) {
hash = this.calculateAdjacent(hash, 'bottom');
heightCount++;
}
// We now know the width and height in hash boxes of the area, fill in the
// rest of the hashes into the hashArray array
for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) {
hash = hashArray[widthIndex];
for (heightIndex = 0; heightIndex < heightCount; heightIndex++) {
hash = this.calculateAdjacent(hash, 'bottom');
hashArray.push(hash);
}
}
return hashArray;
};
/**
* Calculates an adjacent hash to the hash passed, in the direction
* specified.
* @param {String} srcHash The hash to calculate adjacent to.
* @param {String} dir Either "top", "left", "bottom" or "right".
* @returns {String} The resulting geohash.
*/
GeoHash.prototype.calculateAdjacent = function (srcHash, dir) {
srcHash = srcHash.toLowerCase();
var lastChr = srcHash.charAt(srcHash.length - 1),
type = (srcHash.length % 2) ? 'odd' : 'even',
base = srcHash.substring(0, srcHash.length - 1);
if (borders[dir][type].indexOf(lastChr) !== -1) {
base = this.calculateAdjacent(base, dir);
}
return base + base32[neighbors[dir][type].indexOf(lastChr)];
};
/**
* Decodes a string geohash back to a longitude/latitude array.
* The array contains three latitudes and three longitudes. The
* first of each is the lower extent of the geohash bounding box,
* the second is the upper extent and the third is the center
* of the geohash bounding box.
* @param {String} geohash The hash to decode.
* @returns {Object}
*/
GeoHash.prototype.decode = function (geohash) {
var isEven = 1,
lat = [],
lon = [],
i, c, cd, j, mask,
latErr,
lonErr;
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
latErr = 90.0;
lonErr = 180.0;
for (i = 0; i < geohash.length; i++) {
c = geohash[i];
cd = base32.indexOf(c);
for (j = 0; j < 5; j++) {
mask = bits[j];
if (isEven) {
lonErr /= 2;
this.refineInterval(lon, cd, mask);
} else {
latErr /= 2;
this.refineInterval(lat, cd, mask);
}
isEven = !isEven;
}
}
lat[2] = (lat[0] + lat[1]) / 2;
lon[2] = (lon[0] + lon[1]) / 2;
return {
lat: lat,
lng: lon
};
};
/**
* Encodes a longitude/latitude to geohash string.
* @param latitude
* @param longitude
* @param {Number=} precision Length of the geohash string. Defaults to 12.
* @returns {String}
*/
GeoHash.prototype.encode = function (latitude, longitude, precision) {
var isEven = 1,
mid,
lat = [],
lon = [],
bit = 0,
ch = 0,
geoHash = "";
if (!precision) { precision = 12; }
lat[0] = -90.0;
lat[1] = 90.0;
lon[0] = -180.0;
lon[1] = 180.0;
while (geoHash.length < precision) {
if (isEven) {
mid = (lon[0] + lon[1]) / 2;
if (longitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lon[0] = mid;
} else {
lon[1] = mid;
}
} else {
mid = (lat[0] + lat[1]) / 2;
if (latitude > mid) {
ch |= bits[bit]; //jshint ignore: line
lat[0] = mid;
} else {
lat[1] = mid;
}
}
isEven = !isEven;
if (bit < 4) {
bit++;
} else {
geoHash += base32[ch];
bit = 0;
ch = 0;
}
}
return geoHash;
};
if (typeof module !== 'undefined') { module.exports = GeoHash; }
},{}],9:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
GeoHash = _dereq_('./GeoHash'),
sharedPathSolver = new Path(),
sharedGeoHashSolver = new GeoHash(),
// GeoHash Distances in Kilometers
geoHashDistance = [
5000,
1250,
156,
39.1,
4.89,
1.22,
0.153,
0.0382,
0.00477,
0.00119,
0.000149,
0.0000372
];
/**
* The index class used to instantiate 2d indexes that the database can
* use to handle high-performance geospatial queries.
* @constructor
*/
var Index2d = function () {
this.init.apply(this, arguments);
};
/**
* Create the index.
* @param {Object} keys The object with the keys that the user wishes the index
* to operate on.
* @param {Object} options Can be undefined, if passed is an object with arbitrary
* options keys and values.
* @param {Collection} collection The collection the index should be created for.
*/
Index2d.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('Index2d', Index2d);
Shared.mixin(Index2d.prototype, 'Mixin.Common');
Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor');
Shared.mixin(Index2d.prototype, 'Mixin.Sorting');
Index2d.prototype.id = function () {
return this._id;
};
Index2d.prototype.state = function () {
return this._state;
};
Index2d.prototype.size = function () {
return this._size;
};
Shared.synthesize(Index2d.prototype, 'data');
Shared.synthesize(Index2d.prototype, 'name');
Shared.synthesize(Index2d.prototype, 'collection');
Shared.synthesize(Index2d.prototype, 'type');
Shared.synthesize(Index2d.prototype, 'unique');
Index2d.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = sharedPathSolver.parse(this._keys).length;
return this;
}
return this._keys;
};
Index2d.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
Index2d.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
dataItem = this.decouple(dataItem);
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Convert 2d indexed values to geohashes
var keys = this._btree.keys(),
pathVal,
geoHash,
lng,
lat,
i;
for (i = 0; i < keys.length; i++) {
pathVal = sharedPathSolver.get(dataItem, keys[i].path);
if (pathVal instanceof Array) {
lng = pathVal[0];
lat = pathVal[1];
geoHash = sharedGeoHashSolver.encode(lng, lat);
sharedPathSolver.set(dataItem, keys[i].path, geoHash);
}
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
Index2d.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
Index2d.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
Index2d.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
/**
* Looks up records that match the passed query and options.
* @param query The query to execute.
* @param options A query options object.
* @param {Operation=} op Optional operation instance that allows
* us to provide operation diagnostics and analytics back to the
* main calling instance as the process is running.
* @returns {*}
*/
Index2d.prototype.lookup = function (query, options, op) {
// Loop the indexed keys and determine if the query has any operators
// that we want to handle differently from a standard lookup
var keys = this._btree.keys(),
pathStr,
pathVal,
results,
i;
for (i = 0; i < keys.length; i++) {
pathStr = keys[i].path;
pathVal = sharedPathSolver.get(query, pathStr);
if (typeof pathVal === 'object') {
if (pathVal.$near) {
results = [];
// Do a near point lookup
results = results.concat(this.near(pathStr, pathVal.$near, options, op));
}
if (pathVal.$geoWithin) {
results = [];
// Do a geoWithin shape lookup
results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op));
}
return results;
}
}
return this._btree.lookup(query, options);
};
Index2d.prototype.near = function (pathStr, query, options, op) {
var self = this,
neighbours,
visitedCount,
visitedNodes,
visitedData,
search,
results,
finalResults = [],
precision,
maxDistanceKm,
distance,
distCache,
latLng,
pk = this._collection.primaryKey(),
i;
// Calculate the required precision to encapsulate the distance
// TODO: Instead of opting for the "one size larger" than the distance boxes,
// TODO: we should calculate closest divisible box size as a multiple and then
// TODO: scan neighbours until we have covered the area otherwise we risk
// TODO: opening the results up to vastly more information as the box size
// TODO: increases dramatically between the geohash precisions
if (query.$distanceUnits === 'km') {
maxDistanceKm = query.$maxDistance;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i + 1;
break;
}
}
} else if (query.$distanceUnits === 'miles') {
maxDistanceKm = query.$maxDistance * 1.60934;
for (i = 0; i < geoHashDistance.length; i++) {
if (maxDistanceKm > geoHashDistance[i]) {
precision = i + 1;
break;
}
}
}
if (precision === 0) {
precision = 1;
}
// Calculate 9 box geohashes
if (op) { op.time('index2d.calculateHashArea'); }
neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision);
if (op) { op.time('index2d.calculateHashArea'); }
if (op) {
op.data('index2d.near.precision', precision);
op.data('index2d.near.hashArea', neighbours);
op.data('index2d.near.maxDistanceKm', maxDistanceKm);
op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]);
}
// Lookup all matching co-ordinates from the btree
results = [];
visitedCount = 0;
visitedData = {};
visitedNodes = [];
if (op) { op.time('index2d.near.getDocsInsideHashArea'); }
for (i = 0; i < neighbours.length; i++) {
search = this._btree.startsWith(pathStr, neighbours[i]);
visitedData[neighbours[i]] = search;
visitedCount += search._visitedCount;
visitedNodes = visitedNodes.concat(search._visitedNodes);
results = results.concat(search);
}
if (op) {
op.time('index2d.near.getDocsInsideHashArea');
op.data('index2d.near.startsWith', visitedData);
op.data('index2d.near.visitedTreeNodes', visitedNodes);
}
// Work with original data
if (op) { op.time('index2d.near.lookupDocsById'); }
results = this._collection._primaryIndex.lookup(results);
if (op) { op.time('index2d.near.lookupDocsById'); }
if (query.$distanceField) {
// Decouple the results before we modify them
results = this.decouple(results);
}
if (results.length) {
distance = {};
if (op) { op.time('index2d.near.calculateDistanceFromCenter'); }
// Loop the results and calculate distance
for (i = 0; i < results.length; i++) {
latLng = sharedPathSolver.get(results[i], pathStr);
distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]);
if (distCache <= maxDistanceKm) {
if (query.$distanceField) {
// Options specify a field to add the distance data to
// so add it now
sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371));
}
if (query.$geoHashField) {
// Options specify a field to add the distance data to
// so add it now
sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision));
}
// Add item as it is inside radius distance
finalResults.push(results[i]);
}
}
if (op) { op.time('index2d.near.calculateDistanceFromCenter'); }
// Sort by distance from center
if (op) { op.time('index2d.near.sortResultsByDistance'); }
finalResults.sort(function (a, b) {
return self.sortAsc(distance[a[pk]], distance[b[pk]]);
});
if (op) { op.time('index2d.near.sortResultsByDistance'); }
}
// Return data
return finalResults;
};
Index2d.prototype.geoWithin = function (pathStr, query, options) {
console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.');
return [];
};
Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) {
var R = 6371; // kilometres
var lat1Rad = this.toRadians(lat1);
var lat2Rad = this.toRadians(lat2);
var lat2MinusLat1Rad = this.toRadians(lat2-lat1);
var lng2MinusLng1Rad = this.toRadians(lng2-lng1);
var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) +
Math.cos(lat1Rad) * Math.cos(lat2Rad) *
Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
};
Index2d.prototype.toRadians = function (degrees) {
return degrees * 0.01747722222222;
};
Index2d.prototype.match = function (query, options) {
// TODO: work out how to represent that this is a better match if the query has $near than
// TODO: a basic btree index which will not be able to resolve a $near operator
return this._btree.match(query, options);
};
Index2d.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
Index2d.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
Index2d.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index['2d'] = Index2d;
Shared.finishModule('Index2d');
module.exports = Index2d;
},{"./BinaryTree":2,"./GeoHash":8,"./Path":26,"./Shared":29}],10:[function(_dereq_,module,exports){
"use strict";
/*
name(string)
id(string)
rebuild(null)
state ?? needed?
match(query, options)
lookup(query, options)
insert(doc)
remove(doc)
primaryKey(string)
collection(collection)
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree');
/**
* The index class used to instantiate btree indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new BinaryTree();
this._btree.index(keys);
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this._debug = options && options.debug ? options.debug : false;
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
this._btree.primaryKey(collection.primaryKey());
}
this.name(options && options.name ? options.name : this._id);
this._btree.debug(this._debug);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree.clear();
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
if (this._btree.insert(dataItem)) {
this._size++;
return true;
}
return false;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
if (this._btree.remove(dataItem)) {
this._size--;
return true;
}
return false;
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query, options, op) {
return this._btree.lookup(query, options, op);
};
IndexBinaryTree.prototype.match = function (query, options) {
return this._btree.match(query, options);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.btree = IndexBinaryTree;
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":2,"./Path":26,"./Shared":29}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
this._size = 0;
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
// Register this index on the shared object
Shared.index.hashed = IndexHashMap;
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":26,"./Shared":29}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} val A lookup query.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
result = [];
// Check for early exit conditions
if (valType === 'string' || valType === 'number') {
lookupItem = this.get(val);
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
} else if (valType === 'object') {
if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this.lookup(val[arrIndex]);
if (lookupItem) {
if (lookupItem instanceof Array) {
result = result.concat(lookupItem);
} else {
result.push(lookupItem);
}
}
}
return result;
} else if (val[pk]) {
return this.lookup(val[pk]);
}
}
// COMMENTED AS CODE WILL NEVER BE REACHED
// Complex lookup
/*lookupData = this._lookupKeys(val);
keys = lookupData.keys;
negate = lookupData.negate;
if (!negate) {
// Loop keys and return values
for (arrIndex = 0; arrIndex < keys.length; arrIndex++) {
result.push(this.get(keys[arrIndex]));
}
} else {
// Loop data and return non-matching keys
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (keys.indexOf(arrIndex) === -1) {
result.push(this.get(arrIndex));
}
}
}
}
return result;*/
};
// COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES
/*KeyValueStore.prototype._lookupKeys = function (val) {
var pk = this._primaryKey,
valType = typeof val,
arrIndex,
arrCount,
lookupItem,
bool,
result;
if (valType === 'string' || valType === 'number') {
return {
keys: [val],
negate: false
};
} else if (valType === 'object') {
if (val instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (val.test(arrIndex)) {
result.push(arrIndex);
}
}
}
return {
keys: result,
negate: false
};
} else if (val instanceof Array) {
// An array of primary keys, find all matches
arrCount = val.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
result = result.concat(this._lookupKeys(val[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val.$in && (val.$in instanceof Array)) {
return {
keys: this._lookupKeys(val.$in).keys,
negate: false
};
} else if (val.$nin && (val.$nin instanceof Array)) {
return {
keys: this._lookupKeys(val.$nin).keys,
negate: true
};
} else if (val.$ne) {
return {
keys: this._lookupKeys(val.$ne, true).keys,
negate: true
};
} else if (val.$or && (val.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) {
result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys);
}
return {
keys: result,
negate: false
};
} else if (val[pk]) {
return this._lookupKeys(val[pk]);
}
}
};*/
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":29}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":24,"./Shared":29}],14:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],15:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
* Creates a chain link between the current reactor node and the passed
* reactor node. Chain packets that are send by this reactor node will
* then be propagated to the passed node for subsequent packets.
* @param {*} obj The chain reactor node to link to.
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
/**
* Removes a chain link between the current reactor node and the passed
* reactor node. Chain packets sent from this reactor node will no longer
* be received by the passed node.
* @param {*} obj The chain reactor node to unlink from.
*/
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
/**
* Determines if this chain reactor node has any listeners downstream.
* @returns {Boolean} True if there are nodes downstream of this node.
*/
chainWillSend: function () {
return Boolean(this._chain);
},
/**
* Sends a chain reactor packet downstream from this node to any of its
* chained targets that were linked to this node via a call to chain().
* @param {String} type The type of chain reactor packet to send. This
* can be any string but the receiving reactor nodes will not react to
* it unless they recognise the string. Built-in strings include: "insert",
* "update", "remove", "setData" and "debug".
* @param {Object} data A data object that usually contains a key called
* "dataSet" which is an array of items to work on, and can contain other
* custom keys that help describe the operation.
* @param {Object=} options An options object. Can also contain custom
* key/value pairs that your custom chain reactor code can operate on.
*/
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index,
dataCopy = this.decouple(data, count);
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
if (arrItem.chainReceive) {
arrItem.chainReceive(this, type, dataCopy[index], options);
}
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
/**
* Handles receiving a chain reactor message that was sent via the chainSend()
* method. Creates the chain packet object and then allows it to be processed.
* @param {Object} sender The node that is sending the packet.
* @param {String} type The type of packet.
* @param {Object} data The data related to the packet.
* @param {Object=} options An options object.
*/
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
},
cancelPropagate = false;
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + ' Received data from parent reactor node');
}
// Check if we have a chain handler method
if (this._chainHandler) {
// Fire our internal handler
cancelPropagate = this._chainHandler(chainPacket);
}
// Check if we were told to cancel further propagation
if (!cancelPropagate) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],16:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Generates a JSON serialisation-compatible object instance. After the
* instance has been passed through this method, it will be able to survive
* a JSON.stringify() and JSON.parse() cycle and still end up as an
* instance at the end. Further information about this process can be found
* in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks
* @param {*} val The object instance such as "new Date()" or "new RegExp()".
*/
make: function (val) {
// This is a conversion request, hand over to serialiser
return serialiser.convert(val);
},
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined && data !== "") {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return JSON.parse(data, serialiser.reviver());
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
//return serialiser.stringify(data);
return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Generates a unique hash for the passed object.
* @param {Object} obj The object to generate a hash for.
* @returns {String}
*/
hash: function (obj) {
return JSON.stringify(obj);
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return 'ForerunnerDB ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
},
/**
* Registers a timed callback that will overwrite itself if
* the same id is used within the timeout period. Useful
* for de-bouncing fast-calls.
* @param {String} id An ID for the call (use the same one
* to debounce the same calls).
* @param {Function} callback The callback method to call on
* timeout.
* @param {Number} timeout The timeout in milliseconds before
* the callback is called.
*/
debounce: function (id, callback, timeout) {
var self = this,
newData;
self._debounce = self._debounce || {};
if (self._debounce[id]) {
// Clear timeout for this item
clearTimeout(self._debounce[id].timeout);
}
newData = {
callback: callback,
timeout: setTimeout(function () {
// Delete existing reference
delete self._debounce[id];
// Call the callback
callback();
}, timeout)
};
// Save current data
self._debounce[id] = newData;
}
};
module.exports = Common;
},{"./Overload":25,"./Serialiser":28}],17:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":25}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
if (sourceType === 'object' && source === null) {
sourceType = 'null';
}
if (testType === 'object' && test === null) {
testType = 'null';
}
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if options currently holds a root source object
if (!options.$rootSource) {
// Root query not assigned, hold the root query
options.$rootSource = source;
}
// Assign current query data
options.$currentQuery = test;
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number' || sourceType === 'null' || testType === 'null') {
// Number or null comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) {
if (!test.test(source)) {
matchedAll = false;
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Assign previous query data
options.$previousQuery = options.$parent;
// Assign parent query data
options.$parent = {
query: test[i],
key: i,
parent: options.$previousQuery
};
// Reset operation flag
operation = false;
// Grab first two chars of the key name to check for $
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object} queryOptions The options the query was passed with.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$eq': // Equals
return source == test; // jshint ignore:line
case '$eeq': // Equals equals
return source === test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
} else if (typeof test === 'object') {
return this._match(source, test, queryOptions, 'and', options);
} else {
console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery);
return false;
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
case '$find':
case '$findOne':
case '$findSub':
var fromType = 'collection',
findQuery,
findOptions,
subQuery,
subOptions,
subPath,
result,
operation = {};
// Check all parts of the $find operation exist
if (!test.$from) {
throw(key + ' missing $from property!');
}
if (test.$fromType) {
fromType = test.$fromType;
// Check the fromType exists as a method
if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') {
throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!');
}
}
// Perform the find operation
findQuery = test.$query || {};
findOptions = test.$options || {};
if (key === '$findSub') {
if (!test.$path) {
throw(key + ' missing $path property!');
}
subPath = test.$path;
subQuery = test.$subQuery || {};
subOptions = test.$subOptions || {};
if (options.$parent && options.$parent.parent && options.$parent.parent.key) {
result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions);
} else {
// This is a root $find* query
// Test the source against the main findQuery
if (this._match(source, findQuery, {}, 'and', options)) {
result = this._findSub([source], subPath, subQuery, subOptions);
}
return result && result.length > 0;
}
} else {
result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions);
}
operation[options.$parent.parent.key] = result;
return this._match(source, operation, queryOptions, 'and', options);
}
return -1;
},
/**
*
* @param {Array | Object} docArr An array of objects to run the join
* operation against or a single object.
* @param {Array} joinClause The join clause object array (the array in
* the $join key of a normal join options object).
* @param {Object} joinSource An object containing join source reference
* data or a blank object if you are doing a bespoke join operation.
* @param {Object} options An options object or blank object if no options.
* @returns {Array}
* @private
*/
applyJoin: function (docArr, joinClause, joinSource, options) {
var self = this,
joinSourceIndex,
joinSourceKey,
joinMatch,
joinSourceType,
joinSourceIdentifier,
resultKeyName,
joinSourceInstance,
resultIndex,
joinSearchQuery,
joinMulti,
joinRequire,
joinPrefix,
joinMatchIndex,
joinMatchData,
joinSearchOptions,
joinFindResults,
joinFindResult,
joinItem,
resultRemove = [],
l;
if (!(docArr instanceof Array)) {
// Turn the document into an array
docArr = [docArr];
}
for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) {
for (joinSourceKey in joinClause[joinSourceIndex]) {
if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) {
// Get the match data for the join
joinMatch = joinClause[joinSourceIndex][joinSourceKey];
// Check if the join is to a collection (default) or a specified source type
// e.g 'view' or 'collection'
joinSourceType = joinMatch.$sourceType || 'collection';
joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey;
// Set the key to store the join result in to the collection name by default
// can be overridden by the '$as' clause in the join object
resultKeyName = joinSourceKey;
// Get the join collection instance from the DB
if (joinSource[joinSourceIdentifier]) {
// We have a joinSource for this identifier already (given to us by
// an index when we analysed the query earlier on) and we can use
// that source instead.
joinSourceInstance = joinSource[joinSourceIdentifier];
} else {
// We do not already have a joinSource so grab the instance from the db
if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') {
joinSourceInstance = this._db[joinSourceType](joinSourceKey);
}
}
// Loop our result data array
for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
joinMatchData = joinMatch[joinMatchIndex];
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatchData.$query || joinMatchData.$options) {
if (joinMatchData.$query) {
// Commented old code here, new one does dynamic reverse lookups
//joinSearchQuery = joinMatchData.query;
joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]);
}
if (joinMatchData.$options) {
joinSearchOptions = joinMatchData.$options;
}
} else {
throw('$join $where clause requires "$query" and / or "$options" keys to work!');
}
break;
case '$as':
// Rename the collection when stored in the result document
resultKeyName = joinMatchData;
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatchData;
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatchData;
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatchData;
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultKeyName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = docArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultIndex);
}
}
}
}
}
return resultRemove;
},
/**
* Takes a query object with dynamic references and converts the references
* into actual values from the references source.
* @param {Object} query The query object with dynamic references.
* @param {Object} item The document to apply the references to.
* @returns {*}
* @private
*/
resolveDynamicQuery: function (query, item) {
var self = this,
newQuery,
propType,
propVal,
pathResult,
i;
// Check for early exit conditions
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3));
} else {
pathResult = this.sharedPathSolver.value(item, query);
}
if (pathResult.length > 1) {
return {$in: pathResult};
} else {
return pathResult[0];
}
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self.resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
},
spliceArrayByIndexList: function (arr, list) {
var i;
for (i = list.length - 1; i >= 0; i--) {
arr.splice(list[i], 1);
}
}
};
module.exports = Matching;
},{}],20:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],21:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],22:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* When called in a before phase the newDoc object can be directly altered
* to modify the data in it before the operation is carried out.
* @callback addTriggerCallback
* @param {Object} operation The details about the operation.
* @param {Object} oldDoc The document before the operation.
* @param {Object} newDoc The document after the operation.
*/
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Constants} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Constants} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {addTriggerCallback} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
self.triggerStack = {};
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Tells the current instance to fire or ignore all triggers whether they
* are enabled or not.
* @param {Boolean} val Set to true to ignore triggers or false to not
* ignore them.
* @returns {*}
*/
ignoreTriggers: function (val) {
if (val !== undefined) {
this._ignoreTriggers = val;
return this;
}
return this._ignoreTriggers;
},
/**
* Generates triggers that fire in the after phase for all CRUD ops
* that automatically transform data back and forth and keep both
* import and export collections in sync with each other.
* @param {String} id The unique id for this link IO.
* @param {Object} ioData The settings for the link IO.
*/
addLinkIO: function (id, ioData) {
var self = this,
matchAll,
exportData,
importData,
exportTriggerMethod,
importTriggerMethod,
exportTo,
importFrom,
allTypes,
i;
// Store the linkIO
self._linkIO = self._linkIO || {};
self._linkIO[id] = ioData;
exportData = ioData['export'];
importData = ioData['import'];
if (exportData) {
exportTo = self.db().collection(exportData.to);
}
if (importData) {
importFrom = self.db().collection(importData.from);
}
allTypes = [
self.TYPE_INSERT,
self.TYPE_UPDATE,
self.TYPE_REMOVE
];
matchAll = function (data, callback) {
// Match all
callback(false, true);
};
if (exportData) {
// Check for export match method
if (!exportData.match) {
// No match method found, use the match all method
exportData.match = matchAll;
}
// Check for export types
if (!exportData.types) {
exportData.types = allTypes;
}
exportTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
exportData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
exportData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
exportTo.upsert(data, callback);
} else {
// Do remove
exportTo.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (importData) {
// Check for import match method
if (!importData.match) {
// No match method found, use the match all method
importData.match = matchAll;
}
// Check for import types
if (!importData.types) {
importData.types = allTypes;
}
importTriggerMethod = function (operation, oldDoc, newDoc) {
// Check if we should execute against this data
importData.match(newDoc, function (err, doExport) {
if (!err && doExport) {
// Get data to upsert (if any)
importData.data(newDoc, operation.type, function (err, data, callback) {
if (!err && data) {
// Disable all currently enabled triggers so that we
// don't go into a trigger loop
exportTo.ignoreTriggers(true);
if (operation.type !== 'remove') {
// Do upsert
self.upsert(data, callback);
} else {
// Do remove
self.remove(data, callback);
}
// Re-enable the previous triggers
exportTo.ignoreTriggers(false);
}
});
}
});
};
}
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod);
}
}
if (importData) {
for (i = 0; i < importData.types.length; i++) {
importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod);
}
}
},
/**
* Removes a previously added link IO via it's ID.
* @param {String} id The id of the link IO to remove.
* @returns {boolean} True if successful, false if the link IO
* was not found.
*/
removeLinkIO: function (id) {
var self = this,
linkIO = self._linkIO[id],
exportData,
importData,
importFrom,
i;
if (linkIO) {
exportData = linkIO['export'];
importData = linkIO['import'];
if (exportData) {
for (i = 0; i < exportData.types.length; i++) {
self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER);
}
}
if (importData) {
importFrom = self.db().collection(importData.from);
for (i = 0; i < importData.types.length; i++) {
importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER);
}
}
delete self._linkIO[id];
return true;
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (!this._ignoreTriggers && this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response,
typeName,
phaseName;
if (!self._ignoreTriggers && self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (self.debug()) {
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
console.log('Triggers: Processing trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Check if the trigger is already in the stack, if it is,
// don't fire it again (this is so we avoid infinite loops
// where a trigger triggers another trigger which calls this
// one and so on)
if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) {
// The trigger is already in the stack, do not fire the trigger again
if (self.debug()) {
console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!');
}
continue;
}
// Add the trigger to the stack so we don't go down an endless
// trigger loop
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = true;
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Remove the trigger from the stack
self.triggerStack = self.triggerStack || {};
self.triggerStack[type] = {};
self.triggerStack[type][phase] = {};
self.triggerStack[type][phase][triggerItem.id] = false;
// Check the response for a non-expected result (anything other than
// [undefined, true or false] is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":25}],23:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to set.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":26,"./Shared":29}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {String=} name A name to provide this overload to help identify
* it if any errors occur during the resolving phase of the overload. This
* is purely for debug purposes and serves no functional purpose.
* @param {Object} def The overload definition.
* @returns {Function}
* @constructor
*/
var Overload = function (name, def) {
if (!def) {
def = name;
name = undefined;
}
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
overloadName;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown';
console.log('Overload Definition:', def);
throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['array', 'string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Gets a single value from the passed object and given path.
* @param {Object} obj The object to inspect.
* @param {String} path The path to retrieve data from.
* @returns {*}
*/
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @param {Object=} options An optional options object.
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path, options) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr,
returnArr,
i, k;
// Detect early exit
if (path && path.indexOf('.') === -1) {
return [obj[path]];
}
if (obj !== undefined && typeof obj === 'object') {
if (!options || options && !options.skipArrCheck) {
// Check if we were passed an array of objects and if so,
// iterate over the array and return the value from each
// array item
if (obj instanceof Array) {
returnArr = [];
for (i = 0; i < obj.length; i++) {
returnArr.push(this.get(obj[i], path));
}
return returnArr;
}
}
valuesArr = [];
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true}));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":29}],27:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
delete this._listeners;
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":29}],28:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
var self = this;
this._encoder = [];
this._decoder = [];
// Handler for Date() objects
this.registerHandler('$date', function (objInstance) {
if (objInstance instanceof Date) {
// Augment this date object with a new toJSON method
objInstance.toJSON = function () {
return "$date:" + this.toISOString();
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$date:') === 0) {
return self.convert(new Date(data.substr(6)));
}
return undefined;
});
// Handler for RegExp() objects
this.registerHandler('$regexp', function (objInstance) {
if (objInstance instanceof RegExp) {
objInstance.toJSON = function () {
return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '');
/*return {
source: this.source,
params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '')
};*/
};
// Tell the converter we have matched this object
return true;
}
// Tell converter to keep looking, we didn't match this object
return false;
}, function (data) {
if (typeof data === 'string' && data.indexOf('$regexp:') === 0) {
var dataStr = data.substr(8),//±
lengthEnd = dataStr.indexOf(':'),
sourceLength = Number(dataStr.substr(0, lengthEnd)),
source = dataStr.substr(lengthEnd + 1, sourceLength),
params = dataStr.substr(lengthEnd + sourceLength + 2);
return self.convert(new RegExp(source, params));
}
return undefined;
});
};
Serialiser.prototype.registerHandler = function (handles, encoder, decoder) {
if (handles !== undefined) {
// Register encoder
this._encoder.push(encoder);
// Register decoder
this._decoder.push(decoder);
}
};
Serialiser.prototype.convert = function (data) {
// Run through converters and check for match
var arr = this._encoder,
i;
for (i = 0; i < arr.length; i++) {
if (arr[i](data)) {
// The converter we called matched the object and converted it
// so let's return it now.
return data;
}
}
// No converter matched the object, return the unaltered one
return data;
};
Serialiser.prototype.reviver = function () {
var arr = this._decoder;
return function (key, value) {
// Check if we have a decoder method for this key
var decodedData,
i;
for (i = 0; i < arr.length; i++) {
decodedData = arr[i](value);
if (decodedData !== undefined) {
// The decoder we called matched the object and decoded it
// so let's return it now.
return decodedData;
}
}
// No decoder, return basic value
return value;
};
};
module.exports = Serialiser;
},{}],29:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.791',
modules: {},
plugins: {},
index: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
mixin: new Overload({
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
/**
* Adds the properties and methods defined in the mixin to the passed
* object.
* @memberof Shared
* @name mixin
* @param {Object} obj The target object to add mixin key/values to.
* @param {Object} mixinObj The object containing the keys to mix into
* the target object.
*/
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(_dereq_,module,exports){
/* jshint strict:false */
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0; // jshint ignore:line
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
if (typeof Object.create !== 'function') {
Object.create = (function() {
var Temp = function() {};
return function (prototype) {
if (arguments.length > 1) {
throw Error('Second argument not supported');
}
if (typeof prototype !== 'object') {
throw TypeError('Argument must be an object');
}
Temp.prototype = prototype;
var result = new Temp();
Temp.prototype = null;
return result;
};
})();
}
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14e
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"this" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // jshint ignore:line
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
module.exports = {};
},{}]},{},[1]);
|
src/addons/ReactFragment.js | carlosipe/react | /**
* Copyright 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 ReactFragment
*/
'use strict';
var ReactElement = require('ReactElement');
var warning = require('warning');
/**
* We used to allow keyed objects to serve as a collection of ReactElements,
* or nested sets. This allowed us a way to explicitly key a set a fragment of
* components. This is now being replaced with an opaque data structure.
* The upgrade path is to call React.addons.createFragment({ key: value }) to
* create a keyed fragment. The resulting data structure is opaque, for now.
*/
var fragmentKey;
var didWarnKey;
var canWarnForReactFragment;
if (__DEV__) {
fragmentKey = '_reactFragment';
didWarnKey = '_reactDidWarn';
try {
// Feature test. Don't even try to issue this warning if we can't use
// enumerable: false.
var dummy = function() {
return 1;
};
Object.defineProperty(
{},
fragmentKey,
{enumerable: false, value: true}
);
Object.defineProperty(
{},
'key',
{enumerable: true, get: dummy}
);
canWarnForReactFragment = true;
} catch (x) {
canWarnForReactFragment = false;
}
var proxyPropertyAccessWithWarning = function(obj, key) {
Object.defineProperty(obj, key, {
enumerable: true,
get: function() {
warning(
this[didWarnKey],
'A ReactFragment is an opaque type. Accessing any of its ' +
'properties is deprecated. Pass it to one of the React.Children ' +
'helpers.'
);
this[didWarnKey] = true;
return this[fragmentKey][key];
},
set: function(value) {
warning(
this[didWarnKey],
'A ReactFragment is an immutable opaque type. Mutating its ' +
'properties is deprecated.'
);
this[didWarnKey] = true;
this[fragmentKey][key] = value;
},
});
};
var issuedWarnings = {};
var getFragmentKeyString = function(fragment) {
var fragmentCacheKey = '';
for (var key in fragment) {
fragmentCacheKey += key + ':' + (typeof fragment[key]) + ',';
}
return fragmentCacheKey;
};
var didWarnForFragment = function(fragmentCacheKey) {
// We use the keys and the type of the value as a heuristic to dedupe the
// warning to avoid spamming too much.
var alreadyWarnedOnce = !!issuedWarnings[fragmentCacheKey];
issuedWarnings[fragmentCacheKey] = true;
return alreadyWarnedOnce;
};
}
var ReactFragment = {
// Wrap a keyed object in an opaque proxy that warns you if you access any
// of its properties.
create: function(object) {
if (__DEV__) {
if (typeof object !== 'object' || !object || Array.isArray(object)) {
warning(
false,
'React.addons.createFragment only accepts a single object. Got: %s',
object
);
return object;
}
if (ReactElement.isValidElement(object)) {
warning(
false,
'React.addons.createFragment does not accept a ReactElement ' +
'without a wrapper object.'
);
return object;
}
if (canWarnForReactFragment) {
var proxy = {};
Object.defineProperty(proxy, fragmentKey, {
enumerable: false,
value: object,
});
Object.defineProperty(proxy, didWarnKey, {
writable: true,
enumerable: false,
value: false,
});
for (var key in object) {
proxyPropertyAccessWithWarning(proxy, key);
}
Object.preventExtensions(proxy);
return proxy;
}
}
return object;
},
// Extract the original keyed object from the fragment opaque type. Warn if
// a plain object is passed here.
extract: function(fragment) {
if (__DEV__) {
if (canWarnForReactFragment) {
if (!fragment[fragmentKey]) {
var fragmentKeys = getFragmentKeyString(fragment);
warning(
didWarnForFragment(fragmentKeys),
'Any use of a keyed object should be wrapped in ' +
'React.addons.createFragment(object) before being passed as a ' +
'child. {%s}',
fragmentKeys
);
return fragment;
}
return fragment[fragmentKey];
}
}
return fragment;
},
// Check if this is a fragment and if so, extract the keyed object. If it
// is a fragment-like object, warn that it should be wrapped. Ignore if we
// can't determine what kind of object this is.
extractIfFragment: function(fragment) {
if (__DEV__) {
if (canWarnForReactFragment) {
// If it is the opaque type, return the keyed object.
if (fragment[fragmentKey]) {
return fragment[fragmentKey];
}
// Otherwise, check each property if it has an element, if it does
// it is probably meant as a fragment, so we can warn early. Defer,
// the warning to extract.
for (var key in fragment) {
if (fragment.hasOwnProperty(key) &&
ReactElement.isValidElement(fragment[key])) {
// This looks like a fragment object, we should provide an
// early warning.
return ReactFragment.extract(fragment);
}
}
}
}
return fragment;
},
};
module.exports = ReactFragment;
|
src/svg-icons/maps/subway.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsSubway = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="16" r="1"/><circle cx="8.5" cy="16" r="1"/><path d="M7.01 9h10v5h-10zM17.8 2.8C16 2.09 13.86 2 12 2c-1.86 0-4 .09-5.8.8C3.53 3.84 2 6.05 2 8.86V22h20V8.86c0-2.81-1.53-5.02-4.2-6.06zm.2 13.08c0 1.45-1.18 2.62-2.63 2.62l1.13 1.12V20H15l-1.5-1.5h-2.83L9.17 20H7.5v-.38l1.12-1.12C7.18 18.5 6 17.32 6 15.88V9c0-2.63 3-3 6-3 3.32 0 6 .38 6 3v6.88z"/>
</SvgIcon>
);
MapsSubway = pure(MapsSubway);
MapsSubway.displayName = 'MapsSubway';
MapsSubway.muiName = 'SvgIcon';
export default MapsSubway;
|
ajax/libs/antd-mobile/2.0.0-beta.4/antd-mobile.min.js | sashberd/cdnjs | /*!
* antd-mobile v2.0.0-beta.4
*
* Copyright 2015-present, Alipay, Inc.
* All rights reserved.
*/
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports["antd-mobile"]=t(require("react"),require("react-dom")):e["antd-mobile"]=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){e.exports=n(131)},function(t,n){t.exports=e},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 r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(249),a=r(o),i=n(246),l=r(i),u=n(17),s=r(u);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,s.default)(t)));e.prototype=(0,l.default)(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(a.default?(0,a.default)(e,t):e.__proto__=t)}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(17),a=r(o);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,a.default)(t))&&"function"!=typeof t?e:t}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(94),a=r(o);t.default=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),(0,a.default)(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(245),a=r(o);t.default=a.default||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}},function(e,t,n){var r,o;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var i in r)a.call(r,i)&&r[i]&&e.push(i)}}return e.join(" ")}var a={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(94),a=r(o);t.default=function(e,t,n){return t in e?(0,a.default)(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}},function(e,t,n){"use strict";n(352),n(342),n(133)},function(e,t,n){e.exports=n(362)()},function(e,n){e.exports=t},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(409);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}}),e.exports=t.default},function(e,t){var n=e.exports={version:"2.5.1"};"number"==typeof __e&&(__e=n)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(165),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentDidMount",value:function(){(0,b.default)()}},{key:"render",value:function(){var e=this.props,t=e.type,n=e.className,r=e.style,o=e.size,i=_(e,["type","className","style","size"]),l=(0,g.default)("am-icon","am-icon-"+t,"am-icon-"+o,n);return v.default.createElement("svg",(0,a.default)({className:l,style:r},i),v.default.createElement("use",{xlinkHref:"#"+t}))}}]),t}(v.default.Component);t.default=C,C.defaultProps={size:"md"},e.exports=t.default},[444,318],function(e,t,n){var r=n(65)("wks"),o=n(44),a=n(19).Symbol,i="function"==typeof a,l=e.exports=function(e){return r[e]||(r[e]=i&&a[e]||(i?a:o)("Symbol."+e))};l.store=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(251),a=r(o),i=n(250),l=r(i),u="function"==typeof l.default&&"symbol"==typeof a.default?function(e){return typeof e}:function(e){return e&&"function"==typeof l.default&&e.constructor===l.default&&e!==l.default.prototype?"symbol":typeof e};t.default="function"==typeof l.default&&"symbol"===u(a.default)?function(e){return"undefined"==typeof e?"undefined":u(e)}:function(e){return e&&"function"==typeof l.default&&e.constructor===l.default&&e!==l.default.prototype?"symbol":"undefined"==typeof e?"undefined":u(e)}},function(e,t,n){var r=n(19),o=n(13),a=n(56),i=n(29),l="prototype",u=function(e,t,n){var s,c,f,d=e&u.F,p=e&u.G,h=e&u.S,v=e&u.P,m=e&u.B,g=e&u.W,y=p?o:o[t]||(o[t]={}),b=y[l],_=p?r:h?r[t]:(r[t]||{})[l];p&&(n=t);for(s in n)c=!d&&_&&void 0!==_[s],c&&s in y||(f=c?_[s]:n[s],y[s]=p&&"function"!=typeof _[s]?n[s]:m&&c?a(f,r):g&&_[s]==f?function(e){var t=function(t,n,r){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,r)}return e.apply(this,arguments)};return t[l]=e[l],t}(f):v&&"function"==typeof f?a(Function.call,f):f,v&&((y.virtual||(y.virtual={}))[s]=f,e&u.R&&b&&!b[s]&&i(b,s,f)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,e.exports=u},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,n){var r=n(27),o=n(98),a=n(67),i=Object.defineProperty;t.f=n(23)?Object.defineProperty:function(e,t,n){if(r(e),t=a(t,!0),r(n),o)try{return i(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}},[441,322],function(e,t){"use strict";t.__esModule=!0,t.default=function(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}},function(e,t,n){e.exports=!n(28)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(99),o=n(57);e.exports=function(e){return r(o(e))}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(178),g=r(m),y=n(7),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.children,r=e.className,o=e.style,i=e.renderHeader,l=e.renderFooter,u=_(e,["prefixCls","children","className","style","renderHeader","renderFooter"]),s=(0,b.default)(t,r);return v.default.createElement("div",(0,a.default)({className:s,style:o},u),i?v.default.createElement("div",{className:t+"-header"},"function"==typeof i?i():i):null,n?v.default.createElement("div",{className:t+"-body"},n):null,l?v.default.createElement("div",{className:t+"-footer"},"function"==typeof l?l():l):null)}}]),t}(v.default.Component);t.default=C,C.Item=g.default,C.defaultProps={prefixCls:"am-list"},e.exports=t.default},function(e,t,n){var r=n(36);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t,n){var r=n(20),o=n(38);e.exports=n(23)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){"use strict";function r(e,t){return e+t}function o(e,t,n){var r=n;{if("object"!==("undefined"==typeof t?"undefined":w(t)))return"undefined"!=typeof r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):E(e,t);for(var a in t)t.hasOwnProperty(a)&&o(e,a,t[a])}}function a(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}function i(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function l(e){return i(e)}function u(e){return i(e,!0)}function s(e){var t=a(e),n=e.ownerDocument,r=n.defaultView||n.parentWindow;return t.left+=l(r),t.top+=u(r),t}function c(e){return null!==e&&void 0!==e&&e==e.window}function f(e){return c(e)?e.document:9===e.nodeType?e:e.ownerDocument}function d(e,t,n){var r=n,o="",a=f(e);return r=r||a.defaultView.getComputedStyle(e,null),r&&(o=r.getPropertyValue(t)||r[t]),o}function p(e,t){var n=e[j]&&e[j][t];if(M.test(n)&&!N.test(t)){var r=e.style,o=r[L],a=e[D][L];e[D][L]=e[j][L],r[L]="fontSize"===t?"1em":n||0,n=r.pixelLeft+R,r[L]=o,e[D][L]=a}return""===n?"auto":n}function h(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function v(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function m(e,t,n){"static"===o(e,"position")&&(e.style.position="relative");var a=-999,i=-999,l=h("left",n),u=h("top",n),c=v(l),f=v(u);"left"!==l&&(a=999),"top"!==u&&(i=999);var d="",p=s(e);("left"in t||"top"in t)&&(d=(0,P.getTransitionProperty)(e)||"",(0,P.setTransitionProperty)(e,"none")),"left"in t&&(e.style[c]="",e.style[l]=a+"px"),"top"in t&&(e.style[f]="",e.style[u]=i+"px");var m=s(e),g={};for(var y in t)if(t.hasOwnProperty(y)){var b=h(y,n),_="left"===y?a:i,C=p[y]-m[y];b===y?g[b]=_+C:g[b]=_-C}o(e,g),r(e.offsetTop,e.offsetLeft),("left"in t||"top"in t)&&(0,P.setTransitionProperty)(e,d);var x={};for(var S in t)if(t.hasOwnProperty(S)){var O=h(S,n),k=t[S]-p[S];S===O?x[O]=g[O]+k:x[O]=g[O]-k}o(e,x)}function g(e,t){var n=s(e),r=(0,P.getTransformXY)(e),o={x:r.x,y:r.y};"left"in t&&(o.x=r.x+t.left-n.left),"top"in t&&(o.y=r.y+t.top-n.top),(0,P.setTransformXY)(e,o)}function y(e,t,n){n.useCssRight||n.useCssBottom?m(e,t,n):n.useCssTransform&&(0,P.getTransformName)()in document.body.style?g(e,t,n):m(e,t,n)}function b(e,t){for(var n=0;n<e.length;n++)t(e[n])}function _(e){return"border-box"===E(e,"boxSizing")}function C(e,t,n){var r={},o=e.style,a=void 0;for(a in t)t.hasOwnProperty(a)&&(r[a]=o[a],o[a]=t[a]);n.call(e);for(a in t)t.hasOwnProperty(a)&&(o[a]=r[a])}function x(e,t,n){var r=0,o=void 0,a=void 0,i=void 0;for(a=0;a<t.length;a++)if(o=t[a])for(i=0;i<n.length;i++){var l=void 0;l="border"===o?""+o+n[i]+"Width":o+n[i],r+=parseFloat(E(e,l))||0}return r}function S(e,t,n){var r=n;if(c(e))return"width"===t?W.viewportWidth(e):W.viewportHeight(e);if(9===e.nodeType)return"width"===t?W.docWidth(e):W.docHeight(e);var o="width"===t?["Left","Right"]:["Top","Bottom"],a="width"===t?e.getBoundingClientRect().width:e.getBoundingClientRect().height,i=E(e),l=_(e,i),u=0;(null===a||void 0===a||a<=0)&&(a=void 0,u=E(e,t),(null===u||void 0===u||Number(u)<0)&&(u=e.style[t]||0),u=parseFloat(u)||0),void 0===r&&(r=l?B:A);var s=void 0!==a||l,f=a||u;return r===A?s?f-x(e,["border","padding"],o,i):u:s?r===B?f:f+(r===V?-x(e,["border"],o,i):x(e,["margin"],o,i)):u+x(e,I.slice(r),o,i)}function O(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=void 0,o=t[0];return 0!==o.offsetWidth?r=S.apply(void 0,t):C(o,z,function(){r=S.apply(void 0,t)}),r}function k(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}Object.defineProperty(t,"__esModule",{value:!0});var w="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},P=n(304),T=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,E=void 0,M=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),N=/^(top|right|bottom|left)$/,j="currentStyle",D="runtimeStyle",L="left",R="px";"undefined"!=typeof window&&(E=window.getComputedStyle?d:p);var I=["margin","border","padding"],A=-1,V=2,B=1,H=0,W={};b(["Width","Height"],function(e){W["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],W["viewport"+e](n))},W["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,a=r.documentElement,i=a[n];return"CSS1Compat"===r.compatMode&&i||o&&o[n]||i}});var z={position:"absolute",visibility:"hidden",display:"block"};b(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);W["outer"+t]=function(t,n){return t&&O(t,e,n?H:B)};var n="width"===e?["Left","Right"]:["Top","Bottom"];W[e]=function(t,r){var a=r;{if(void 0===a)return t&&O(t,e,A);if(t){var i=E(t),l=_(t);return l&&(a+=x(t,["padding","border"],n,i)),o(t,e,a)}}}});var F={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},getDocument:f,offset:function(e,t,n){return"undefined"==typeof t?s(e):void y(e,t,n||{})},isWindow:c,each:b,css:o,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);var r=e.overflow;if(r)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:k,getWindowScrollLeft:function(e){return l(e)},getWindowScrollTop:function(e){return u(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var o=0;o<n.length;o++)F.mix(e,n[o]);return e},viewportWidth:0,viewportHeight:0};k(F,W),t.default=F,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return Object.keys(e).reduce(function(t,n){return"aria-"!==n.substr(0,5)&&"data-"!==n.substr(0,5)&&"role"!==n||(t[n]=e[n]),t},{})},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n,r){var o={};if(t&&t.antLocale&&t.antLocale[n])o=t.antLocale[n];else{var a=r();o=a.default||a}var i=(0,l.default)({},o);return e.locale&&(i=(0,l.default)({},i,e.locale),e.locale.lang&&(i.lang=(0,l.default)({},o.lang,e.locale.lang))),i}function a(e){var t=e.antLocale&&e.antLocale.locale;return e.antLocale&&e.antLocale.exist&&!t?"zh-cn":t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),l=r(i);t.getComponentLocale=o,t.getLocaleCode=a},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(161),a=r(o),i=n(162),l=r(i);a.default.Item=l.default,t.default=a.default,e.exports=t.default},[441,316],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(244),a=r(o);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return(0,a.default)(e)}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports={}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.children;return b.default.isValidElement(t)&&!t.key?b.default.cloneElement(t,{key:P}):t}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),l=r(i),u=n(8),s=r(u),c=n(2),f=r(c),d=n(5),p=r(d),h=n(4),v=r(h),m=n(3),g=r(m),y=n(1),b=r(y),_=n(10),C=r(_),x=n(365),S=n(364),O=r(S),k=n(111),w=r(k),P="rc_animate_"+Date.now(),T=function(e){function t(e){(0,f.default)(this,t);var n=(0,v.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return E.call(n),n.currentlyAnimatingKeys={},n.keysToEnter=[],n.keysToLeave=[],n.state={children:(0,x.toArrayChildren)(o(n.props))},n.childrenRefs={},n}return(0,g.default)(t,e),(0,p.default)(t,[{key:"componentDidMount",value:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){t&&e.performAppear(t.key)})}},{key:"componentWillReceiveProps",value:function(e){var t=this;this.nextProps=e;var n=(0,x.toArrayChildren)(o(e)),r=this.props;r.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var a=r.showProp,i=this.currentlyAnimatingKeys,l=r.exclusive?(0,x.toArrayChildren)(o(r)):this.state.children,u=[];a?(l.forEach(function(e){var t=e&&(0,x.findChildInChildrenByKey)(n,e.key),r=void 0;r=t&&t.props[a]||!e.props[a]?t:b.default.cloneElement(t||e,(0,s.default)({},a,!0)),r&&u.push(r)}),n.forEach(function(e){e&&(0,x.findChildInChildrenByKey)(l,e.key)||u.push(e)})):u=(0,x.mergeChildren)(l,n),this.setState({children:u}),n.forEach(function(e){var n=e&&e.key;if(!e||!i[n]){var r=e&&(0,x.findChildInChildrenByKey)(l,n);if(a){var o=e.props[a];if(r){var u=(0,x.findShownChildInChildrenByKey)(l,n,a);!u&&o&&t.keysToEnter.push(n)}else o&&t.keysToEnter.push(n)}else r||t.keysToEnter.push(n)}}),l.forEach(function(e){var r=e&&e.key;if(!e||!i[r]){var o=e&&(0,x.findChildInChildrenByKey)(n,r);if(a){var l=e.props[a];if(o){var u=(0,x.findShownChildInChildrenByKey)(n,r,a);!u&&l&&t.keysToLeave.push(r)}else l&&t.keysToLeave.push(r)}else o||t.keysToLeave.push(r)}})}},{key:"componentDidUpdate",value:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)}},{key:"isValidChildByKey",value:function(e,t){var n=this.props.showProp;return n?(0,x.findShownChildInChildrenByKey)(e,t,n):(0,x.findChildInChildrenByKey)(e,t)}},{key:"stop",value:function(e){delete this.currentlyAnimatingKeys[e];var t=this.childrenRefs[e];t&&t.stop()}},{key:"render",value:function(){var e=this,t=this.props;this.nextProps=t;var n=this.state.children,r=null;n&&(r=n.map(function(n){if(null===n||void 0===n)return n;if(!n.key)throw new Error("must set key for <rc-animate> children");return b.default.createElement(O.default,{key:n.key,ref:function(t){return e.childrenRefs[n.key]=t},animation:t.animation,transitionName:t.transitionName,transitionEnter:t.transitionEnter,transitionAppear:t.transitionAppear,transitionLeave:t.transitionLeave},n)}));var o=t.component;if(o){var a=t;return"string"==typeof o&&(a=(0,l.default)({className:t.className,style:t.style},t.componentProps)),b.default.createElement(o,a,r)}return r[0]||null}}]),t}(b.default.Component);T.propTypes={component:C.default.any,componentProps:C.default.object,animation:C.default.object,transitionName:C.default.oneOfType([C.default.string,C.default.object]),transitionEnter:C.default.bool,transitionAppear:C.default.bool,exclusive:C.default.bool,transitionLeave:C.default.bool,onEnd:C.default.func,onEnter:C.default.func,onLeave:C.default.func,onAppear:C.default.func,showProp:C.default.string},T.defaultProps={animation:{},component:"span",componentProps:{},transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:a,onEnter:a,onLeave:a,onAppear:a};var E=function(){var e=this;this.performEnter=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillEnter(e.handleDoneAdding.bind(e,t,"enter")))},this.performAppear=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillAppear(e.handleDoneAdding.bind(e,t,"appear")))},this.handleDoneAdding=function(t,n){var r=e.props;if(delete e.currentlyAnimatingKeys[t],!r.exclusive||r===e.nextProps){var a=(0,x.toArrayChildren)(o(r));e.isValidChildByKey(a,t)?"appear"===n?w.default.allowAppearCallback(r)&&(r.onAppear(t),r.onEnd(t,!0)):w.default.allowEnterCallback(r)&&(r.onEnter(t),r.onEnd(t,!0)):e.performLeave(t)}},this.performLeave=function(t){e.childrenRefs[t]&&(e.currentlyAnimatingKeys[t]=!0,e.childrenRefs[t].componentWillLeave(e.handleDoneLeaving.bind(e,t)))},this.handleDoneLeaving=function(t){var n=e.props;if(delete e.currentlyAnimatingKeys[t],!n.exclusive||n===e.nextProps){var r=(0,x.toArrayChildren)(o(n));if(e.isValidChildByKey(r,t))e.performEnter(t);else{var a=function(){w.default.allowLeaveCallback(n)&&(n.onLeave(t),n.onEnd(t,!1))};(0,x.isSameChildren)(e.state.children,r,n.showProp)?a():e.setState({children:r},a)}}}};t.default=T,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(76),b=r(y),_=n(7),C=r(_),x=n(185),S=n(12),O=r(S),k=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},w=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"isInModal",value:function(e){if(/\biPhone\b|\biPod\b/i.test(navigator.userAgent)){var t=this.props.prefixCls,n=function(e){for(;e.parentNode&&e.parentNode!==document.body;){if(e.classList.contains(t))return e;e=e.parentNode}}(e.target);return n||e.preventDefault(),!0}}},{key:"renderFooterButton",value:function(e,t,n){var r={};if(e.style&&(r=e.style,"string"==typeof r)){var o={cancel:{},default:{},destructive:{color:"red"}};r=o[r]||{}}var a=function(t){t.preventDefault(),e.onPress&&e.onPress()};return g.default.createElement(O.default,{activeClassName:t+"-button-active",key:n},g.default.createElement("a",{className:t+"-button",role:"button",style:r,onClick:a},e.text||"Button"))}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.className,i=n.wrapClassName,u=n.transitionName,s=n.maskTransitionName,c=n.style,f=n.platform,d=n.footer,p=void 0===d?[]:d,h=n.operation,v=n.animated,m=n.transparent,y=n.popup,_=n.animationType,x=k(n,["prefixCls","className","wrapClassName","transitionName","maskTransitionName","style","platform","footer","operation","animated","transparent","popup","animationType"]),S=(0,C.default)(r+"-button-group-"+(2!==p.length||h?"v":"h"),r+"-button-group-"+(h?"operation":"normal")),O=p.length?g.default.createElement("div",{className:S,role:"group"},p.map(function(e,n){return t.renderFooterButton(e,r,n)})):null;y&&(m=!1);var w=void 0,P=void 0;v&&(w=P=m?"am-fade":"am-slide-up",y&&(w="slide-up"===_?"am-slide-up":"am-slide-down",P="am-fade"));var T=(0,C.default)(i,(0,l.default)({},r+"-wrap-popup",y)),E=(0,C.default)(o,(e={},(0,l.default)(e,r+"-transparent",m),(0,l.default)(e,r+"-popup",y),(0,l.default)(e,r+"-popup-"+_,y&&_),(0,l.default)(e,r+"-android","android"===f),e));return g.default.createElement(b.default,(0,a.default)({},x,{prefixCls:r,className:E,wrapClassName:T,transitionName:u||w,maskTransitionName:s||P,style:c,footer:O,wrapProps:{onTouchStart:function(e){return t.isInModal(e)}}}))}}]),t}(x.ModalComponent);t.default=w,w.defaultProps={prefixCls:"am-modal",transparent:!1,popup:!1,animationType:"slide-down",animated:!0,style:{},onShow:function(){},footer:[],closable:!1,operation:!1,platform:"ios"},e.exports=t.default},function(e,t,n){var r=n(103),o=n(58);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var r=n(57);e.exports=function(e){return Object(r(e))}},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={title:"\u65e5\u671f\u9009\u62e9",today:"\u4eca\u5929",month:"\u6708",year:"\u5e74",am:"\u4e0a\u5348",pm:"\u4e0b\u5348",dateTimeFormat:"yyyy\u5e74MM\u6708dd\u65e5 \u661f\u671fw hh:mm",dateFormat:"yyyy\u5e74MM\u6708dd\u65e5 \u661f\u671fw",noChoose:"\u672a\u9009\u62e9",week:["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],clear:"\u6e05\u9664",selectTime:"\u9009\u62e9\u65f6\u95f4",selectStartTime:"\u9009\u62e9\u5f00\u59cb\u65f6\u95f4",selectEndTime:"\u9009\u62e9\u7ed3\u675f\u65f6\u95f4",start:"\u5f00\u59cb",end:"\u7ed3\u675f",begin:"\u8d77",over:"\u6b62",begin_over:"\u8d77/\u6b62",confirm:"\u786e\u8ba4",monthTitle:"yyyy\u5e74MM\u6708",loadPrevMonth:"\u52a0\u8f7d\u4e0a\u4e00\u4e2a\u6708",yesterday:"\u6628\u5929",lastWeek:"\u8fd1\u4e00\u5468",lastMonth:"\u8fd1\u4e00\u4e2a\u6708"};t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(1),l=r(i),u=n(7),s=r(u),c=n(420),f=r(c),d=function(e){var t=e.prefixCls,n=e.className,r=e.rootNativeProps,o=e.children,i=e.style,u=e.getValue(),c=l.default.Children.map(o,function(t,n){return l.default.cloneElement(t,{selectedValue:u[n],onValueChange:function(){for(var t=arguments.length,r=Array(t),o=0;o<t;o++)r[o]=arguments[o];return e.onValueChange.apply(e,[n].concat(r))},onScrollChange:e.onScrollChange&&function(){for(var t=arguments.length,r=Array(t),o=0;o<t;o++)r[o]=arguments[o];return e.onScrollChange.apply(e,[n].concat(r))}})});return l.default.createElement("div",(0,a.default)({},r,{style:i,className:(0,s.default)(n,t)}),c)};t.default=(0,f.default)(d),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(6),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(126),C=r(_),x=n(421),S=r(x),O=function(e){function t(e){(0,s.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.scrollTo=function(e){n.zscroller.scroller.scrollTo(0,e)},n.fireValueChange=function(e){e!==n.state.selectedValue&&("selectedValue"in n.props||n.setState({selectedValue:e}),n.props.onValueChange&&n.props.onValueChange(e))},n.onScrollChange=function(){var e=n.zscroller.scroller.getValues(),t=e.top;if(t>=0){var r=g.default.Children.toArray(n.props.children),o=n.props.coumputeChildIndex(t,n.itemHeight,r.length);if(n.scrollValue!==o){n.scrollValue=o;var a=r[o];a&&n.props.onScrollChange?n.props.onScrollChange(a.props.value):console.warn&&console.warn("child not found",r,o)}}},n.scrollingComplete=function(){var e=n.zscroller.scroller.getValues(),t=e.top;t>=0&&n.props.doScrollingComplete(t,n.itemHeight,n.fireValueChange)};var r=void 0,o=n.props,a=o.selectedValue,i=o.defaultSelectedValue;if(void 0!==a)r=a;else if(void 0!==i)r=i;else{var l=g.default.Children.toArray(n.props.children);r=l&&l[0]&&l[0].props.value}return n.state={selectedValue:r},n}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentDidMount",value:function(){var e=this.contentRef,t=this.indicatorRef,n=this.maskRef,r=this.rootRef,o=r.getBoundingClientRect().height,a=this.itemHeight=t.getBoundingClientRect().height,i=Math.floor(o/a);i%2===0&&i--,i--,i/=2,e.style.padding=a*i+"px 0",t.style.top=a*i+"px",n.style.backgroundSize="100% "+a*i+"px",this.zscroller=new C.default(e,{scrollingX:!1,snapping:!0,locking:!1,penetrationDeceleration:.1,minVelocityToKeepDecelerating:.5,scrollingComplete:this.scrollingComplete,onScroll:this.props.onScrollChange&&this.onScrollChange}),this.zscroller.setDisabled(this.props.disabled),this.zscroller.scroller.setSnapSize(0,a),this.props.select(this.state.selectedValue,this.itemHeight,this.scrollTo)}},{key:"componentWillReceiveProps",value:function(e){"selectedValue"in e&&this.setState({selectedValue:e.selectedValue}),this.zscroller.setDisabled(e.disabled)}},{key:"shouldComponentUpdate",value:function(e,t){return this.state.selectedValue!==t.selectedValue||this.props.children!==e.children}},{key:"componentDidUpdate",value:function(){this.zscroller.reflow(),this.props.select(this.state.selectedValue,this.itemHeight,this.scrollTo)}},{key:"componentWillUnmount",value:function(){this.zscroller.destroy()}},{key:"getValue",value:function(){if("selectedValue"in this.props)return this.props.selectedValue;var e=g.default.Children.toArray(this.props.children);return e&&e[0]&&e[0].props.value}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.itemStyle,i=n.indicatorStyle,u=n.indicatorClassName,s=void 0===u?"":u,c=n.children,f=this.state.selectedValue,d=r+"-item",p=d+" "+r+"-item-selected",h=function(e){var t=e.props,n=t.className,r=void 0===n?"":n,a=t.style,i=t.value;return g.default.createElement("div",{style:(0,l.default)({},o,a),className:(f===i?p:d)+" "+r,key:i},e.children||e.props.children)},v=g.default.Children?g.default.Children.map(c,h):[].concat(c).map(h),m=(e={},(0,a.default)(e,n.className,!!n.className),(0,a.default)(e,r,!0),e);return g.default.createElement("div",{className:(0,b.default)(m),ref:function(e){return t.rootRef=e},style:this.props.style},g.default.createElement("div",{className:r+"-mask",ref:function(e){return t.maskRef=e}}),g.default.createElement("div",{className:r+"-indicator "+s,ref:function(e){return t.indicatorRef=e},style:i}),g.default.createElement("div",{className:r+"-content",ref:function(e){return t.contentRef=e}},v))}}]),t}(g.default.Component);O.defaultProps={prefixCls:"rmc-picker"},t.default=(0,S.default)(O),e.exports=t.default},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return"string"==typeof e}function a(e){return o(e.type)&&T(e.props.children)?b.default.cloneElement(e,{},e.props.children.split("").join(" ")):o(e)?(T(e)&&(e=e.split("").join(" ")),b.default.createElement("span",null,e)):e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),l=r(i),u=n(8),s=r(u),c=n(2),f=r(c),d=n(5),p=r(d),h=n(4),v=r(h),m=n(3),g=r(m),y=n(1),b=r(y),_=n(7),C=r(_),x=n(14),S=r(x),O=n(12),k=r(O),w=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},P=/^[\u4e00-\u9fa5]{2}$/,T=P.test.bind(P),E=function(e){function t(){return(0,f.default)(this,t),(0,v.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,g.default)(t,e),(0,p.default)(t,[{key:"render",value:function(){var e,t=this.props,n=t.children,r=t.className,o=t.prefixCls,i=t.type,u=t.size,c=t.inline,f=t.disabled,d=t.icon,p=t.loading,h=t.activeStyle,v=t.activeClassName,m=t.onClick,g=(t.delayPressIn,t.delayPressOut,w(t,["children","className","prefixCls","type","size","inline","disabled","icon","loading","activeStyle","activeClassName","onClick","delayPressIn","delayPressOut"])),y=p?"loading":d,_=(0,C.default)(o,r,(e={},(0,s.default)(e,o+"-primary","primary"===i),(0,s.default)(e,o+"-ghost","ghost"===i),(0,s.default)(e,o+"-warning","warning"===i),(0,s.default)(e,o+"-small","small"===u),(0,s.default)(e,o+"-inline",c),(0,s.default)(e,o+"-disabled",f),(0,s.default)(e,o+"-loading",p),(0,s.default)(e,o+"-icon",!!y),e)),x=b.default.Children.map(n,a),O=void 0;if("string"==typeof y)O=b.default.createElement(S.default,{"aria-hidden":"true",type:y,size:"small"===u?"xxs":"md",className:o+"-icon"});else if(y){var P=(0,C.default)("am-icon",o+"-icon","small"===u?"am-icon-xxs":"am-icon-md");O=b.default.cloneElement(y,{className:P})}return b.default.createElement(k.default,{activeClassName:v||(h?o+"-active":void 0),disabled:f,activeStyle:h},b.default.createElement("a",(0,l.default)({role:"button",className:_},g,{onClick:f?void 0:m,"aria-disabled":f}),O,x))}}]),t}(b.default.Component);E.defaultProps={prefixCls:"am-button",size:"large",inline:!1,disabled:!1,loading:!1,activeStyle:{}},t.default=E,e.exports=t.default},[442,310],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(112),v=r(h),m=n(7),g=r(m),y=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},b=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.style,r=y(e,["className","style"]),o=r.prefixCls,a=r.children,i=(0,g.default)(o+"-wrapper",t);"class"in r&&delete r.class;var l=p.default.createElement("label",{className:i,style:n},p.default.createElement(v.default,r),a);return this.props.wrapLabel?l:p.default.createElement(v.default,this.props)}}]),t}(p.default.Component);t.default=b,b.defaultProps={prefixCls:"am-checkbox",wrapLabel:!0},e.exports=t.default},[441,329],function(e,t,n){"use strict";n(52),n(330)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(112),g=r(m),y=n(7),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);
return n},C=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.style,r=_(e,["className","style"]),o=r.prefixCls,i=r.children,l=(0,b.default)(o+"-wrapper",t);"class"in r&&delete r.class;var u=v.default.createElement("label",{className:l,style:n},v.default.createElement(g.default,(0,a.default)({},r,{type:"radio"})),i);return this.props.wrapLabel?u:v.default.createElement(g.default,(0,a.default)({},this.props,{type:"radio"}))}}]),t}(v.default.Component);t.default=C,C.defaultProps={prefixCls:"am-radio",wrapLabel:!0},e.exports=t.default},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(262);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){e.exports=!0},function(e,t,n){var r=n(27),o=n(277),a=n(58),i=n(64)("IE_PROTO"),l=function(){},u="prototype",s=function(){var e,t=n(97)("iframe"),r=a.length,o="<",i=">";for(t.style.display="none",n(268).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(o+"script"+i+"document.F=Object"+o+"/script"+i),e.close(),s=e.F;r--;)delete s[u][a[r]];return s()};e.exports=Object.create||function(e,t){var n;return null!==e?(l[u]=r(e),n=new l,l[u]=null,n[i]=e):n=s(),void 0===t?n:o(n,t)}},function(e,t,n){var r=n(42),o=n(38),a=n(25),i=n(67),l=n(24),u=n(98),s=Object.getOwnPropertyDescriptor;t.f=n(23)?s:function(e,t){if(e=a(e),t=i(t,!0),u)try{return s(e,t)}catch(e){}if(l(e,t))return o(!r.f.call(e,t),e[t])}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var r=n(20).f,o=n(24),a=n(16)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,a)&&r(e,a,{configurable:!0,value:t})}},function(e,t,n){var r=n(65)("keys"),o=n(44);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t,n){var r=n(19),o="__core-js_shared__",a=r[o]||(r[o]={});e.exports=function(e){return a[e]||(a[e]={})}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(36);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){var r=n(19),o=n(13),a=n(59),i=n(69),l=n(20).f;e.exports=function(e){var t=o.Symbol||(o.Symbol=a?{}:r.Symbol||{});"_"==e.charAt(0)||e in t||l(t,e,{value:i.f(e)})}},function(e,t,n){t.f=n(16)},function(e,t,n){"use strict";function r(e,t,n,r,a,i,l,u){if(o(t),!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,a,i,l,u],f=0;s=new Error(t.replace(/%s/g,function(){return c[f++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}}var o=function(e){};e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(374),g=n(113),y={all:g.DIRECTION_ALL,vertical:g.DIRECTION_VERTICAL,horizontal:g.DIRECTION_HORIZONTAL},b=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={},n.triggerEvent=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];var a=n.props[e];"function"==typeof a&&a.apply(void 0,[n.getGestureState()].concat(r))},n.triggerCombineEvent=function(e,t){for(var r=arguments.length,o=Array(r>2?r-2:0),a=2;a<r;a++)o[a-2]=arguments[a];n.triggerEvent.apply(n,[e].concat(o)),n.triggerSubEvent.apply(n,[e,t].concat(o))},n.triggerSubEvent=function(e,t){for(var r=arguments.length,o=Array(r>2?r-2:0),a=2;a<r;a++)o[a-2]=arguments[a];if(t){var i=(0,m.getEventName)(e,t);n.triggerEvent.apply(n,[i].concat(o))}},n.triggerPinchEvent=function(e,t){for(var r=arguments.length,o=Array(r>2?r-2:0),a=2;a<r;a++)o[a-2]=arguments[a];var i=n.gesture.scale;"move"===t&&"number"==typeof i&&(i>1&&n.triggerEvent("onPinchOut"),i<1&&n.triggerEvent("onPinchIn")),n.triggerCombineEvent.apply(n,[e,t].concat(o))},n.initPressTimer=function(){n.cleanPressTimer(),n.pressTimer=setTimeout(function(){n.setGestureState({press:!0}),n.triggerEvent("onPress")},g.PRESS.time)},n.cleanPressTimer=function(){n.pressTimer&&clearTimeout(n.pressTimer)},n.setGestureState=function(e){n.gesture||(n.gesture={}),n.gesture=(0,a.default)({},n.gesture,e)},n.getGestureState=function(){return n.gesture?(0,a.default)({},n.gesture):n.gesture},n.cleanGestureState=function(){delete n.gesture},n.getTouches=function(e){return Array.prototype.slice.call(e.touches).map(function(e){return{x:e.screenX,y:e.screenY}})},n.triggerUserCb=function(e,t){var r=(0,m.getEventName)("onTouch",e);r in n.props&&n.props[r](t)},n._handleTouchStart=function(e){n.triggerUserCb("start",e),n.event=e,e.touches.length>1&&e.preventDefault(),n.initGestureStatus(e),n.initPressTimer(),n.checkIfMultiTouchStart()},n.initGestureStatus=function(e){n.cleanGestureState();var t=n.getTouches(e),r=(0,m.now)(),o=(0,m.calcMutliFingerStatus)(t);n.setGestureState({startTime:r,startTouches:t,startMutliFingerStatus:o,time:r,touches:t,mutliFingerStatus:o})},n.checkIfMultiTouchStart=function(){var e=n.props,t=e.enablePinch,r=e.enableRotate,o=n.gesture.touches;if(o.length>1&&(t||r)){if(t){var a=(0,m.calcMutliFingerStatus)(o);n.setGestureState({startMutliFingerStatus:a,pinch:!0,scale:1}),n.triggerCombineEvent("onPinch","start")}r&&(n.setGestureState({rotate:!0,rotation:0}),n.triggerCombineEvent("onRotate","start"))}},n._handleTouchMove=function(e){n.triggerUserCb("move",e),n.event=e,n.gesture&&(n.cleanPressTimer(),n.updateGestureStatus(e),n.checkIfSingleTouchMove(),n.checkIfMultiTouchMove())},n.checkIfMultiTouchMove=function(){var e=n.gesture,t=e.pinch,r=e.rotate,o=e.touches,a=e.startMutliFingerStatus,i=e.mutliFingerStatus;if(t||r){if(o.length<2)return n.setGestureState({pinch:!1,rotate:!1}),t&&n.triggerCombineEvent("onPinch","cancel"),void(r&&n.triggerCombineEvent("onRotate","cancel"));if(t){var l=i.z/a.z;n.setGestureState({scale:l}),n.triggerPinchEvent("onPinch","move")}if(r){var u=(0,m.calcRotation)(a,i);n.setGestureState({rotation:u}),n.triggerCombineEvent("onRotate","move")}}},n.allowGesture=function(){return(0,m.shouldTriggerDirection)(n.gesture.direction,n.directionSetting)},n.checkIfSingleTouchMove=function(){var e=n.gesture,t=e.pan,r=e.touches,o=e.moveStatus;if(r.length>1)return n.setGestureState({pan:!1}),void(t&&n.triggerCombineEvent("onPan","cancel"));if(o){var a=o.x,i=o.y,l=(0,m.getDirection)(a,i);n.setGestureState({direction:l});var u=(0,m.getDirectionEventName)(l);if(!n.allowGesture())return;t?(n.triggerCombineEvent("onPan",u),n.triggerSubEvent("onPan","move")):(n.triggerCombineEvent("onPan","start"),n.setGestureState({pan:!0}))}},n.checkIfMultiTouchEnd=function(e){var t=n.gesture,r=t.pinch,o=t.rotate;r&&n.triggerCombineEvent("onPinch",e),o&&n.triggerCombineEvent("onRotate",e)},n.updateGestureStatus=function(e){var t=(0,m.now)();if(n.setGestureState({time:t}),e.touches&&e.touches.length){var r=n.gesture,o=r.startTime,a=r.startTouches,i=r.pinch,l=r.rotate,u=n.getTouches(e),s=(0,m.calcMoveStatus)(a,u,t-o),c=void 0;(i||l)&&(c=(0,m.calcMutliFingerStatus)(u)),n.setGestureState({touches:u,mutliFingerStatus:c,moveStatus:s})}},n._handleTouchEnd=function(e){n.triggerUserCb("end",e),n.event=e,n.gesture&&(n.cleanPressTimer(),n.updateGestureStatus(e),n.doSingleTouchEnd("end"),n.checkIfMultiTouchEnd("end"))},n._handleTouchCancel=function(e){n.triggerUserCb("cancel",e),n.event=e,n.gesture&&(n.cleanPressTimer(),n.updateGestureStatus(e),n.doSingleTouchEnd("cancel"),n.checkIfMultiTouchEnd("cancel"))},n.triggerAllowEvent=function(e,t){n.allowGesture()?n.triggerCombineEvent(e,t):n.triggerSubEvent(e,t)},n.doSingleTouchEnd=function(e){var t=n.gesture,r=t.moveStatus,o=t.pinch,a=t.rotate,i=t.press,l=t.pan,u=t.direction;if(!o&&!a){if(r){var s=r.z,c=r.velocity,f=(0,m.shouldTriggerSwipe)(s,c);if(n.setGestureState({swipe:f}),l&&n.triggerAllowEvent("onPan",e),f){var d=(0,m.getDirectionEventName)(u);return void n.triggerAllowEvent("onSwipe",d)}}return i?void n.triggerEvent("onPressUp"):void n.triggerEvent("onTap")}},n.getTouchAction=function(){var e=n.props,t=e.enablePinch,r=e.enableRotate,o=n.directionSetting;return t||r||o===g.DIRECTION_ALL?"pan-x pan-y":o===g.DIRECTION_VERTICAL?"pan-x":o===g.DIRECTION_HORIZONTAL?"pan-y":"auto"},n.directionSetting=y[e.direction],n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillUnmount",value:function(){this.cleanPressTimer()}},{key:"render",value:function(){var e=this.props.children,t=v.default.Children.only(e),n=this.getTouchAction(),r={onTouchStart:this._handleTouchStart,onTouchMove:this._handleTouchMove,onTouchCancel:this._handleTouchCancel,onTouchEnd:this._handleTouchEnd};return v.default.cloneElement(t,(0,a.default)({},r,{style:(0,a.default)({touchAction:n},t.props.style||{})}))}}]),t}(h.Component);t.default=b,b.defaultProps={enableRotate:!1,enablePinch:!1,direction:"all"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return Object.keys(t).some(function(n){return e.target===(0,g.findDOMNode)(t[n])})}function a(e,t){var n=t.min,r=t.max;return e<n||e>r}function i(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function l(e,t){var n=t.marks,r=t.step,o=t.min,a=Object.keys(n).map(parseFloat);if(null!==r){var i=Math.round((e-o)/r)*r+o;a.push(i)}var l=a.map(function(t){return Math.abs(e-t)});return a[l.indexOf(Math.min.apply(Math,(0,m.default)(l)))]}function u(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n}function s(e,t){return e?t.clientY:t.pageX}function c(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function f(e,t){var n=t.getBoundingClientRect();return e?n.top+.5*n.height:n.left+.5*n.width}function d(e,t){var n=t.max,r=t.min;return e<=r?r:e>=n?n:e}function p(e,t){var n=t.step,r=l(e,t);return null===n?r:parseFloat(r.toFixed(u(n)))}function h(e){e.stopPropagation(),e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var v=n(35),m=r(v);t.isEventFromHandle=o,t.isValueOutOfRange=a,t.isNotTouchEvent=i,t.getClosestPoint=l,t.getPrecision=u,t.getMousePosition=s,t.getTouchPosition=c,t.getHandleCenterPosition=f,t.ensureValueInRange=d,t.ensureValuePrecision=p,t.pauseEvent=h;var g=n(11)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){var r=u.default.unstable_batchedUpdates?function(e){u.default.unstable_batchedUpdates(n,e)}:n;return(0,i.default)(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(130),i=r(a),l=n(11),u=r(l);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return e===t?0!==e||0!==t||1/e===1/t:e!==e&&t!==t}function a(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];if(o(e,t))return!0;if("object"!==("undefined"==typeof e?"undefined":(0,l.default)(e))||null===e||"object"!==("undefined"==typeof t?"undefined":(0,l.default)(t))||null===t)return!1;var r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(var i=0;i<r.length;i++)if(!(n.indexOf(r[i])>=0||u.call(t,r[i])&&o(e[r[i]],t[r[i]])))return!1;return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.formatDate=t.mergeDateTime=void 0;var i=n(17),l=r(i);t.shallowEqual=a;var u=(t.mergeDateTime=function(e,t){return e=e||new Date,t?new Date(e.getFullYear(),e.getMonth(),e.getDate(),t.getHours(),t.getMinutes(),t.getSeconds()):e},t.formatDate=function(e,t,n){var r=n&&n.week,o={"M+":e.getMonth()+1,"d+":e.getDate(),"h+":e.getHours(),"m+":e.getMinutes(),"s+":e.getSeconds(),"q+":Math.floor((e.getMonth()+3)/3),"w+":r&&r[e.getDay()],S:e.getMilliseconds()};/(y+)/.test(t)&&(t=t.replace(RegExp.$1,(e.getFullYear()+"").substr(4-RegExp.$1.length)));for(var a in o)new RegExp("("+a+")").test(t)&&(t=t.replace(RegExp.$1,1==RegExp.$1.length?o[a]:("00"+o[a]).substr((""+o[a]).length)));return t},Object.prototype.hasOwnProperty)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return new Date(e.getFullYear(),e.getMonth()+1,0).getDate()}function a(e){return e<10?"0"+e:e+""}function i(e){return new Date(+e)}function l(e,t){e.setDate(Math.min(e.getDate(),o(new Date(e.getFullYear(),t)))),e.setMonth(t)}Object.defineProperty(t,"__esModule",{value:!0});var u=n(6),s=r(u),c=n(35),f=r(c),d=n(2),p=r(d),h=n(5),v=r(h),m=n(4),g=r(m),y=n(3),b=r(y),_=n(1),C=r(_),x=n(46),S=r(x),O=n(47),k=r(O),w=n(406),P=r(w),T={fontSize:20},E="datetime",M="date",N="time",j="month",D="year",L=864e5,R=function(e){function t(){(0,p.default)(this,t);var e=(0,g.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={date:e.props.date||e.props.defaultDate},e.getNewDate=function(t,n){var r=parseInt(t[n],10),o=e.props,a=o.mode,u=i(e.getDate());if(a===E||a===M||a===D||a===j)switch(n){case 0:u.setFullYear(r);break;case 1:l(u,r);break;case 2:u.setDate(r);break;case 3:e.setHours(u,r);break;case 4:u.setMinutes(r);break;case 5:e.setAmPm(u,r)}else switch(n){case 0:e.setHours(u,r);break;case 1:u.setMinutes(r);break;case 2:e.setAmPm(u,r)}return e.clipDate(u)},e.onValueChange=function(t,n){var r=e.props,o=e.getNewDate(t,n);"date"in r||e.setState({date:o}),r.onDateChange&&r.onDateChange(o),r.onValueChange&&r.onValueChange(t,n)},e.onScrollChange=function(t,n){var r=e.props;if(r.onScrollChange){var o=e.getNewDate(t,n);r.onScrollChange(o,t,n)}},e}return(0,b.default)(t,e),(0,v.default)(t,[{key:"componentWillReceiveProps",value:function(e){"date"in e&&this.setState({date:e.date||e.defaultDate})}},{key:"setHours",value:function(e,t){if(this.props.use12Hours){var n=e.getHours(),r=t;r=n>=12?t+12:t,r=r>=24?0:r,e.setHours(r)}else e.setHours(t)}},{key:"setAmPm",value:function(e,t){0===t?e.setTime(+e-L/2):e.setTime(+e+L/2)}},{key:"getDefaultMinDate",value:function(){return this.defaultMinDate||(this.defaultMinDate=this.getGregorianCalendar([2e3,1,1,0,0,0])),this.defaultMinDate}},{key:"getDefaultMaxDate",value:function(){return this.defaultMaxDate||(this.defaultMaxDate=this.getGregorianCalendar([2030,1,1,23,59,59])),this.defaultMaxDate}},{key:"getDate",value:function(){return this.state.date||this.getDefaultMinDate()}},{key:"getValue",value:function(){return this.getDate()}},{key:"getMinYear",value:function(){return this.getMinDate().getFullYear()}},{key:"getMaxYear",value:function(){return this.getMaxDate().getFullYear()}},{key:"getMinMonth",value:function(){return this.getMinDate().getMonth()}},{key:"getMaxMonth",value:function(){return this.getMaxDate().getMonth()}},{key:"getMinDay",value:function(){return this.getMinDate().getDate()}},{key:"getMaxDay",value:function(){return this.getMaxDate().getDate()}},{key:"getMinHour",value:function(){return this.getMinDate().getHours()}},{key:"getMaxHour",value:function(){return this.getMaxDate().getHours()}},{key:"getMinMinute",value:function(){return this.getMinDate().getMinutes()}},{key:"getMaxMinute",value:function(){return this.getMaxDate().getMinutes()}},{key:"getMinDate",value:function(){return this.props.minDate||this.getDefaultMinDate()}},{key:"getMaxDate",value:function(){return this.props.maxDate||this.getDefaultMaxDate()}},{key:"getDateData",value:function(){for(var e=this.props,t=e.locale,n=e.formatMonth,r=e.formatDay,a=e.mode,i=this.getDate(),l=i.getFullYear(),u=i.getMonth(),s=this.getMinYear(),c=this.getMaxYear(),f=this.getMinMonth(),d=this.getMaxMonth(),p=this.getMinDay(),h=this.getMaxDay(),v=[],m=s;m<=c;m++)v.push({value:m+"",label:m+t.year+""});var g={key:"year",props:{children:v}};if(a===D)return[g];var y=[],b=0,_=11;s===l&&(b=f),c===l&&(_=d);for(var C=b;C<=_;C++){var x=n?n(C,i):C+1+t.month+"";y.push({value:C+"",label:x})}var S={key:"month",props:{children:y}};if(a===j)return[g,S];var O=[],k=1,w=o(i);s===l&&f===u&&(k=p),c===l&&d===u&&(w=h);for(var P=k;P<=w;P++){var T=r?r(P,i):P+t.day+"";O.push({value:P+"",label:T})}return[g,S,{key:"day",props:{children:O}}]}},{key:"getDisplayHour",value:function(e){return this.props.use12Hours?(0===e&&(e=12),e>12&&(e-=12),e):e}},{key:"getTimeData",value:function(){var e=0,t=23,n=0,r=59,o=this.props,i=o.mode,l=o.locale,u=o.minuteStep,s=o.use12Hours,c=this.getDate(),f=this.getMinMinute(),d=this.getMaxMinute(),p=this.getMinHour(),h=this.getMaxHour(),v=c.getHours();if(i===E){var m=c.getFullYear(),g=c.getMonth(),y=c.getDate(),b=this.getMinYear(),_=this.getMaxYear(),C=this.getMinMonth(),x=this.getMaxMonth(),S=this.getMinDay(),O=this.getMaxDay();b===m&&C===g&&S===y&&(e=p,p===v&&(n=f)),_===m&&x===g&&O===y&&(t=h,h===v&&(r=d))}else e=p,p===v&&(n=f),t=h,h===v&&(r=d);var k=[];0===e&&0===t||0!==e&&0!==t?e=this.getDisplayHour(e):0===e&&s&&(e=1,k.push({value:"0",label:l.hour?"12"+l.hour:"12"})),t=this.getDisplayHour(t);for(var w=e;w<=t;w++)k.push({value:w+"",label:l.hour?w+l.hour+"":a(w)});for(var P=[],T=n;T<=r;T+=u)P.push({value:T+"",label:l.minute?T+l.minute+"":a(T)});return[{key:"hours",props:{children:k}},{key:"minutes",props:{children:P}}].concat(s?[{key:"ampm",props:{children:[{value:"0",label:l.am},{value:"1",label:l.pm}]}}]:[])}},{key:"getGregorianCalendar",value:function(e){return new(Function.prototype.bind.apply(Date,[null].concat((0,f.default)(e))))}},{key:"clipDate",value:function(e){var t=this.props.mode,n=this.getMinDate(),r=this.getMaxDate();if(t===E){if(e<n)return i(n);if(e>r)return i(r)}else if(t===M){if(+e+L<=n)return i(n);if(e>=+r+L)return i(r)}else{var o=r.getHours(),a=r.getMinutes(),l=n.getHours(),u=n.getMinutes(),s=e.getHours(),c=e.getMinutes();if(s<l||s===l&&c<u)return i(n);if(s>o||s===o&&c>a)return i(r)}return e}},{key:"getValueCols",value:function(){var e=this.props,t=e.mode,n=e.use12Hours,r=this.getDate(),o=[],a=[];if(t===D)return{cols:this.getDateData(),value:[r.getFullYear()+""]};if(t===j)return{cols:this.getDateData(),value:[r.getFullYear()+"",r.getMonth()+""]};if(t!==E&&t!==M||(o=this.getDateData(),a=[r.getFullYear()+"",r.getMonth()+"",r.getDate()+""]),t===E||t===N){o=o.concat(this.getTimeData());var i=r.getHours(),l=[i+"",r.getMinutes()+""],u=i;n&&(u=0===i?12:i>12?i-12:i,l=[u+"",r.getMinutes()+"",(i>=12?1:0)+""]),a=a.concat(l)}return{value:a,cols:o}}},{key:"render",value:function(){var e=this.getValueCols(),t=e.value,n=e.cols,r=this.props,o=r.mode,a=r.disabled,i=r.pickerPrefixCls,l=r.prefixCls,u=r.rootNativeProps,c=r.className,f=r.style,d=(0,s.default)({flexDirection:"row",alignItems:"center"},f);return C.default.createElement(S.default,{style:d,rootNativeProps:u,className:c,prefixCls:l,selectedValue:t,onValueChange:this.onValueChange,onScrollChange:this.onScrollChange},n.map(function(e){return C.default.createElement(k.default,{style:{flex:1},key:e.key,disabled:a,prefixCls:i,itemStyle:"undefined"==typeof window&&"datetime"===o?T:void 0},e.props.children.map(function(e){return C.default.createElement(k.default.Item,{key:e.value,value:e.value},e.label)}))}))}}]),t}(C.default.Component);R.defaultProps={prefixCls:"rmc-date-picker",pickerPrefixCls:"rmc-picker",locale:P.default,mode:M,disabled:!1,minuteStep:1,onDateChange:function(){},use12Hours:!1},t.default=R,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(2),u=r(l),s=n(5),c=r(s),f=n(4),d=r(f),p=n(3),h=r(p),v=n(1),m=r(v),g=n(11),y=r(g),b=n(407),_=r(b),C=!!y.default.createPortal,x=function(e){function t(){(0,u.default)(this,t);var e=(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.saveRef=function(t){C&&(e._component=t)},e.getComponent=function(t){var n=(0,i.default)({},e.props);return["visible","onAnimateLeave"].forEach(function(e){n.hasOwnProperty(e)&&delete n[e]}),m.default.createElement(_.default,(0,i.default)({},n,{visible:t,onAnimateLeave:e.removeContainer,ref:e.saveRef}))},e.removeContainer=function(){var t=document.querySelector("#"+e.props.prefixCls+"-container");t&&(C||y.default.unmountComponentAtNode(t),t.parentNode.removeChild(t))},e.getContainer=function(){var t=e.props.prefixCls,n=document.querySelector("#"+t+"-container");return n||(n=document.createElement("div"),n.setAttribute("id",t+"-container"),document.body.appendChild(n)),n},e}return(0,h.default)(t,e),(0,c.default)(t,[{key:"componentDidMount",value:function(){this.props.visible&&this.componentDidUpdate()}},{key:"shouldComponentUpdate",value:function(e){var t=e.visible;return!(!this.props.visible&&!t)}},{key:"componentWillUnmount",value:function(){this.props.visible?this.renderDialog(!1):this.removeContainer()}},{key:"componentDidUpdate",value:function(){C||this.renderDialog(this.props.visible)}},{key:"renderDialog",value:function(e){y.default.unstable_renderSubtreeIntoContainer(this,this.getComponent(e),this.getContainer())}},{key:"render",value:function(){var e=this.props.visible;return C&&(e||this._component)?y.default.createPortal(this.getComponent(e),this.getContainer()):null}}]),t}(m.default.Component);t.default=x,x.defaultProps={visible:!1,prefixCls:"rmc-dialog",onClose:o},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.RefreshControl=t.IndexedList=t.DataSource=void 0;var o=n(120),a=r(o),i=n(413),l=r(i),u=n(415),s=r(u);a.default.IndexedList=l.default,a.default.RefreshControl=s.default;var c=a.default.DataSource;t.DataSource=c,t.IndexedList=l.default,t.RefreshControl=s.default,t.default=a.default},function(e,t){"use strict";function n(e){return{transform:e,WebkitTransform:e,MozTransform:e}}function r(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"px",n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return e=n?"0px, "+e+t+", 0px":""+e+t+", 0px, 0px","translate3d("+e+")"}function o(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"px",o=arguments.length>3&&void 0!==arguments[3]&&arguments[3];a(e.style,r(t,n,o))}function a(e,t){e.transform=t,e.webkitTransform=t,e.mozTransform=t}Object.defineProperty(t,"__esModule",{value:!0}),t.getTransformPropValue=n,t.getPxStyle=r,t.setPxStyle=o,t.setTransform=a},function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r,o=e||[],a=[],i=0;do{var r=o.filter(function(e){return t(e,i)})[0];if(!r)break;a.push(r),o=r[n.childrenKeyName]||[],i+=1}while(o.length>0);return a}e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e,t,n=this.props,r=n.className,o=n.prefixCls,i=n.children,u=n.text,s=n.size,c=n.overflowCount,f=n.dot,d=n.corner,p=n.hot,h=_(n,["className","prefixCls","children","text","size","overflowCount","dot","corner","hot"]);c=c,u="number"==typeof u&&u>c?c+"+":u,f&&(u="");var v=(0,b.default)((e={},(0,l.default)(e,o+"-dot",f),(0,l.default)(e,o+"-dot-large",f&&"large"===s),(0,l.default)(e,o+"-text",!f&&!d),(0,l.default)(e,o+"-corner",d),(0,l.default)(e,o+"-corner-large",d&&"large"===s),e)),m=(0,b.default)(o,r,(t={},(0,l.default)(t,o+"-not-a-wrapper",!i),(0,l.default)(t,o+"-corner-wrapper",d),(0,l.default)(t,o+"-hot",!!p),(0,l.default)(t,o+"-corner-wrapper-large",d&&"large"===s),t));return g.default.createElement("span",{className:m},i,(u||f)&&g.default.createElement("sup",(0,a.default)({className:v},h),u))}}]),t}(g.default.Component);t.default=C,C.defaultProps={prefixCls:"am-badge",size:"small",overflowCount:99,dot:!1,corner:!1},e.exports=t.default},[441,309],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(6),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(419),C=r(_),x=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},S=function(e){function t(e){(0,s.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onChange=function(e){n.setState({selectedIndex:e},function(){n.props.afterChange&&n.props.afterChange(e)})},n.state={selectedIndex:n.props.selectedIndex},n}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this.props,t=e.infinite,n=e.selectedIndex,r=e.beforeChange,o=(e.afterChange,e.dots),i=x(e,["infinite","selectedIndex","beforeChange","afterChange","dots"]),u=i.prefixCls,s=i.dotActiveStyle,c=i.dotStyle,f=i.className,d=i.vertical,p=(0,l.default)({},i,{wrapAround:t,slideIndex:n,beforeSlide:r}),h=[];o&&(h=[{component:function(e){for(var t=e.slideCount,n=e.slidesToScroll,r=e.currentSlide,o=[],i=0;i<t;i+=n)o.push(i);var l=o.map(function(e){var t=(0,b.default)(u+"-wrap-dot",(0,a.default)({},u+"-wrap-dot-active",e===r)),n=e===r?s:c;return g.default.createElement("div",{className:t,key:e},g.default.createElement("span",{style:n}))});return g.default.createElement("div",{className:u+"-wrap"},l)},position:"BottomCenter"}]);var v=(0,b.default)(u,f,(0,a.default)({},u+"-vertical",d));return g.default.createElement(C.default,(0,l.default)({},p,{className:v,decorators:h,afterSlide:this.onChange}))}}]),t}(g.default.Component);t.default=S,S.defaultProps={prefixCls:"am-carousel",dots:!0,arrows:!1,autoplay:!1,infinite:!1,cellAlign:"center",selectedIndex:0,dotStyle:{},dotActiveStyle:{}},e.exports=t.default},[441,313],[443,314],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n=e.renderHeader,r=e.renderFooter,o=e.renderSectionHeader,a=e.renderBodyComponent,l=s(e,["renderHeader","renderFooter","renderSectionHeader","renderBodyComponent"]),u=e.listPrefixCls,f={renderHeader:null,renderFooter:null,renderSectionHeader:null,renderBodyComponent:a||function(){return i.default.createElement("div",{className:u+"-body"})}};return n&&(f.renderHeader=function(){return i.default.createElement("div",{className:u+"-header"},n())}),r&&(f.renderFooter=function(){return i.default.createElement("div",{className:u+"-footer"},r())}),o&&(f.renderSectionHeader=t?function(e,t){return i.default.createElement("div",null,i.default.createElement(c,{prefixCls:u},o(e,t)))}:function(e,t){return i.default.createElement(c,{prefixCls:u},o(e,t))}),{restProps:l,extraProps:f}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1),i=r(a),l=n(26),u=r(l),s=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},c=u.default.Item;e.exports=t.default},[443,333],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTabBar=void 0;var o=n(5),a=r(o),i=n(6),l=r(i),u=n(2),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(430),g=t.DefaultTabBar=function(e){function t(){return(0,s.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),t}(m.DefaultTabBar);g.defaultProps=(0,l.default)({},m.DefaultTabBar.defaultProps,{prefixCls:"am-tabs-default-bar"});var y=function(e){function t(){(0,s.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.renderTabBar=function(t){var n=e.props.renderTab;return v.default.createElement(g,(0,l.default)({},t,{renderTab:n}))},e}return(0,p.default)(t,e),(0,a.default)(t,[{key:"render",value:function(){return v.default.createElement(m.Tabs,(0,l.default)({renderTabBar:this.renderTabBar},this.props))}}]),t}(v.default.PureComponent);t.default=y,y.DefaultTabBar=g,y.defaultProps={prefixCls:"am-tabs"}},[441,346],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t;return m&&(m.destroy(),m=null),m=f.default.newInstance({prefixCls:g,style:{},transitionName:"am-fade",className:(0,v.default)((t={},(0,l.default)(t,g+"-mask",e),(0,l.default)(t,g+"-nomask",!e),t))})}function a(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,r=arguments[3],a=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],i={info:"",success:"success",fail:"fail",offline:"dislike",loading:"loading"}[t],l=o(a);l.notice({duration:n,style:{},content:i?s.default.createElement("div",{className:g+"-text "+g+"-text-icon",role:"alert","aria-live":"assertive"},s.default.createElement(p.default,{type:i,size:"lg"}),s.default.createElement("div",{className:g+"-text-info"},e)):s.default.createElement("div",{className:g+"-text",role:"alert","aria-live":"assertive"},s.default.createElement("div",null,e)),onClose:function(){r&&r(),l.destroy(),l=null,m=null}})}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),l=r(i),u=n(1),s=r(u),c=n(377),f=r(c),d=n(14),p=r(d),h=n(7),v=r(h),m=void 0,g="am-toast";t.default={SHORT:3,LONG:8,show:function(e,t,n){return a(e,"info",t,function(){},n)},info:function(e,t,n,r){return a(e,"info",t,n,r)},success:function(e,t,n,r){return a(e,"success",t,n,r)},fail:function(e,t,n,r){return a(e,"fail",t,n,r)},offline:function(e,t,n,r){return a(e,"offline",t,n,r)},loading:function(e,t,n,r){return a(e,"loading",t,n,r)},hide:function(){m&&(m.destroy(),m=null)}},e.exports=t.default},[442,349],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},g=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=(0,a.default)({},this.props);if(Array.isArray(e.style)){var t={};e.style.forEach(function(e){t=(0,a.default)({},t,e)}),e.style=t}var n=e.Component,r=m(e,["Component"]);return v.default.createElement(n,r)}}]),t}(v.default.Component);t.default=g,g.defaultProps={Component:"div"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{
default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(7),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.size,r=e.className,o=e.children,a=e.style,i=(0,v.default)(t,t+"-"+n,r);return p.default.createElement("div",{className:i,style:a},o)}}]),t}(p.default.Component);t.default=m,m.defaultProps={prefixCls:"am-wingblank",size:"lg"},e.exports=t.default},[441,351],function(e,t,n){e.exports={default:n(256),__esModule:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}t.__esModule=!0;var o=n(248),a=r(o),i=n(247),l=r(i);t.default=function e(t,n,r){null===t&&(t=Function.prototype);var o=(0,l.default)(t,n);if(void 0===o){var i=(0,a.default)(t);return null===i?void 0:e(i,n,r)}if("value"in o)return o.value;var u=o.get;if(void 0!==u)return u.call(r)}},function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){var r=n(36),o=n(19).document,a=r(o)&&r(o.createElement);e.exports=function(e){return a?o.createElement(e):{}}},function(e,t,n){e.exports=!n(23)&&!n(28)(function(){return 7!=Object.defineProperty(n(97)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(55);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t,n){"use strict";var r=n(59),o=n(18),a=n(105),i=n(29),l=n(24),u=n(37),s=n(272),c=n(63),f=n(102),d=n(16)("iterator"),p=!([].keys&&"next"in[].keys()),h="@@iterator",v="keys",m="values",g=function(){return this};e.exports=function(e,t,n,y,b,_,C){s(n,t,y);var x,S,O,k=function(e){if(!p&&e in E)return E[e];switch(e){case v:return function(){return new n(this,e)};case m:return function(){return new n(this,e)}}return function(){return new n(this,e)}},w=t+" Iterator",P=b==m,T=!1,E=e.prototype,M=E[d]||E[h]||b&&E[b],N=M||k(b),j=b?P?k("entries"):N:void 0,D="Array"==t?E.entries||M:M;if(D&&(O=f(D.call(new e)),O!==Object.prototype&&O.next&&(c(O,w,!0),r||l(O,d)||i(O,d,g))),P&&M&&M.name!==m&&(T=!0,N=function(){return M.call(this)}),r&&!C||!p&&!T&&E[d]||i(E,d,N),u[t]=N,u[w]=g,b)if(x={values:P?N:k(m),keys:_?N:k(v),entries:j},C)for(S in x)S in E||a(E,S,x[S]);else o(o.P+o.F*(p||T),t,x);return x}},function(e,t,n){var r=n(103),o=n(58).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,o)}},function(e,t,n){var r=n(24),o=n(43),a=n(64)("IE_PROTO"),i=Object.prototype;e.exports=Object.getPrototypeOf||function(e){return e=o(e),r(e,a)?e[a]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?i:null}},function(e,t,n){var r=n(24),o=n(25),a=n(264)(!1),i=n(64)("IE_PROTO");e.exports=function(e,t){var n,l=o(e),u=0,s=[];for(n in l)n!=i&&r(l,n)&&s.push(n);for(;t.length>u;)r(l,n=t[u++])&&(~a(s,n)||s.push(n));return s}},function(e,t,n){var r=n(18),o=n(13),a=n(28);e.exports=function(e,t){var n=(o.Object||{})[e]||Object[e],i={};i[e]=t(n),r(r.S+r.F*a(function(){n(1)}),"Object",i)}},function(e,t,n){e.exports=n(29)},function(e,t,n){var r=n(66),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){"use strict";var r=n(280)(!0);n(100)(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=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){for(var n=window.getComputedStyle(e,null),r="",o=0;o<v.length&&!(r=n.getPropertyValue(v[o]+t));o++);return r}function a(e){if(p){var t=parseFloat(o(e,"transition-delay"))||0,n=parseFloat(o(e,"transition-duration"))||0,r=parseFloat(o(e,"animation-delay"))||0,a=parseFloat(o(e,"animation-duration"))||0,i=Math.max(n+t,a+r);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*i+200)}}function i(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}Object.defineProperty(t,"__esModule",{value:!0}),t.isCssAnimationSupported=void 0;var l=n(17),u=r(l),s=n(296),c=r(s),f=n(252),d=r(f),p=0!==c.default.endEvents.length,h=["Webkit","Moz","O","ms"],v=["-webkit-","-moz-","-o-","ms-",""],m=function(e,t,n){var r="object"===("undefined"==typeof t?"undefined":(0,u.default)(t)),o=r?t.name:t,l=r?t.active:t+"-active",s=n,f=void 0,p=void 0,h=(0,d.default)(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(s=n.end,f=n.start,p=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),i(e),h.remove(o),h.remove(l),c.default.removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,s&&s())},c.default.addEndEventListener(e,e.rcEndListener),f&&f(),h.add(o),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,h.add(l),p&&setTimeout(p,0),a(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};m.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),i(e),c.default.removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},c.default.addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,a(e)},0)},m.setTransition=function(e,t,n){var r=t,o=n;void 0===n&&(o=r,r=""),r=r||"",h.forEach(function(t){e.style[t+"Transition"+r]=o})},m.isCssAnimationSupported=p,t.isCssAnimationSupported=p,t.default=m},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){if(i.default.isWindow(e)||9===e.nodeType)return null;var t=i.default.getDocument(e),n=t.body,r=void 0,o=i.default.css(e,"position"),a="fixed"===o||"absolute"===o;if(!a)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(r=e.parentNode;r&&r!==n;r=r.parentNode)if(o=i.default.css(r,"position"),"static"!==o)return r;return null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(30),i=r(a);t.default=o,e.exports=t.default},function(e,t,n){(function(t){for(var r=n(360),o="undefined"==typeof window?t:window,a=["moz","webkit"],i="AnimationFrame",l=o["request"+i],u=o["cancel"+i]||o["cancelRequest"+i],s=0;!l&&s<a.length;s++)l=o[a[s]+"Request"+i],u=o[a[s]+"Cancel"+i]||o[a[s]+"CancelRequest"+i];if(!l||!u){var c=0,f=0,d=[],p=1e3/60;l=function(e){if(0===d.length){var t=r(),n=Math.max(0,p-(t-c));c=n+t,setTimeout(function(){var e=d.slice(0);d.length=0;for(var t=0;t<e.length;t++)if(!e[t].cancelled)try{e[t].callback(c)}catch(e){setTimeout(function(){throw e},0)}},Math.round(n))}return d.push({handle:++f,callback:e,cancelled:!1}),f},u=function(e){for(var t=0;t<d.length;t++)d[t].handle===e&&(d[t].cancelled=!0)}}e.exports=function(e){return l.call(o,e)},e.exports.cancel=function(){u.apply(o,arguments)},e.exports.polyfill=function(){o.requestAnimationFrame=l,o.cancelAnimationFrame=u}}).call(t,function(){return this}())},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}};t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(366);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}}),e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=(t.DIRECTION_NONE=1,t.DIRECTION_LEFT=2),r=t.DIRECTION_RIGHT=4,o=t.DIRECTION_UP=8,a=t.DIRECTION_DOWN=16,i=t.DIRECTION_HORIZONTAL=n|r,l=t.DIRECTION_VERTICAL=o|a;t.DIRECTION_ALL=i|l,t.PRESS={time:251},t.SWIPE={threshold:10,velocity:.3}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(1),l=r(i),u=function(e){var t=e.className,n=e.included,r=e.vertical,o=e.offset,i=e.length,u=e.style,s=r?{bottom:o+"%",height:i+"%"}:{left:o+"%",width:i+"%"},c=(0,a.default)({visibility:n?"visible":"hidden"},u,s);return l.default.createElement("div",{className:t,style:c})};t.default=u,e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}function a(){}function i(e){var t,n;return n=t=function(e){function t(e){(0,h.default)(this,t);var n=(0,y.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onMouseDown=function(e){if(0===e.button){var t=n.props.vertical,r=B.getMousePosition(t,e);if(B.isEventFromHandle(e,n.handlesRefs)){var o=B.getHandleCenterPosition(t,e.target);n.dragOffset=r-o,r=o}else n.dragOffset=0;n.onStart(r),n.addDocumentMouseEvents(),B.pauseEvent(e)}},n.onTouchStart=function(e){if(!B.isNotTouchEvent(e)){var t=n.props.vertical,r=B.getTouchPosition(t,e);if(B.isEventFromHandle(e,n.handlesRefs)){var o=B.getHandleCenterPosition(t,e.target);n.dragOffset=r-o,r=o}else n.dragOffset=0;n.onStart(r),n.addDocumentTouchEvents(),B.pauseEvent(e)}},n.onMouseMove=function(e){if(!n.sliderRef)return void n.onEnd();var t=B.getMousePosition(n.props.vertical,e);n.onMove(e,t-n.dragOffset)},n.onTouchMove=function(e){if(B.isNotTouchEvent(e)||!n.sliderRef)return void n.onEnd();var t=B.getTouchPosition(n.props.vertical,e);n.onMove(e,t-n.dragOffset)},n.saveSlider=function(e){n.sliderRef=e};return n.handlesRefs={},n}return(0,x.default)(t,e),(0,m.default)(t,[{key:"componentWillUnmount",value:function(){(0,_.default)(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillUnmount",this)&&(0,_.default)(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"componentWillUnmount",this).call(this),this.removeDocumentEvents()}},{key:"addDocumentTouchEvents",value:function(){this.onTouchMoveListener=(0,T.default)(document,"touchmove",this.onTouchMove),this.onTouchUpListener=(0,T.default)(document,"touchend",this.onEnd)}},{key:"addDocumentMouseEvents",value:function(){this.onMouseMoveListener=(0,T.default)(document,"mousemove",this.onMouseMove),this.onMouseUpListener=(0,T.default)(document,"mouseup",this.onEnd)}},{key:"removeDocumentEvents",value:function(){this.onTouchMoveListener&&this.onTouchMoveListener.remove(),this.onTouchUpListener&&this.onTouchUpListener.remove(),this.onMouseMoveListener&&this.onMouseMoveListener.remove(),this.onMouseUpListener&&this.onMouseUpListener.remove()}},{key:"getSliderStart",value:function(){var e=this.sliderRef,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left}},{key:"getSliderLength",value:function(){var e=this.sliderRef;if(!e)return 0;var t=e.getBoundingClientRect();return this.props.vertical?t.height:t.width}},{key:"calcValue",value:function(e){var t=this.props,n=t.vertical,r=t.min,o=t.max,a=Math.abs(Math.max(e,0)/this.getSliderLength()),i=n?(1-a)*(o-r)+r:a*(o-r)+r;return i}},{key:"calcValueByPos",value:function(e){var t=e-this.getSliderStart(),n=this.trimAlignValue(this.calcValue(t));return n}},{key:"calcOffset",value:function(e){var t=this.props,n=t.min,r=t.max,o=(e-n)/(r-n);return 100*o}},{key:"saveHandle",value:function(e,t){this.handlesRefs[e]=t}},{key:"render",value:function(){var e,n=this.props,r=n.prefixCls,o=n.className,i=n.marks,l=n.dots,u=n.step,s=n.included,f=n.disabled,p=n.vertical,h=n.min,v=n.max,m=n.children,g=n.maximumTrackStyle,y=n.style,b=n.railStyle,C=n.dotStyle,x=n.activeDotStyle,S=(0,_.default)(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"render",this).call(this),k=S.tracks,w=S.handles,P=(0,M.default)(r,(e={},(0,d.default)(e,r+"-with-marks",Object.keys(i).length),(0,d.default)(e,r+"-disabled",f),(0,d.default)(e,r+"-vertical",p),(0,d.default)(e,o,o),e));return O.default.createElement("div",{ref:this.saveSlider,className:P,onTouchStart:f?a:this.onTouchStart,onMouseDown:f?a:this.onMouseDown,style:y},O.default.createElement("div",{className:r+"-rail",style:(0,c.default)({},g,b)}),k,O.default.createElement(D.default,{prefixCls:r,vertical:p,marks:i,dots:l,step:u,included:s,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:v,min:h,dotStyle:C,activeDotStyle:x}),w,O.default.createElement(R.default,{className:r+"-mark",vertical:p,marks:i,included:s,lowerBound:this.getLowerBound(),upperBound:this.getUpperBound(),max:v,min:h}),m)}}]),t}(e),t.displayName="ComponentEnhancer("+e.displayName+")",t.propTypes=(0,c.default)({},e.propTypes,{min:w.default.number,max:w.default.number,step:w.default.number,marks:w.default.object,included:w.default.bool,className:w.default.string,prefixCls:w.default.string,disabled:w.default.bool,children:w.default.any,onBeforeChange:w.default.func,onChange:w.default.func,onAfterChange:w.default.func,handle:w.default.func,dots:w.default.bool,vertical:w.default.bool,style:w.default.object,minimumTrackStyle:w.default.object,maximumTrackStyle:w.default.object,handleStyle:w.default.oneOfType([w.default.object,w.default.arrayOf(w.default.object)]),trackStyle:w.default.oneOfType([w.default.object,w.default.arrayOf(w.default.object)]),railStyle:w.default.object,dotStyle:w.default.object,activeDotStyle:w.default.object}),t.defaultProps=(0,c.default)({},e.defaultProps,{prefixCls:"rc-slider",className:"",min:0,max:100,step:1,marks:{},handle:function(e){var t=e.index,n=(0,u.default)(e,["index"]);return delete n.dragging,O.default.createElement(A.default,(0,c.default)({},n,{key:t}))},onBeforeChange:a,onChange:a,onAfterChange:a,included:!0,disabled:!1,dots:!1,vertical:!1,trackStyle:[{}],handleStyle:[{}],railStyle:{},dotStyle:{},activeDotStyle:{}}),n}Object.defineProperty(t,"__esModule",{value:!0});var l=n(22),u=o(l),s=n(6),c=o(s),f=n(8),d=o(f),p=n(2),h=o(p),v=n(5),m=o(v),g=n(4),y=o(g),b=n(95),_=o(b),C=n(3),x=o(C);t.default=i;var S=n(1),O=o(S),k=n(10),w=o(k),P=n(73),T=o(P),E=n(7),M=o(E),N=n(48),j=(o(N),n(382)),D=o(j),L=n(381),R=o(L),I=n(378),A=o(I),V=n(72),B=r(V);e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=o(a),l=n(5),u=o(l),s=n(4),c=o(s),f=n(3),d=o(f),p=n(1),h=r(p),v=n(393),m=o(v),g=n(400),y=o(g),b=n(399),_=o(b),C=function(e){function t(){(0,i.default)(this,t);var e=(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.transform={},e.genMonthComponent=function(t){if(t)return h.createElement(_.default,{key:t.title,locale:e.props.locale||{},monthData:t,rowSize:e.props.rowSize,onCellClick:e.onCellClick,getDateExtra:e.props.getDateExtra,ref:function(n){t.componentRef=n||void 0,t.updateLayout=function(){e.computeHeight(t,n)},t.updateLayout()}})},e.computeHeight=function(t,n){if(n&&n.wrapperDivDOM){if(!t.height&&!n.wrapperDivDOM.clientHeight)return void setTimeout(function(){return e.computeHeight(t,n)},500);t.height=n.wrapperDivDOM.clientHeight||t.height||0,t.y=n.wrapperDivDOM.offsetTop||t.y||0}},e.setLayout=function(t){if(t){var n=e.props.onLayout;n&&n(t.clientHeight);var r=e.createOnScroll();t.onscroll=function(e){r({client:t.clientHeight,full:e.currentTarget.clientHeight,top:e.currentTarget.scrollTop})}}},e.setPanel=function(t){e.panel=t},e.touchHandler=function(){var t=0,n=0,r=t;return{onTouchStart:function(e){n=e.touches[0].screenY,r=t},onTouchMove:function(t){var o=t.currentTarget,a=0===o.scrollTop;a&&(r=t.touches[0].screenY-n,r>0?(t.preventDefault(),r>80&&(r=80)):r=0,e.setTransform(e.panel.style,"translate3d(0,"+r+"px,0)"))},onTouchEnd:function(){e.touchHandler.onFinish()},onTouchCancel:function(){e.touchHandler.onFinish()},onFinish:function(){r>40&&e.canLoadPrev()&&(e.genMonthData(e.state.months[0].firstDate,-1),e.visibleMonth=e.state.months.slice(0,e.props.initalMonths),e.state.months.forEach(function(e){e.updateLayout&&e.updateLayout()}),e.forceUpdate()),e.setTransform(e.panel.style,"translate3d(0,0,0)"),e.setTransition(e.panel.style,".3s"),setTimeout(function(){e.setTransition(e.panel.style,"")},300)}}}(),e}return(0,d.default)(t,e),(0,u.default)(t,[{key:"setTransform",value:function(e,t){this.transform=t,e.transform=t,e.webkitTransform=t}},{key:"setTransition",value:function(e,t){e.transition=t,e.webkitTransition=t}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=void 0===n?"":n,o=t.locale,a=void 0===o?{}:o,i={transform:this.transform};return h.createElement("div",{className:r+" date-picker"},h.createElement(y.default,null),h.createElement("div",{className:"wrapper",style:{overflowX:"hidden",overflowY:"visible"},ref:this.setLayout,onTouchStart:this.touchHandler.onTouchStart,onTouchMove:this.touchHandler.onTouchMove,onTouchEnd:this.touchHandler.onTouchEnd,onTouchCancel:this.touchHandler.onTouchCancel},h.createElement("div",{style:i,ref:this.setPanel},this.canLoadPrev()&&h.createElement("div",{className:"load-tip"},a.loadPrevMonth),h.createElement("div",{className:"months"},this.state.months.map(function(t){var n=t.height&&e.visibleMonth.indexOf(t)<0;return n?h.createElement("div",{key:t.title+"_shallow",style:{height:t.height}}):t.component})))))}}]),t}(m.default);t.default=C,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=t.Models=void 0;!function(e){var t=void 0;!function(e){e[e.None=0]="None",e[e.Single=1]="Single",e[e.All=2]="All",e[e.Only=3]="Only",e[e.Start=4]="Start",e[e.Middle=5]="Middle",e[e.End=6]="End"}(t=e.SelectType||(e.SelectType={}))}(n||(t.Models=n={}))},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(79),g=r(m),y=n(46),b=r(y),_=n(47),C=r(_),x=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={value:e.getValue(e.props.data,e.props.defaultValue||e.props.value)},e.onValueChange=function(t,n){var r=(0,g.default)(e.props.data,function(e,r){return r<=n&&e.value===t[r]}),o=r[n],a=void 0;for(a=n+1;o&&o.children&&o.children.length&&a<e.props.cols;a++)o=o.children[0],t[a]=o.value;t.length=a,"value"in e.props||e.setState({value:t}),e.props.onChange&&e.props.onChange(t)},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:this.getValue(e.data,e.value)})}},{key:"getValue",value:function(e,t){var n=e||this.props.data,r=t||this.props.value||this.props.defaultValue;if(!r||!r.length){r=[];for(var o=0;o<this.props.cols;o++)n&&n.length&&(r[o]=n[0].value,n=n[0].children)}return r}},{key:"getCols",value:function(){var e=this.props,t=e.data,n=e.cols,r=e.pickerPrefixCls,o=e.disabled,a=e.pickerItemStyle,i=e.indicatorStyle,l=this.state.value,u=(0,g.default)(t,function(e,t){return e.value===l[t]}).map(function(e){return e.children}),s=n-u.length;if(s>0)for(var c=0;c<s;c++)u.push([]);return u.length=n-1,u.unshift(t),u.map(function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments[1];return v.default.createElement(C.default,{key:t,prefixCls:r,style:{flex:1},disabled:o,itemStyle:a,indicatorStyle:i},e.map(function(e){return v.default.createElement(C.default.Item,{value:e.value,key:e.value},e.label)}))})}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.rootNativeProps,o=e.style,i=this.getCols(),l=(0,a.default)({flexDirection:"row",alignItems:"center"},o);return v.default.createElement(b.default,{style:l,prefixCls:t,className:n,selectedValue:this.state.value,rootNativeProps:r,onValueChange:this.onValueChange,onScrollChange:e.onScrollChange},i)}}]),t}(v.default.Component);x.defaultProps={cols:3,prefixCls:"rmc-cascader",pickerPrefixCls:"rmc-picker",data:[],disabled:!1},t.default=x,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={year:"\u5e74",month:"\u6708",day:"\u65e5",hour:"\u65f6",minute:"\u5206",am:"\u4e0a\u5348",pm:"\u4e0b\u5348"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(22),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(10),b=r(y),_=n(11),C=r(_),x=n(414),S=r(x),O=n(416),k=r(O),w=1,P=10,T=1e3,E=1e3,M=50,N=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"shouldComponentUpdate",value:function(e){return e.shouldUpdate}},{key:"render",value:function(){return this.props.render()}}]),t}(g.default.Component),j=function(e){function t(){var e,n,r,o;(0,s.default)(this,t);for(var a=arguments.length,i=Array(a),l=0;l<a;l++)i[l]=arguments[l];return n=r=(0,p.default)(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(i))),D.call(r),o=n,(0,p.default)(r,o)}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentWillMount",value:function(){this.scrollProperties={visibleLength:null,contentLength:null,offset:0},this._childFrames=[],this._visibleRows={},this._prevRenderedRowsCount=0,this._sentEndForContentLength=null}},{key:"componentWillReceiveProps",value:function(e){var t=this;this.props.dataSource===e.dataSource&&this.props.initialListSize===e.initialListSize||this.setState(function(n,r){return t._prevRenderedRowsCount=0,{curRenderedRowsCount:Math.min(Math.max(n.curRenderedRowsCount,e.initialListSize),e.dataSource.getRowCount())}},function(){return t._renderMoreRowsIfNeeded()})}},{key:"render",value:function(){for(var e=this,t=this.props.dataSource,n=t.rowIdentities,r=[],o=0,i=0;i<n.length;i++){var u=t.sectionIdentities[i],s=n[i];if(0!==s.length){var c=void 0;if(this.props.renderSectionHeader){var f=o>=this._prevRenderedRowsCount&&t.sectionHeaderShouldUpdate(i);c=g.default.createElement(N,{key:"s_"+u,shouldUpdate:!!f,render:this.props.renderSectionHeader.bind(null,t.getSectionHeaderData(i),u)})}for(var d=[],p=0;p<s.length;p++){var h=s[p],v=u+"_"+h,m=o>=this._prevRenderedRowsCount&&t.rowShouldUpdate(i,p),y=g.default.createElement(N,{key:"r_"+v,shouldUpdate:!!m,render:this.props.renderRow.bind(null,t.getRowData(i,p),u,h,this.onRowHighlighted)});if(d.push(y),this.props.renderSeparator&&(p!==s.length-1||i===n.length-1)){var b=this.state.highlightedRow.sectionID===u&&(this.state.highlightedRow.rowID===h||this.state.highlightedRow.rowID===s[p+1]),_=this.props.renderSeparator(u,h,b);_&&d.push(_)}if(++o===this.state.curRenderedRowsCount)break}var C=g.default.cloneElement(this.props.renderSectionBodyWrapper(u),{className:this.props.sectionBodyClassName},d);if(this.props.renderSectionWrapper?r.push(g.default.cloneElement(this.props.renderSectionWrapper(u),{},c,C)):(r.push(c),r.push(C)),o>=this.state.curRenderedRowsCount)break}}var x=this.props,S=x.renderScrollComponent,O=(0,l.default)(x,["renderScrollComponent"]);return this._sc=g.default.cloneElement(S((0,a.default)({},O,{onScroll:this._onScroll})),{ref:function(t){return e.ListViewRef=t},onContentSizeChange:this._onContentSizeChange,onLayout:this._onLayout},this.props.renderHeader?this.props.renderHeader():null,g.default.cloneElement(O.renderBodyComponent(),{},r),this.props.renderFooter?this.props.renderFooter():null,O.children),this._sc}}]),t}(g.default.Component);j.DataSource=S.default,j.propTypes=(0,a.default)({},k.default.propTypes,{dataSource:b.default.instanceOf(S.default).isRequired,renderSeparator:b.default.func,renderRow:b.default.func.isRequired,initialListSize:b.default.number,onEndReached:b.default.func,onEndReachedThreshold:b.default.number,pageSize:b.default.number,renderFooter:b.default.func,renderHeader:b.default.func,renderSectionHeader:b.default.func,renderScrollComponent:b.default.func,scrollRenderAheadDistance:b.default.number,onChangeVisibleRows:b.default.func,scrollEventThrottle:b.default.number,renderBodyComponent:b.default.func,renderSectionWrapper:b.default.func,renderSectionBodyWrapper:b.default.func,sectionBodyClassName:b.default.string,listViewPrefixCls:b.default.string,useZscroller:b.default.bool,useBodyScroll:b.default.bool,pullUpEnabled:b.default.bool,pullUpRefreshing:b.default.bool,pullUpOnRefresh:b.default.func,pullUpDistanceToRefresh:b.default.number,pullUpRenderer:b.default.func}),j.defaultProps={initialListSize:P,pageSize:w,renderScrollComponent:function(e){return g.default.createElement(k.default,e)},renderBodyComponent:function(){return g.default.createElement("div",null)},renderSectionBodyWrapper:function(e){return g.default.createElement("div",{key:e})},sectionBodyClassName:"list-view-section-body",listViewPrefixCls:"rmc-list-view",scrollRenderAheadDistance:T,onEndReachedThreshold:E,scrollEventThrottle:M,scrollerOptions:{},pullUpEnabled:!1,pullUpRefreshing:!1,pullUpOnRefresh:function(){},pullUpDistanceToRefresh:25};var D=function(){var e=this;this.state={curRenderedRowsCount:this.props.initialListSize,highlightedRow:{}},this.getMetrics=function(){return{contentLength:e.scrollProperties.contentLength,totalRows:e.props.dataSource.getRowCount(),renderedRows:e.state.curRenderedRowsCount,visibleRows:Object.keys(e._visibleRows).length}},this.scrollTo=function(){var t;e.ListViewRef&&e.ListViewRef.scrollTo&&(t=e.ListViewRef).scrollTo.apply(t,arguments)},this.getInnerViewNode=function(){return e.ListViewRef.getInnerViewNode()},this.onRowHighlighted=function(t,n){e.setState({highlightedRow:{sectionID:t,rowID:n}})},this._onContentSizeChange=function(t,n){var r=e.props.horizontal?t:n;r!==e.scrollProperties.contentLength&&(e.scrollProperties.contentLength=r,e._renderMoreRowsIfNeeded()),e.props.onContentSizeChange&&e.props.onContentSizeChange(t,n)},this._onLayout=function(t){var n=t.nativeEvent.layout,r=n.width,o=n.height,a=e.props.horizontal?r:o;a!==e.scrollProperties.visibleLength&&(e.scrollProperties.visibleLength=a,e._renderMoreRowsIfNeeded()),e.props.onLayout&&e.props.onLayout(t)},this._maybeCallOnEndReached=function(t){return!!(e.props.onEndReached&&e.scrollProperties.contentLength!==e._sentEndForContentLength&&e._getDistanceFromEnd(e.scrollProperties)<e.props.onEndReachedThreshold&&e.state.curRenderedRowsCount===e.props.dataSource.getRowCount())&&(e._sentEndForContentLength=e.scrollProperties.contentLength,e.props.onEndReached(t),!0)},this._renderMoreRowsIfNeeded=function(){if(null===e.scrollProperties.contentLength||null===e.scrollProperties.visibleLength||e.state.curRenderedRowsCount===e.props.dataSource.getRowCount())return void e._maybeCallOnEndReached();var t=e._getDistanceFromEnd(e.scrollProperties);t<e.props.scrollRenderAheadDistance&&e._pageInNewRows()},this._pageInNewRows=function(){e.setState(function(t,n){var r=Math.min(t.curRenderedRowsCount+n.pageSize,n.dataSource.getRowCount());return e._prevRenderedRowsCount=t.curRenderedRowsCount,{curRenderedRowsCount:r}},function(){e._prevRenderedRowsCount=e.state.curRenderedRowsCount})},this._getDistanceFromEnd=function(e){return e.contentLength-e.visibleLength-e.offset},this._onScroll=function(t){var n=!e.props.horizontal,r=t;if(e.ListViewRef){var o=C.default.findDOMNode(e.ListViewRef);if(e.props.useBodyScroll){e.scrollProperties.visibleLength=window[n?"innerHeight":"innerWidth"],e.scrollProperties.contentLength=o[n?"scrollHeight":"scrollWidth"];var a=document.scrollingElement?document.scrollingElement:document.body;e.scrollProperties.offset=a[n?"scrollTop":"scrollLeft"]}else if(e.props.useZscroller){var i=e.ListViewRef.domScroller;r=i,e.scrollProperties.visibleLength=i.container[n?"clientHeight":"clientWidth"],e.scrollProperties.contentLength=i.content[n?"offsetHeight":"offsetWidth"],e.scrollProperties.offset=i.scroller.getValues()[n?"top":"left"]}else e.scrollProperties.visibleLength=o[n?"offsetHeight":"offsetWidth"],e.scrollProperties.contentLength=o[n?"scrollHeight":"scrollWidth"],e.scrollProperties.offset=o[n?"scrollTop":"scrollLeft"];e._maybeCallOnEndReached(r)||e._renderMoreRowsIfNeeded(),e.props.onEndReached&&e._getDistanceFromEnd(e.scrollProperties)>e.props.onEndReachedThreshold&&(e._sentEndForContentLength=null),e.props.onScroll&&e.props.onScroll(r)}}};t.default=j,e.exports=t.default},function(e,t){"use strict";function n(e){var t=0;do isNaN(e.offsetTop)||(t+=e.offsetTop);while(e=e.offsetParent);return t}function r(e){return e.touches&&e.touches.length?e.touches[0]:e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e}function o(e,t){var n=!0,r=!0;return function(o){n&&(n=!1,setTimeout(function(){n=!0,e(o)},t),r&&(e(o),r=!1))}}function a(e,t){e.transform=t,e.webkitTransform=t,e.MozTransform=t}function i(e,t){e.transformOrigin=t,e.webkitTransformOrigin=t,e.MozTransformOrigin=t}Object.defineProperty(t,"__esModule",{value:!0}),t.getOffsetTop=n,t._event=r,t.throttle=o,t.setTransform=a,t.setTransformOrigin=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(76),l=r(i),u=n(422),s=r(u),c=n(12),f=r(c),d=function(e,t,n){var r=n.getContent,o=n.hide,i=n.onDismiss,u=n.onOk;if(!t)return null;var s=e.prefixCls;return a.default.createElement(l.default,{prefixCls:""+s,className:e.className||"",visible:!0,closable:!1,transitionName:e.transitionName||e.popupTransitionName,maskTransitionName:e.maskTransitionName,onClose:o,style:e.style},a.default.createElement("div",null,a.default.createElement("div",{className:s+"-header"},a.default.createElement(f.default,{activeClassName:s+"-item-active"},a.default.createElement("div",{className:s+"-item "+s+"-header-left",onClick:i},e.dismissText)),a.default.createElement("div",{className:s+"-item "+s+"-title"},e.title),a.default.createElement(f.default,{activeClassName:s+"-item-active"},a.default.createElement("div",{className:s+"-item "+s+"-header-right",onClick:u},e.okText))),r()))};t.default=(0,s.default)(d,{prefixCls:"rmc-picker-popup",WrapComponent:"span",triggerType:"onClick",pickerValueProp:"selectedValue",pickerValueChangeProp:"onValueChange"}),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultTabBar=t.StateType=void 0;var o=n(6),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(2),p=r(d),h=n(1),v=r(h),m=n(71),g=r(m),y=n(78),b=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},_=t.StateType=function e(){(0,p.default)(this,e),this.transform="",this.isMoving=!1,this.showPrev=!1,this.showNext=!1},C=t.DefaultTabBar=function(e){function t(e){(0,p.default)(this,t);var n=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onPan=function(){var e=0,t=0,r=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.isTabBarVertical(),r=+(""+e).replace("%","");return(""+e).indexOf("%")>=0&&(r/=100,r*=t?n.layout.clientHeight:n.layout.clientWidth),
r};return{onPanStart:function(){n.setState({isMoving:!0})},onPanMove:function(e){if(e.moveStatus&&n.layout){var o=n.isTabBarVertical(),a=r()+(o?e.moveStatus.y:e.moveStatus.x),i=o?-n.layout.scrollHeight+n.layout.clientHeight:-n.layout.scrollWidth+n.layout.clientWidth;a=Math.min(a,0),a=Math.max(a,i),(0,y.setPxStyle)(n.layout,a,"px",o),t=a,n.setState({showPrev:-a>0,showNext:a>i})}},onPanEnd:function(){var r=n.isTabBarVertical();e=t,n.setState({isMoving:!1,transform:(0,y.getPxStyle)(t,"px",r)})},setCurrentOffset:function(t){return e=t}}}(),n.getTransformByIndex=function(e){var t=e.activeTab,r=e.tabs,o=e.page,a=void 0===o?0:o,i=n.isTabBarVertical(),l=n.getTabSize(a,r.length),u=a/2,s=Math.min(t,r.length-u-.5),c=Math.min(-(s-u+.5)*l,0);return n.onPan.setCurrentOffset(c+"%"),{transform:(0,y.getPxStyle)(c,"%",i),showPrev:t>2&&r.length>a,showNext:t<r.length-3&&r.length>a}},n.onPress=function(e){var t=n.props,r=t.goToTab,o=t.onTabClick,a=t.tabs;o&&o(a[e],e),r&&r(e)},n.isTabBarVertical=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.props.tabBarPosition;return"left"===e||"right"===e},n.renderTab=function(e,t,r,o){var i=n.props,l=i.prefixCls,u=i.renderTab,s=i.activeTab,c=i.tabBarTextStyle,f=i.tabBarActiveTextColor,d=i.tabBarInactiveTextColor,p=(0,a.default)({},c),h=l+"-tab";return s===t?(h+=" "+h+"-active",f&&(p.color=f)):d&&(p.color=d),v.default.createElement("div",{key:"t_"+t,style:(0,a.default)({},p,o?{height:r+"%"}:{width:r+"%"}),className:h,onClick:function(){return n.onPress(t)}},u?u(e):e.title)},n.setContentLayout=function(e){n.layout=e},n.getTabSize=function(e,t){return 100/Math.min(e,t)},n.state=(0,a.default)({},new _,n.getTransformByIndex(e)),n}return(0,f.default)(t,e),(0,l.default)(t,[{key:"componentWillReceiveProps",value:function(e){this.props.activeTab!==e.activeTab&&this.setState((0,a.default)({},this.getTransformByIndex(e)))}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.animated,o=t.tabs,i=void 0===o?[]:o,l=t.page,u=void 0===l?0:l,s=t.activeTab,c=void 0===s?0:s,f=t.tabBarBackgroundColor,d=t.tabBarUnderlineStyle,p=t.tabBarPosition,h=this.state,m=h.isMoving,_=h.transform,C=h.showNext,x=h.showPrev,S=this.isTabBarVertical(),O=i.length>u,k=this.getTabSize(u,i.length),w=i.map(function(t,n){return e.renderTab(t,n,k,S)}),P=n;r&&!m&&(P+=" "+n+"-animated");var T={backgroundColor:f||""},E=O?(0,a.default)({},(0,y.getTransformPropValue)(_)):{},M=this.onPan,N=(M.setCurrentOffset,b(M,["setCurrentOffset"]));return v.default.createElement("div",{className:P+" "+n+"-"+p,style:T},x&&v.default.createElement("div",{className:n+"-prevpage"}),v.default.createElement(g.default,(0,a.default)({},N,{direction:S?"vertical":"horizontal"}),v.default.createElement("div",{className:n+"-content",style:E,ref:this.setContentLayout},w,v.default.createElement("div",{style:(0,a.default)({},d,S?{height:k+"%"}:{width:k+"%"},S?{top:k*c+"%"}:{left:k*c+"%"}),className:n+"-underline"}))),C&&v.default.createElement("div",{className:n+"-nextpage"}))}}]),t}(v.default.PureComponent);C.defaultProps={prefixCls:"rmc-tabs-tab-bar",animated:!0,tabs:[],goToTab:function(){},activeTab:0,page:5,tabBarUnderlineStyle:{},tabBarBackgroundColor:"#fff",tabBarActiveTextColor:"",tabBarInactiveTextColor:"",tabBarTextStyle:{}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},v=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"shouldComponentUpdate",value:function(e){return e.hiddenClassName||e.visible}},{key:"render",value:function(){var e=this.props,t=e.hiddenClassName,n=e.visible,r=h(e,["hiddenClassName","visible"]);return t||p.default.Children.count(r.children)>1?(!n&&t&&(r.className+=" "+t),p.default.createElement("div",r)):p.default.Children.only(r.children)}}]),t}(d.Component);t.default=v,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return e[0]===t[0]&&e[1]===t[1]}function a(e,t,n){var r=e[t]||{};return(0,s.default)({},r,n)}function i(e,t,n){var r=n.points;for(var a in e)if(e.hasOwnProperty(a)&&o(e[a].points,r))return t+"-placement-"+a;return""}function l(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var u=n(6),s=r(u);t.getAlignFromPlacement=a,t.getPopupClassNameFromAlign=i,t.saveRef=l},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){e.transform=t,e.webkitTransform=t,e.MozTransform=t}function a(e,t){e.transformOrigin=t,e.webkitTransformOrigin=t,e.MozTransformOrigin=t}function i(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=void 0,i=void 0,l=void 0,s=void 0,d=void 0,p=void 0,h=void 0,v=void 0;this.content=e,this.container=e.parentNode,this.options=(0,u.default)({},n,{scrollingComplete:function(){t.clearScrollbarTimer(),t.timer=setTimeout(function(){t._destroyed||(n.scrollingComplete&&n.scrollingComplete(),r&&["x","y"].forEach(function(e){r[e]&&t.setScrollbarOpacity(e,0)}))},0)}}),this.options.scrollbars&&(r=this.scrollbars={},i=this.indicators={},l=this.indicatorsSize={},s=this.scrollbarsSize={},d=this.indicatorsPos={},p=this.scrollbarsOpacity={},h=this.contentSize={},v=this.clientSize={},["x","y"].forEach(function(e){var n="x"===e?"scrollingX":"scrollingY";t.options[n]!==!1&&(r[e]=document.createElement("div"),r[e].className="zscroller-scrollbar-"+e,i[e]=document.createElement("div"),i[e].className="zscroller-indicator-"+e,r[e].appendChild(i[e]),l[e]=-1,p[e]=0,d[e]=0,t.container.appendChild(r[e]))}));var m=!0,g=e.style;this.scroller=new c.default(function(e,a,i){!m&&n.onScroll&&n.onScroll(),o(g,"translate3d("+-e+"px,"+-a+"px,0) scale("+i+")"),r&&["x","y"].forEach(function(n){if(r[n]){var o="x"===n?e:a;if(v[n]>=h[n])t.setScrollbarOpacity(n,0);else{m||t.setScrollbarOpacity(n,1);var i=v[n]/h[n]*s[n],l=i,u=void 0;o<0?(l=Math.max(i+o,f),u=0):o>h[n]-v[n]?(l=Math.max(i+h[n]-v[n]-o,f),u=s[n]-l):u=o/h[n]*s[n],t.setIndicatorSize(n,l),t.setIndicatorPos(n,u)}}}),m=!1},this.options),this.bindEvents(),a(e.style,"left top"),this.reflow()}Object.defineProperty(t,"__esModule",{value:!0});var l=n(6),u=r(l),s=n(440),c=r(s),f=8;i.prototype.setDisabled=function(e){this.disabled=e},i.prototype.clearScrollbarTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},i.prototype.setScrollbarOpacity=function(e,t){this.scrollbarsOpacity[e]!==t&&(this.scrollbars[e].style.opacity=t,this.scrollbarsOpacity[e]=t)},i.prototype.setIndicatorPos=function(e,t){this.indicatorsPos[e]!==t&&("x"===e?o(this.indicators[e].style,"translate3d("+t+"px,0,0)"):o(this.indicators[e].style,"translate3d(0, "+t+"px,0)"),this.indicatorsPos[e]=t)},i.prototype.setIndicatorSize=function(e,t){this.indicatorsSize[e]!==t&&(this.indicators[e].style["x"===e?"width":"height"]=t+"px",this.indicatorsSize[e]=t)},i.prototype.reflow=function(){this.scrollbars&&(this.contentSize.x=this.content.offsetWidth,this.contentSize.y=this.content.offsetHeight,this.clientSize.x=this.container.clientWidth,this.clientSize.y=this.container.clientHeight,this.scrollbars.x&&(this.scrollbarsSize.x=this.scrollbars.x.offsetWidth),this.scrollbars.y&&(this.scrollbarsSize.y=this.scrollbars.y.offsetHeight)),this.scroller.setDimensions(this.container.clientWidth,this.container.clientHeight,this.content.offsetWidth,this.content.offsetHeight);var e=this.container.getBoundingClientRect();this.scroller.setPosition(e.x+this.container.clientLeft,e.y+this.container.clientTop)},i.prototype.destroy=function(){this._destroyed=!0,window.removeEventListener("resize",this.onResize,!1),this.container.removeEventListener("touchstart",this.onTouchStart,!1),this.container.removeEventListener("touchmove",this.onTouchMove,!1),this.container.removeEventListener("touchend",this.onTouchEnd,!1),this.container.removeEventListener("touchcancel",this.onTouchCancel,!1),this.container.removeEventListener("mousedown",this.onMouseDown,!1),document.removeEventListener("mousemove",this.onMouseMove,!1),document.removeEventListener("mouseup",this.onMouseUp,!1),this.container.removeEventListener("mousewheel",this.onMouseWheel,!1)},i.prototype.bindEvents=function(){var e=this,t=this;window.addEventListener("resize",this.onResize=function(){t.reflow()},!1);var n=!1,r=void 0;this.container.addEventListener("touchstart",this.onTouchStart=function(o){n=!0,r&&(clearTimeout(r),r=null),o.touches[0]&&o.touches[0].target&&o.touches[0].target.tagName.match(/input|textarea|select/i)||e.disabled||(e.clearScrollbarTimer(),t.reflow(),t.scroller.doTouchStart(o.touches,o.timeStamp))},!1),this.container.addEventListener("touchmove",this.onTouchMove=function(n){e.options.preventDefaultOnTouchMove!==!1&&n.preventDefault(),t.scroller.doTouchMove(n.touches,n.timeStamp,n.scale)},!1),this.container.addEventListener("touchend",this.onTouchEnd=function(e){t.scroller.doTouchEnd(e.timeStamp),r=setTimeout(function(){n=!1},300)},!1),this.container.addEventListener("touchcancel",this.onTouchCancel=function(e){t.scroller.doTouchEnd(e.timeStamp),r=setTimeout(function(){n=!1},300)},!1),this.onMouseUp=function(n){t.scroller.doTouchEnd(n.timeStamp),document.removeEventListener("mousemove",e.onMouseMove,!1),document.removeEventListener("mouseup",e.onMouseUp,!1)},this.onMouseMove=function(e){t.scroller.doTouchMove([{pageX:e.pageX,pageY:e.pageY}],e.timeStamp)},this.container.addEventListener("mousedown",this.onMouseDown=function(r){n||r.target.tagName.match(/input|textarea|select/i)||e.disabled||(e.clearScrollbarTimer(),t.scroller.doTouchStart([{pageX:r.pageX,pageY:r.pageY}],r.timeStamp),t.reflow(),r.preventDefault(),document.addEventListener("mousemove",e.onMouseMove,!1),document.addEventListener("mouseup",e.onMouseUp,!1))},!1),this.container.addEventListener("mousewheel",this.onMouseWheel=function(e){t.options.zooming&&(t.scroller.doMouseZoom(e.wheelDelta,e.timeStamp,e.pageX,e.pageY),e.preventDefault())},!1)},t.default=i,e.exports=t.default},function(e,t,n){function r(e){return n(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./accordion/style/index.tsx":135,"./action-sheet/style/index.tsx":137,"./activity-indicator/style/index.tsx":139,"./badge/style/index.tsx":81,"./button/style/index.tsx":50,"./calendar/style/index.tsx":142,"./card/style/index.tsx":147,"./carousel/style/index.tsx":83,"./checkbox/style/index.tsx":84,"./date-picker-view/style/index.tsx":154,"./date-picker/style/index.tsx":157,"./drawer/style/index.tsx":160,"./flex/style/index.tsx":34,"./grid/style/index.tsx":164,"./icon/style/index.tsx":15,"./image-picker/style/index.tsx":167,"./input-item/style/index.tsx":174,"./list-view/style/index.tsx":177,"./list/style/index.tsx":21,"./locale-provider/style/index.tsx":181,"./menu/style/index.tsx":184,"./modal/style/index.tsx":190,"./nav-bar/style/index.tsx":192,"./notice-bar/style/index.tsx":195,"./pagination/style/index.tsx":198,"./picker-view/style/index.tsx":52,"./picker/style/index.tsx":53,"./popover/style/index.tsx":206,"./progress/style/index.tsx":208,"./radio/style/index.tsx":86,"./range/style/index.tsx":212,"./refresh-control/style/index.tsx":214,"./result/style/index.tsx":216,"./search-bar/style/index.tsx":219,"./segmented-control/style/index.tsx":221,"./slider/style/index.tsx":223,"./stepper/style/index.tsx":225,"./steps/style/index.tsx":227,"./swipe-action/style/index.tsx":229,"./switch/style/index.tsx":231,"./tab-bar/style/index.tsx":234,"./tabs/style/index.tsx":88,"./tag/style/index.tsx":236,"./text/style/index.tsx":238,"./textarea-item/style/index.tsx":240,"./toast/style/index.tsx":90,"./view/style/index.tsx":241,"./white-space/style/index.tsx":243,"./wing-blank/style/index.tsx":93};r.keys=function(){return Object.keys(a)},r.resolve=o,e.exports=r,r.id=127},function(e,t){"use strict";function n(){return!1}function r(){return!0}function o(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),o.prototype={isEventObject:1,constructor:o,isDefaultPrevented:n,isPropagationStopped:n,isImmediatePropagationStopped:n,preventDefault:function(){this.isDefaultPrevented=r},stopPropagation:function(){this.isPropagationStopped=r},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=r,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t.default=o,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return null===e||void 0===e}function a(){return d}function i(){return p}function l(e){var t=e.type,n="function"==typeof e.stopPropagation||"boolean"==typeof e.cancelBubble;s.default.call(this),this.nativeEvent=e;var r=i;"defaultPrevented"in e?r=e.defaultPrevented?a:i:"getPreventDefault"in e?r=e.getPreventDefault()?a:i:"returnValue"in e&&(r=e.returnValue===p?a:i),this.isDefaultPrevented=r;var o=[],l=void 0,u=void 0,c=void 0,f=h.concat();for(v.forEach(function(e){t.match(e.reg)&&(f=f.concat(e.props),e.fix&&o.push(e.fix))}),u=f.length;u;)c=f[--u],this[c]=e[c];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),u=o.length;u;)(l=o[--u])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var u=n(128),s=r(u),c=n(359),f=r(c),d=!0,p=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],v=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){o(e.which)&&(e.which=o(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,r=void 0,o=void 0,a=t.wheelDelta,i=t.axis,l=t.wheelDeltaY,u=t.wheelDeltaX,s=t.detail;a&&(o=a/120),s&&(o=0-(s%3===0?s/3:s)),void 0!==i&&(i===e.HORIZONTAL_AXIS?(r=0,n=0-o):i===e.VERTICAL_AXIS&&(n=0,r=o)),void 0!==l&&(r=l/120),void 0!==u&&(n=-1*u/120),n||r||(r=o),void 0!==n&&(e.deltaX=n),void 0!==r&&(e.deltaY=r),void 0!==o&&(e.delta=o)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,r=void 0,a=void 0,i=e.target,l=t.button;return i&&o(e.pageX)&&!o(t.clientX)&&(n=i.ownerDocument||document,r=n.documentElement,a=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||a&&a.scrollLeft||0)-(r&&r.clientLeft||a&&a.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||a&&a.scrollTop||0)-(r&&r.clientTop||a&&a.clientTop||0)),e.which||void 0===l||(1&l?e.which=1:2&l?e.which=3:4&l?e.which=2:e.which=0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===i?e.toElement:e.fromElement),e}}],m=s.default.prototype;(0,f.default)(l.prototype,m,{constructor:l,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=p,m.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=d,m.stopPropagation.call(this)}}),t.default=l,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){function r(t){var r=new i.default(t);n.call(e,r)}return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(129),i=r(a);e.exports=t.default},function(e,t,n){"use strict";var r=n(127);r.keys().forEach(function(e){r(e)}),e.exports=n(168)},function(e,t){"use strict";function n(e,t){if(e.classList)return e.classList.contains(t);var n=e.className;return(" "+n+" ").indexOf(" "+t+" ")>-1}function r(e,t){e.classList?e.classList.add(t):n(e,t)||(e.className=e.className+" "+t)}function o(e,t){if(e.classList)e.classList.remove(t);else if(n(e,t)){var r=e.className;e.className=(" "+r+" ").replace(" "+t+" ","")}}Object.defineProperty(t,"__esModule",{value:!0}),t.hasClass=n,t.addClass=r,t.removeClass=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var o=n(35);r(o)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(370),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement(v.default,this.props)}}]),t}(p.default.Component);t.default=m,m.Panel=h.Panel,m.defaultProps={prefixCls:"am-accordion"},e.exports=t.default},[441,306],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(e,t,n){function r(){if(y){p.default.unmountComponentAtNode(y),y.parentNode.removeChild(y),y=null;var e=w.indexOf(r);e!==-1&&w.splice(e,1)}}function o(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,o=n(e,t);o&&o.then?o.then(function(){r()}):r()}var a=(0,s.default)({prefixCls:"am-action-sheet",cancelButtonText:"\u53d6\u6d88"},t),i=a.prefixCls,u=a.className,c=a.transitionName,d=a.maskTransitionName,h=a.maskClosable,m=void 0===h||h,y=document.createElement("div");document.body.appendChild(y),w.push(r);var _=a.title,x=a.message,P=a.options,T=a.destructiveButtonIndex,E=a.cancelButtonIndex,M=a.cancelButtonText,N=[_?f.default.createElement("h3",{key:"0",className:i+"-title"},_):null,x?f.default.createElement("div",{key:"1",className:i+"-message"},x):null],j=null,D="normal";switch(e){case O:D="normal",j=f.default.createElement("div",(0,C.default)(a),N,f.default.createElement("div",{className:i+"-button-list",role:"group"},P.map(function(e,t){var n,r={className:(0,g.default)(i+"-button-list-item",(n={},(0,l.default)(n,i+"-destructive-button",T===t),(0,l.default)(n,i+"-cancel-button",E===t),n)),onClick:function(){return o(t)},role:"button"},a=f.default.createElement(S.default,{key:t,activeClassName:i+"-button-list-item-active"},f.default.createElement("div",r,e));return E!==t&&T!==t||(a=f.default.createElement(S.default,{key:t,activeClassName:i+"-button-list-item-active"},f.default.createElement("div",r,e,E===t?f.default.createElement("span",{className:i+"-cancel-button-mask"}):null))),a})));break;case k:D="share";var L=P.length&&Array.isArray(P[0])||!1,R=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return f.default.createElement("div",{className:i+"-share-list-item",role:"button",key:t,onClick:function(){return o(t,n)}},f.default.createElement("div",{className:i+"-share-list-item-icon"},e.iconName?f.default.createElement(b.default,{type:e.iconName}):e.icon),f.default.createElement("div",{className:i+"-share-list-item-title"},e.title))};j=f.default.createElement("div",(0,C.default)(a),N,f.default.createElement("div",{className:i+"-share"},L?P.map(function(e,t){return f.default.createElement("div",{key:t,className:i+"-share-list"},e.map(function(e,n){return R(e,n,t)}))}):f.default.createElement("div",{className:i+"-share-list"},P.map(function(e,t){return R(e,t)})),f.default.createElement(S.default,{activeClassName:i+"-share-cancel-button-active"},f.default.createElement("div",{className:i+"-share-cancel-button",role:"button",onClick:function(){return o(-1)}},M))))}var I=(0,g.default)(i+"-"+D,u);return p.default.render(f.default.createElement(v.default,{visible:!0,title:"",footer:"",prefixCls:i,className:I,transitionName:c||"am-slide-up",maskTransitionName:d||"am-fade",onClose:function(){return o(E||-1)},maskClosable:m,wrapProps:a.wrapProps||{}},j),y),{close:r}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),l=r(i),u=n(6),s=r(u),c=n(1),f=r(c),d=n(11),p=r(d),h=n(76),v=r(h),m=n(7),g=r(m),y=n(14),b=r(y),_=n(31),C=r(_),x=n(12),S=r(x),O="NORMAL",k="SHARE",w=[];t.default={showActionSheetWithOptions:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o;a(O,e,t)},showShareActionSheetWithOptions:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:o;a(k,e,t)},close:function(){w.forEach(function(e){return e()})}},e.exports=t.default},[442,307],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.animating,i=t.toast,l=t.size,u=t.text,s=(0,g.default)(n,r,(e={},(0,a.default)(e,n+"-lg","large"===l),(0,a.default)(e,n+"-sm","small"===l),(0,a.default)(e,n+"-toast",!!i),e)),c=(0,g.default)(n+"-spinner",(0,a.default)({},n+"-spinner-lg",!!i||"large"===l));return o?i?v.default.createElement("div",{className:s},u?v.default.createElement("div",{className:n+"-content"},v.default.createElement("span",{className:c,"aria-hidden":"true"}),v.default.createElement("span",{className:n+"-toast"},u)):v.default.createElement("div",{className:n+"-content"},v.default.createElement("span",{className:c,"aria-label":"Loading"}))):u?v.default.createElement("div",{className:s},v.default.createElement("span",{className:c,"aria-hidden":"true"}),v.default.createElement("span",{className:n+"-tip"},u)):v.default.createElement("div",{className:s},v.default.createElement("span",{className:c,"aria-label":"loading"})):null}}]),t}(v.default.Component);t.default=y,y.defaultProps={prefixCls:"am-activity-indicator",animating:!0,size:"small",panelColor:"rgba(34,34,34,0.6)",toast:!1},e.exports=t.default},[441,308],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(14),g=r(m),y=n(10),b=r(y),_=n(401),C=n(32),x=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=this.context,r=(0,C.getComponentLocale)(e,t,"Calendar",function(){return n(141)}),o=_.Calendar.DefaultHeader;return v.default.createElement(_.Calendar,(0,a.default)({locale:r,renderHeader:function(e){return v.default.createElement(o,(0,a.default)({},e,{closeIcon:v.default.createElement(g.default,{type:"cross"})}))}},e))}}]),t}(v.default.Component);t.default=x,x.defaultProps={prefixCls:"am-calendar",timePickerPrefixCls:"am-picker",timePickerPickerPrefixCls:"am-picker-col"},x.contextTypes={antLocale:b.default.object},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(45),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";n(53),n(311)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},b=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=y(e,["prefixCls","className"]),o=(0,g.default)(t+"-body",n);return v.default.createElement("div",(0,a.default)({className:o},r))}}]),t}(v.default.Component);t.default=b,b.defaultProps={prefixCls:"am-card"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},b=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.content,r=e.className,o=e.extra,i=y(e,["prefixCls","content","className","extra"]),l=(0,g.default)(t+"-footer",r);return v.default.createElement("div",(0,a.default)({className:l},i),v.default.createElement("div",{className:t+"-footer-content"},n),o&&v.default.createElement("div",{className:t+"-footer-extra"},o))}}]),t}(v.default.Component);t.default=b,b.defaultProps={prefixCls:"am-card"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},b=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.title,o=e.thumb,i=e.thumbStyle,l=e.extra,u=y(e,["prefixCls","className","title","thumb","thumbStyle","extra"]),s=(0,g.default)(t+"-header",n);return v.default.createElement("div",(0,a.default)({className:s},u),v.default.createElement("div",{className:t+"-header-content"},"string"==typeof o?v.default.createElement("img",{style:i,src:o}):o,r),l?v.default.createElement("div",{className:t+"-header-extra"},l):null)}}]),t}(v.default.Component);t.default=b,b.defaultProps={prefixCls:"am-card",thumbStyle:{}},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(145),C=r(_),x=n(143),S=r(x),O=n(144),k=r(O),w=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},P=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.full,r=e.className,o=w(e,["prefixCls","full","className"]),i=(0,b.default)(t,r,(0,l.default)({},t+"-full",n));return g.default.createElement("div",(0,a.default)({className:i},o))}}]),t}(g.default.Component);t.default=P,P.defaultProps={prefixCls:"am-card",full:!1},P.Header=C.default,P.Body=S.default,P.Footer=k.default,e.exports=t.default},[441,312],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(51),b=r(y),_=n(31),C=r(_),x=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},S=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.style,n=x(e,["style"]),r=n.prefixCls,o=n.className,i=(0,g.default)(r+"-agree",o);return v.default.createElement("div",(0,a.default)({},(0,C.default)(n),{className:i,style:t}),v.default.createElement(b.default,(0,a.default)({},n,{className:r+"-agree-label"})))}}]),t}(v.default.Component);t.default=S,S.defaultProps={prefixCls:"am-checkbox"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(8),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v),g=n(1),y=r(g),b=n(7),_=r(b),C=n(26),x=r(C),S=n(51),O=r(S),k=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},w=x.default.Item,P=function(e){function t(){return(0,c.default)(this,t),(0,h.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,m.default)(t,e),(0,d.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.listPrefixCls,r=(t.onChange,t.disabled),a=t.checkboxProps,l=t.onClick,s=k(t,["listPrefixCls","onChange","disabled","checkboxProps","onClick"]),c=s.prefixCls,f=s.className,d=s.children,p=(0,_.default)(c+"-item",f,(0,u.default)({},c+"-item-disabled",r===!0));r||(s.onClick=l||o);var h={};return["name","defaultChecked","checked","onChange","disabled"].forEach(function(t){t in e.props&&(h[t]=e.props[t])}),y.default.createElement(w,(0,i.default)({},s,{prefixCls:n,className:p,thumb:y.default.createElement(O.default,(0,i.default)({},a,h))}),d)}}]),t}(y.default.Component);t.default=P,P.defaultProps={prefixCls:"am-checkbox",listPrefixCls:"am-list",checkboxProps:{}},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(51),a=r(o),i=n(149),l=r(i),u=n(148),s=r(u);a.default.CheckboxItem=l.default,a.default.AgreeItem=s.default,t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.defaultDate,n=e.minDate,r=e.maxDate;if(t)return t;var o=new Date;return n&&o<n?n:r&&r<o?n:o}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(2),u=r(l),s=n(5),c=r(s),f=n(4),d=r(f),p=n(3),h=r(p),v=n(1),m=r(v),g=n(10),y=r(g),b=n(75),_=r(b),C=n(32),x=function(e){function t(){return(0,u.default)(this,t),(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,h.default)(t,e),(0,c.default)(t,[{
key:"render",value:function(){var e=this.props,t=this.context,r=(0,C.getComponentLocale)(e,t,"DatePickerView",function(){return n(153)});return m.default.createElement(_.default,(0,i.default)({},e,{locale:r,date:e.value||o(this.props),onDateChange:e.onChange,onValueChange:e.onValueChange,onScrollChange:e.onScrollChange}))}}]),t}(m.default.Component);t.default=x,x.defaultProps={mode:"datetime",extra:"\u8bf7\u9009\u62e9",prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",minuteStep:1,use12Hours:!1},x.contextTypes={antLocale:y.default.object},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(151),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(119),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";n(52)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(10),g=r(m),y=n(404),b=r(y),_=n(75),C=r(_),x=n(158),S=n(32),O=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.setScrollValue=function(t){e.scrollValue=t},e.onOk=function(t){void 0!==e.scrollValue&&(t=e.scrollValue),e.props.onChange&&e.props.onChange(t),e.props.onOk&&e.props.onOk(t)},e.fixOnOk=function(t){t.onOk=e.onOk},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=this.context,r=e.children,o=e.value,i=e.extra,l=e.popupPrefixCls,u=(0,S.getComponentLocale)(e,t,"DatePicker",function(){return n(156)}),s=u.okText,c=u.dismissText,f=u.DatePickerLocale,d=v.default.createElement(C.default,{minuteStep:e.minuteStep,locale:f,minDate:e.minDate,maxDate:e.maxDate,mode:e.mode,pickerPrefixCls:e.pickerPrefixCls,prefixCls:e.prefixCls,defaultDate:o||(0,x.getDefaultDate)(this.props),use12Hours:e.use12Hours,onValueChange:e.onValueChange,onScrollChange:this.setScrollValue});return v.default.createElement(b.default,(0,a.default)({datePicker:d,WrapComponent:"div",transitionName:"am-slide-up",maskTransitionName:"am-fade"},e,{prefixCls:l,date:o||(0,x.getDefaultDate)(this.props),dismissText:c,okText:s,ref:this.fixOnOk}),r&&v.default.cloneElement(r,{extra:o?(0,x.formatFn)(this,o):i}))}}]),t}(v.default.Component);t.default=O,O.defaultProps={mode:"datetime",extra:"\u8bf7\u9009\u62e9",prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",popupPrefixCls:"am-picker-popup",minuteStep:1,use12Hours:!1},O.contextTypes={antLocale:g.default.object},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(119),a=r(o);t.default={okText:"\u786e\u5b9a",dismissText:"\u53d6\u6d88",DatePickerLocale:a.default},e.exports=t.default},function(e,t,n){"use strict";n(53)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n=function(e){return e<10?"0"+e:e},r=e.getFullYear()+"-"+n(e.getMonth()+1)+"-"+n(e.getDate()),o=n(e.getHours())+":"+n(e.getMinutes());return"YYYY-MM-DD"===t?r:"HH:mm"===t?o:r+" "+o}function a(e,t){var n={date:"YYYY-MM-DD",time:"HH:mm",datetime:"YYYY-MM-DD HH:mm"},r=e.props.format,a="undefined"==typeof r?"undefined":(0,u.default)(r);return"string"===a?o(t,r):"function"===a?r(t):o(t,n[e.props.mode])}function i(e){var t=e.defaultDate,n=e.minDate,r=e.maxDate;if(t)return t;var o=new Date;return n&&o<n?n:r&&r<o?n:o}Object.defineProperty(t,"__esModule",{value:!0});var l=n(17),u=r(l);t.formatFn=a,t.getDefaultDate=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(373),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement(v.default,this.props)}}]),t}(p.default.Component);t.default=m,m.defaultProps={prefixCls:"am-drawer",enableDragHandle:!1},e.exports=t.default},[441,315],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e,t=this.props,n=t.direction,r=t.wrap,o=t.justify,i=t.align,u=t.alignContent,s=t.className,c=t.children,f=t.prefixCls,d=t.style,p=_(t,["direction","wrap","justify","align","alignContent","className","children","prefixCls","style"]),h=(0,b.default)(f,s,(e={},(0,l.default)(e,f+"-dir-row","row"===n),(0,l.default)(e,f+"-dir-row-reverse","row-reverse"===n),(0,l.default)(e,f+"-dir-column","column"===n),(0,l.default)(e,f+"-dir-column-reverse","column-reverse"===n),(0,l.default)(e,f+"-nowrap","nowrap"===r),(0,l.default)(e,f+"-wrap","wrap"===r),(0,l.default)(e,f+"-wrap-reverse","wrap-reverse"===r),(0,l.default)(e,f+"-justify-start","start"===o),(0,l.default)(e,f+"-justify-end","end"===o),(0,l.default)(e,f+"-justify-center","center"===o),(0,l.default)(e,f+"-justify-between","between"===o),(0,l.default)(e,f+"-justify-around","around"===o),(0,l.default)(e,f+"-align-start","start"===i),(0,l.default)(e,f+"-align-center","center"===i),(0,l.default)(e,f+"-align-end","end"===i),(0,l.default)(e,f+"-align-baseline","baseline"===i),(0,l.default)(e,f+"-align-stretch","stretch"===i),(0,l.default)(e,f+"-align-content-start","start"===u),(0,l.default)(e,f+"-align-content-end","end"===u),(0,l.default)(e,f+"-align-content-center","center"===u),(0,l.default)(e,f+"-align-content-between","between"===u),(0,l.default)(e,f+"-align-content-around","around"===u),(0,l.default)(e,f+"-align-content-stretch","stretch"===u),e));return g.default.createElement("div",(0,a.default)({className:h,style:d},p),c)}}]),t}(g.default.Component);t.default=C,C.defaultProps={prefixCls:"am-flexbox",align:"center"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},b=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.children,n=e.className,r=e.prefixCls,o=e.style,i=y(e,["children","className","prefixCls","style"]),l=(0,g.default)(r+"-item",n);return v.default.createElement("div",(0,a.default)({className:l,style:o},i),t)}}]),t}(v.default.Component);t.default=b,b.defaultProps={prefixCls:"am-flexbox"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(6),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(33),C=r(_),x=n(82),S=r(x),O=n(12),k=r(O),w=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},P=function(e){function t(){(0,s.default)(this,t);var e=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={initialSlideWidth:0},e.renderCarousel=function(t,n,r){for(var o=e.props.prefixCls,a=e.props.carouselMaxRow,i=[],l=0;l<n;l++){for(var u=[],s=0;s<a;s++){var c=l*a+s;c<r?u.push(t[c]):u.push(g.default.createElement("div",{key:"gridline-"+c}))}i.push(g.default.createElement("div",{key:"pageitem-"+l,className:o+"-carousel-page"},u))}return i},e.renderItem=function(t,n,r,o){var a=e.props.prefixCls,i=null;if(o)i=o(t,n);else if(t){var l=t.icon,u=t.text;i=g.default.createElement("div",{className:a+"-item-inner-content column-num-"+r},g.default.isValidElement(l)?l:g.default.createElement("img",{className:a+"-icon",src:l}),g.default.createElement("div",{className:a+"-text"},u))}return g.default.createElement("div",{className:a+"-item-content"},i)},e.getRows=function(t,n){var r=e.props,o=r.columnNum,a=r.data,i=r.renderItem,l=r.prefixCls,u=r.onClick,s=r.activeStyle,c=r.activeClassName,f=[];o=o;for(var d=100/o+"%",p={width:d},h=0;h<t;h++){for(var v=[],m=function(t){var r=h*o+t,f=void 0;if(r<n){var d=a&&a[r];f=g.default.createElement(k.default,{key:"griditem-"+r,activeClassName:c?c:l+"-item-active",activeStyle:s},g.default.createElement(C.default.Item,{className:l+"-item",onClick:function(){return u&&u(d,r)},style:p},e.renderItem(d,r,o,i)))}else f=g.default.createElement(C.default.Item,{key:"griditem-"+r,className:l+"-item "+l+"-null-item",style:p});v.push(f)},y=0;y<o;y++)m(y);f.push(g.default.createElement(C.default,{justify:"center",align:"stretch",key:"gridline-"+h},v))}return f},e}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentDidMount",value:function(){this.setState({initialSlideWidth:document.documentElement.clientWidth})}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.data,i=t.hasLine,u=t.isCarousel,s=t.square,c=(t.activeStyle,t.activeClassName,w(t,["prefixCls","className","data","hasLine","isCarousel","square","activeStyle","activeClassName"])),f=c.columnNum,d=c.carouselMaxRow,p=(c.onClick,c.renderItem,w(c,["columnNum","carouselMaxRow","onClick","renderItem"])),h=this.state.initialSlideWidth;f=f,d=d;var v=o&&o.length||0,m=Math.ceil(v/f),y=void 0,_=void 0;if(u){if(h<0)return null;m%d!==0&&(m=m+d-m%d);var C=Math.ceil(m/d);y=this.getRows(m,v);var x={};C<=1&&(x={dots:!1,dragging:!1,swiping:!1}),_=g.default.createElement(S.default,(0,l.default)({initialSlideWidth:h},p,x),this.renderCarousel(y,C,m))}else y=this.getRows(m,v),_=y;var O=(0,b.default)(n,r,(e={},(0,a.default)(e,n+"-square",s),(0,a.default)(e,n+"-line",i),(0,a.default)(e,n+"-carousel",u),e));return g.default.createElement("div",{className:O},_)}}]),t}(g.default.Component);t.default=P,P.defaultProps={data:[],hasLine:!0,isCarousel:!1,columnNum:4,carouselMaxRow:2,prefixCls:"am-grid",square:!0},e.exports=t.default},function(e,t,n){"use strict";n(9),n(34),n(83),n(317)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e){return'\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlns:xlink="http://www.w3.org/1999/xlink"\n id="__ANTD_MOBILE_SVG_SPRITE_NODE__"\n style="position:absolute;width:0;height:0"\n >\n <defs>\n '+e+"\n </defs>\n </svg>\n"},r={check:'<svg viewBox="0 0 44 44"><path fill-rule="evenodd" d="M34.538 8L38 11.518 17.808 32 8 22.033l3.462-3.518 6.346 6.45z"/></svg>',"check-circle":'<svg viewBox="0 0 48 48"><path d="M24 48c13.255 0 24-10.745 24-24S37.255 0 24 0 0 10.745 0 24s10.745 24 24 24zM13.1 23.2l-2.2 2.1 10 9.9L38.1 15l-2.2-2-15.2 17.8-7.6-7.6z" fill-rule="evenodd"/></svg>',"check-circle-o":'<svg viewBox="0 0 48 48"><g fill-rule="evenodd"><path d="M24 48c13.255 0 24-10.745 24-24S37.255 0 24 0 0 10.745 0 24s10.745 24 24 24zm0-3c11.598 0 21-9.402 21-21S35.598 3 24 3 3 12.402 3 24s9.402 21 21 21z"/><path d="M12.2 23.2L10 25.3l10 9.9L37.2 15 35 13 19.8 30.8z"/></g></svg>',cross:'<svg viewBox="0 0 44 44"><path fill-rule="evenodd" d="M24.008 21.852l8.97-8.968L31.092 11l-8.97 8.968L13.157 11l-1.884 1.884 8.968 8.968-9.24 9.24 1.884 1.885 9.24-9.24 9.24 9.24 1.885-1.884-9.24-9.24z"/></svg>',"cross-circle":'<svg viewBox="0 0 48 48"><g fill-rule="evenodd"><path d="M24 48c13.255 0 24-10.745 24-24S37.255 0 24 0 0 10.745 0 24s10.745 24 24 24zm0-3c11.598 0 21-9.402 21-21S35.598 3 24 3 3 12.402 3 24s9.402 21 21 21z"/><path d="M24.34 22.22l-7.775-7.775a1.5 1.5 0 1 0-2.12 2.12l7.773 7.775-7.774 7.775a1.5 1.5 0 1 0 2.12 2.12l7.775-7.773 7.774 7.774a1.5 1.5 0 1 0 2.12-2.12L26.46 24.34l7.774-7.774a1.5 1.5 0 1 0-2.12-2.12l-7.776 7.773z"/></g></svg>',"cross-circle-o":'<svg viewBox="0 0 48 48"><path d="M24 48c13.255 0 24-10.745 24-24S37.255 0 24 0 0 10.745 0 24s10.745 24 24 24zm.353-25.77l-7.593-7.593c-.797-.8-1.538-.822-2.263-.207-.724.614-.56 1.617-.124 2.067l7.852 7.847-7.72 7.723c-.727.728-.56 1.646-.066 2.177.493.532 1.553.683 2.31-.174l7.588-7.584 7.644 7.623c.796.798 1.608.724 2.21.145.605-.58.72-1.442-.074-2.24l-7.657-7.67 7.545-7.52c.81-.697.9-1.76.297-2.34-.92-.885-1.85-.338-2.264.078l-7.685 7.667z" fill-rule="evenodd"/></svg>',left:'<svg viewBox="0 0 44 44"><defs><path id="a" d="M-129-845h24v24h-24z"/></defs><clipPath id="b"><use xlink:href="#a" overflow="visible"/></clipPath><g clip-path="url(#b)"><defs><path id="c" d="M-903-949H947V996H-903z"/></defs></g><path d="M16.247 21.4L28.48 9.165l2.12 2.12-10.117 10.12L30.6 31.524l-2.12 2.12-12.233-12.232.007-.006z"/></svg>',right:'<svg viewBox="0 0 44 44"><defs><path id="a" d="M-129-845h24v24h-24z"/></defs><clipPath id="b"><use xlink:href="#a" overflow="visible"/></clipPath><g clip-path="url(#b)"><defs><path id="c" d="M-903-949H947V996H-903z"/></defs></g><path d="M30.6 21.4L18.37 9.165l-2.12 2.12 10.117 10.12-10.118 10.118 2.12 2.12 12.234-12.232-.005-.006z"/></svg>',down:'<svg viewBox="0 0 44 44"><path d="M22.355 28.237l-11.483-10.9c-.607-.576-1.714-.396-2.48.41l.674-.71c-.763.802-.73 2.07-.282 2.496l11.37 10.793-.04.04 2.088 2.195L23.3 31.52l12.308-11.682c.447-.425.48-1.694-.282-2.496l.674.71c-.766-.806-1.873-.986-2.48-.41L22.355 28.237z" fill-rule="evenodd"/></svg>',up:'<svg viewBox="0 0 44 44"><path fill="none" d="M-1-1h46v46H-1z"/><defs><path id="a" d="M-129-845h24v24h-24z"/></defs><clipPath id="b"><use xlink:href="#a"/></clipPath><g clip-path="url(#b)"><defs><path id="c" d="M-903-949H947V996H-903z"/></defs></g><path d="M23.417 14.23L11.184 26.46l2.12 2.12 10.12-10.117 10.118 10.118 2.12-2.12L23.43 14.228l-.006.005z"/></svg>',loading:'<svg viewBox="0 -2 59.75 60.25"><path fill="#ccc" d="M29.69-.527C14.044-.527 1.36 12.158 1.36 27.806S14.043 56.14 29.69 56.14c15.65 0 28.334-12.686 28.334-28.334S45.34-.527 29.69-.527zm.185 53.75c-14.037 0-25.417-11.38-25.417-25.417S15.838 2.39 29.875 2.39s25.417 11.38 25.417 25.417-11.38 25.416-25.417 25.416z"/><path fill="none" stroke="#108ee9" stroke-width="3" stroke-linecap="round" stroke-miterlimit="10" d="M56.587 29.766c.37-7.438-1.658-14.7-6.393-19.552"/></svg>',search:'<svg viewBox="0 0 44 44"><path d="M32.98 29.255l8.915 8.293L39.603 40l-8.86-8.242a15.952 15.952 0 0 1-10.753 4.147C11.16 35.905 4 28.763 4 19.952 4 11.142 11.16 4 19.99 4s15.99 7.142 15.99 15.952c0 3.472-1.112 6.685-3 9.303zm.05-9.21c0 7.123-5.7 12.918-12.88 12.918-7.176 0-13.015-5.795-13.015-12.918 0-7.12 5.84-12.917 13.017-12.917 7.178 0 12.88 5.797 12.88 12.917z" fill-rule="evenodd"/></svg>',ellipsis:'<svg viewBox="0 0 44 44"><circle cx="21.888" cy="22" r="4.045"/><circle cx="5.913" cy="22" r="4.045"/><circle cx="37.863" cy="22" r="4.045"/></svg>',"ellipsis-circle":'<svg viewBox="0 0 44 44"><g fill-rule="evenodd"><path d="M22.13.11C10.05.11.255 9.902.255 21.983S10.05 43.86 22.13 43.86s21.875-9.795 21.875-21.876S34.21.11 22.13.11zm0 40.7c-10.396 0-18.825-8.43-18.825-18.826S11.735 3.16 22.13 3.16c10.396 0 18.825 8.428 18.825 18.824S32.525 40.81 22.13 40.81z"/><circle cx="21.888" cy="22.701" r="2.445"/><circle cx="12.23" cy="22.701" r="2.445"/><circle cx="31.546" cy="22.701" r="2.445"/></g></svg>',"exclamation-circle":'<svg viewBox="0 0 64 64"><path d="M59.58 40.89L41.193 9.11C39.135 5.382 35.723 3 31.387 3c-3.11 0-6.52 2.382-8.58 6.11L4.42 40.89c-2.788 4.635-3.126 8.81-1.225 12.22C5.015 56.208 7.572 58 13 58h36.773c5.428 0 9.21-1.792 11.03-4.89 1.9-3.41 1.565-7.583-1.224-12.22zm-2.452 11c-.635 1.694-3.802 2.443-7.354 2.443H13c-3.59 0-5.493-.75-6.13-2.444-1.71-2.41-1.374-5.263 0-8.557l18.387-31.777c2.116-3.168 4.394-4.89 6.13-4.89 2.96 0 5.238 1.722 7.354 4.89l18.387 31.777c1.374 3.294 1.713 6.146 0 8.556zm-25.74-33c-.405 0-1.227.835-1.227 2.443v15.89c0 1.608.823 2.444 1.227 2.444 1.628 0 2.452-.836 2.452-2.445v-15.89c0-1.607-.825-2.443-2.453-2.443zm0 23.22c-.405 0-1.227.79-1.227 1.223v2.445c0 .434.823 1.222 1.227 1.222 1.628 0 2.452-.788 2.452-1.222v-2.445c0-.434-.825-1.222-2.453-1.222z" fill-rule="evenodd"/></svg>',"info-circle":'<svg viewBox="0 0 44 44"><circle cx="13.828" cy="19.63" r="1.938"/><circle cx="21.767" cy="19.63" r="1.938"/><circle cx="29.767" cy="19.63" r="1.938"/><path d="M22.102 4.16c-9.918 0-17.958 7.147-17.958 15.962 0 4.935 2.522 9.345 6.48 12.273v5.667l.04.012a2.627 2.627 0 1 0 4.5 1.455h.002l5.026-3.54c.628.06 1.265.094 1.91.094 9.92 0 17.96-7.146 17.96-15.96C40.06 11.306 32.02 4.16 22.1 4.16zm-.04 29.902c-.902 0-1.78-.08-2.642-.207l-5.882 4.234c-.024.024-.055.04-.083.06l-.008.005a.51.51 0 0 1-.284.095.525.525 0 0 1-.525-.525l.005-6.375c-3.91-2.516-6.456-6.544-6.456-11.1 0-7.628 7.107-13.812 15.875-13.812s15.875 6.184 15.875 13.812-7.107 13.812-15.875 13.812z"/></svg>',"question-circle":'<svg viewBox="0 0 44 44"><g fill-rule="evenodd"><path d="M21.186 3c-10.853 0-19.36 8.506-19.36 19.358C1.827 32.494 10.334 41 21.187 41c10.133 0 18.64-8.506 18.64-18.642C39.827 11.506 31.32 3 21.187 3m15.64 19c0 8.823-7.178 16-16 16s-16-7.177-16-16 7.178-16 16-16 16 7.177 16 16z"/><path d="M22.827 31.5a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m4-15.48c0 .957-.203 1.822-.61 2.593-.427.792-1.117 1.612-2.073 2.457-.867.734-1.453 1.435-1.754 2.096-.302.7-.453 1.693-.453 2.98a.828.828 0 0 1-.823.854.828.828 0 0 1-.584-.22.877.877 0 0 1-.24-.635c0-1.305.168-2.38.506-3.227.336-.883.93-1.682 1.78-2.4 1.01-.883 1.71-1.692 2.1-2.428.336-.645.503-1.38.503-2.21-.02-.935-.3-1.7-.85-2.288-.655-.717-1.62-1.075-2.897-1.075-1.506 0-2.596.535-3.27 1.6-.46.754-.688 1.645-.688 2.677a.92.92 0 0 1-.266.66.747.747 0 0 1-.56.25.73.73 0 0 1-.584-.194c-.16-.164-.24-.393-.24-.69 0-1.82.585-3.272 1.755-4.357C18.645 11.486 19.928 11 21.434 11h.293c1.452 0 2.638.414 3.56 1.24 1.028.903 1.54 2.163 1.54 3.78z"/></g></svg>',voice:'<svg viewBox="0 0 38 33"><g fill-rule="evenodd"><path d="M17.838 28.8c-.564-.468-1.192-.983-1.836-1.496-4.244-3.385-5.294-3.67-6.006-3.67-.014 0-.027.005-.04.005-.015 0-.028-.006-.042-.006H3.562c-.734 0-.903-.203-.903-.928v-12.62c0-.49.057-.8.66-.8H9.1c.694 0 1.76-.28 6.4-3.63.83-.596 1.638-1.196 2.337-1.722V28.8zM19.682.19c-.463-.22-1.014-.158-1.417.157-.02.016-1.983 1.552-4.152 3.125C10.34 6.21 9.243 6.664 9.02 6.737H3.676c-.027 0-.053.003-.08.004H1.183c-.608 0-1.1.487-1.1 1.086V25.14c0 .598.492 1.084 1.1 1.084h8.71c.22.08 1.257.55 4.605 3.24 1.947 1.562 3.694 3.088 3.712 3.103.25.22.568.333.89.333.186 0 .373-.038.55-.116.48-.213.79-.684.79-1.204V1.38c0-.506-.294-.968-.758-1.19z" mask="url(#mask-2)"/><path d="M31.42 16.475c0-3.363-1.854-6.297-4.606-7.876-.125-.067-.42-.193-.625-.193-.613 0-1.11.488-1.11 1.09 0 .404.22.764.55.952 2.13 1.19 3.566 3.44 3.566 6.024 0 2.627-1.486 4.913-3.677 6.087-.32.19-.53.54-.53.935 0 .602.495 1.09 1.106 1.09.26.002.568-.15.568-.15 2.835-1.556 4.754-4.538 4.754-7.96" mask="url(#mask-4)"/><path d="M30.14 3.057c-.205-.122-.41-.22-.658-.22-.608 0-1.1.485-1.1 1.084 0 .434.26.78.627.978 4.042 2.323 6.76 6.636 6.76 11.578 0 4.938-2.715 9.248-6.754 11.572-.354.19-.66.55-.66.993 0 .6.494 1.085 1.102 1.085.243 0 .438-.092.65-.213 4.692-2.695 7.848-7.7 7.848-13.435 0-5.723-3.142-10.718-7.817-13.418" mask="url(#mask-6)"/></g></svg>',plus:'<svg viewBox="0 0 30 30"><path d="M14 14H0v2h14v14h2V16h14v-2H16V0h-2v14z" fill-rule="evenodd"/></svg>',minus:'<svg viewBox="0 0 30 2"><path d="M0 0h30v2H0z" fill-rule="evenodd"/></svg>',dislike:'<svg viewBox="0 0 72 72"><g fill="none" fill-rule="evenodd"><path d="M36 72c19.882 0 36-16.118 36-36S55.882 0 36 0 0 16.118 0 36s16.118 36 36 36zm0-2c18.778 0 34-15.222 34-34S54.778 2 36 2 2 17.222 2 36s15.222 34 34 34z" fill="#FFF"/><path fill="#FFF" d="M47 22h2v6h-2zm-24 0h2v6h-2z"/><path d="M21 51s4.6-7 15-7 15 7 15 7" stroke="#FFF" stroke-width="2"/></g></svg>',fail:'<svg viewBox="0 0 72 72"><g fill="none" fill-rule="evenodd"><path d="M36 72c19.882 0 36-16.118 36-36S55.882 0 36 0 0 16.118 0 36s16.118 36 36 36zm0-2c18.778 0 34-15.222 34-34S54.778 2 36 2 2 17.222 2 36s15.222 34 34 34z" fill="#FFF"/><path d="M22 22l28.304 28.304m-28.304 0L50.304 22" stroke="#FFF" stroke-width="2"/></g></svg>',success:'<svg viewBox="0 0 72 72"><g fill="none" fill-rule="evenodd"><path d="M36 72c19.882 0 36-16.118 36-36S55.882 0 36 0 0 16.118 0 36s16.118 36 36 36zm0-2c18.778 0 34-15.222 34-34S54.778 2 36 2 2 17.222 2 36s15.222 34 34 34z" fill="#FFF"/><path stroke="#FFF" stroke-width="2" d="M19 34.54l11.545 11.923L52.815 24"/></g></svg>'},o=function(){var e=Object.keys(r).map(function(e){var t=r[e].split("svg")[1];return"<symbol id="+e+t+"symbol>"}).join("");return n(e)},a=function(){if(document){var e=document.getElementById("__ANTD_MOBILE_SVG_SPRITE_NODE__"),t=document.body;e||t.insertAdjacentHTML("afterbegin",o())}};t.default=a,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=r(a),l=n(5),u=r(l),s=n(4),c=r(s),f=n(3),d=r(f),p=n(1),h=r(p),v=n(7),m=r(v),g=n(92),y=r(g),b=n(33),_=r(b),C=n(89),x=r(C),S=n(12),O=r(S),k=_.default.Item,w=function(e){function t(){(0,i.default)(this,t);var e=(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getOrientation=function(e,t){var n=new FileReader;n.onload=function(e){var n=new DataView(e.target.result);if(65496!==n.getUint16(0,!1))return t(-2);for(var r=n.byteLength,o=2;o<r;){var a=n.getUint16(o,!1);if(o+=2,65505===a){var i=n.getUint32(o+=2,!1);if(1165519206!==i)return t(-1);var l=18761===n.getUint16(o+=6,!1);o+=n.getUint32(o+4,l);var u=n.getUint16(o,l);o+=2;for(var s=0;s<u;s++)if(274===n.getUint16(o+12*s,l))return t(n.getUint16(o+12*s+8,l))}else{if(65280!==(65280&a))break;o+=n.getUint16(o,!1)}}return t(-1)},n.readAsArrayBuffer(e.slice(0,65536))},e.getRotation=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=0;switch(e){case 3:t=180;break;case 6:t=90;break;case 8:t=270}return t},e.removeImage=function(t){var n=[],r=e.props.files,o=void 0===r?[]:r;o.forEach(function(e,r){t!==r&&n.push(e)}),e.props.onChange&&e.props.onChange(n,"remove",t)},e.addImage=function(t){var n=e.props.files,r=void 0===n?[]:n,o=r.concat(t);e.props.onChange&&e.props.onChange(o,"add")},e.onImageClick=function(t){e.props.onImageClick&&e.props.onImageClick(t,e.props.files)},e.onFileChange=function(){var t=e.fileSelectorInput;if(t&&t.files&&t.files.length){var n=t.files[0],r=new FileReader;r.onload=function(r){var o=r.target.result;if(!o)return void x.default.fail("\u56fe\u7247\u83b7\u53d6\u5931\u8d25");var a=1;e.getOrientation(n,function(r){r>0&&(a=r),e.addImage({url:o,orientation:a,file:n}),t.value=""})},r.readAsDataURL(n)}},e}return(0,d.default)(t,e),(0,u.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.style,o=t.className,a=t.files,i=void 0===a?[]:a,l=t.selectable,u=t.onAddImageClick,s=[],c=(0,m.default)(""+n,o);i.forEach(function(t,r){var o={backgroundImage:"url("+t.url+")",transform:"rotate("+e.getRotation(t.orientation)+"deg)"};s.push(h.default.createElement(k,{key:"item-"+r},h.default.createElement("div",{key:r,className:n+"-item"},h.default.createElement("div",{className:n+"-item-remove",role:"button","aria-label":"Click and Remove this image",onClick:function(){e.removeImage(r)}}),h.default.createElement("div",{className:n+"-item-content",role:"button","aria-label":"Image can be clicked",onClick:function(){e.onImageClick(r)},style:o}))))});var f=h.default.createElement(k,{key:"select"},h.default.createElement(O.default,{activeClassName:n+"-upload-btn-active"},h.default.createElement("div",{className:n+"-item "+n+"-upload-btn",onClick:u,role:"button","aria-label":"Choose and add image"},h.default.createElement("input",{ref:function(t){e.fileSelectorInput=t},type:"file",accept:"image/jpg,image/jpeg,image/png,image/gif",onChange:function(){e.onFileChange()}})))),d=l?s.concat([f]):s,p=d.length;if(0!==p&&p%4!==0){for(var v=4-p%4,g=[],b=0;b<v;b++)g.push(h.default.createElement(k,{key:"blank-"+b}));d=d.concat(g)}for(var C=[],x=0;x<d.length/4;x++){var S=d.slice(4*x,4*x+4);C.push(S)}var w=C.map(function(e,t){return h.default.createElement(_.default,{key:"flex-"+t},e)});return h.default.createElement("div",{className:c,style:r},h.default.createElement("div",{className:n+"-list",role:"group"},h.default.createElement(y.default,{size:"md"},w)))}}]),t}(h.default.Component);t.default=w,w.defaultProps={prefixCls:"am-image-picker",files:[],onChange:o,onImageClick:o,onAddImageClick:o,selectable:!0},e.exports=t.default},function(e,t,n){"use strict";n(9),n(93),n(34),n(90),n(319)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(134);Object.defineProperty(t,"Accordion",{enumerable:!0,get:function(){return r(o).default}});var a=n(136);Object.defineProperty(t,"ActionSheet",{enumerable:!0,get:function(){return r(a).default}});var i=n(138);Object.defineProperty(t,"ActivityIndicator",{enumerable:!0,get:function(){return r(i).default}});var l=n(80);Object.defineProperty(t,"Badge",{enumerable:!0,get:function(){return r(l).default}});var u=n(49);Object.defineProperty(t,"Button",{enumerable:!0,get:function(){return r(u).default}});var s=n(140);Object.defineProperty(t,"Calendar",{enumerable:!0,get:function(){return r(s).default}});var c=n(146);Object.defineProperty(t,"Card",{enumerable:!0,get:function(){return r(c).default}});var f=n(82);Object.defineProperty(t,"Carousel",{enumerable:!0,get:function(){return r(f).default}});var d=n(150);Object.defineProperty(t,"Checkbox",{enumerable:!0,get:function(){return r(d).default}});var p=n(155);Object.defineProperty(t,"DatePicker",{enumerable:!0,get:function(){return r(p).default}});var h=n(152);Object.defineProperty(t,"DatePickerView",{enumerable:!0,get:function(){return r(h).default}});var v=n(159);Object.defineProperty(t,"Drawer",{enumerable:!0,get:function(){return r(v).default}});var m=n(33);Object.defineProperty(t,"Flex",{enumerable:!0,get:function(){return r(m).default}});var g=n(163);Object.defineProperty(t,"Grid",{enumerable:!0,get:function(){return r(g).default}});var y=n(14);Object.defineProperty(t,"Icon",{enumerable:!0,get:function(){return r(y).default}});var b=n(166);Object.defineProperty(t,"ImagePicker",{enumerable:!0,get:function(){return r(b).default}});var _=n(172);Object.defineProperty(t,"InputItem",{enumerable:!0,get:function(){return r(_).default}});var C=n(26);Object.defineProperty(t,"List",{enumerable:!0,get:function(){return r(C).default}});var x=n(176);Object.defineProperty(t,"ListView",{enumerable:!0,get:function(){return r(x).default}});var S=n(183);Object.defineProperty(t,"Menu",{enumerable:!0,get:function(){return r(S).default}});var O=n(187);Object.defineProperty(t,"Modal",{enumerable:!0,get:function(){return r(O).default}});var k=n(191);Object.defineProperty(t,"NavBar",{enumerable:!0,get:function(){return r(k).default}});var w=n(194);Object.defineProperty(t,"NoticeBar",{enumerable:!0,get:function(){return r(w).default}});var P=n(196);Object.defineProperty(t,"Pagination",{enumerable:!0,get:function(){return r(P).default}});var T=n(202);Object.defineProperty(t,"Picker",{enumerable:!0,get:function(){return r(T).default}});var E=n(200);Object.defineProperty(t,"PickerView",{enumerable:!0,get:function(){return r(E).default}});var M=n(205);Object.defineProperty(t,"Popover",{enumerable:!0,get:function(){return r(M).default}});var N=n(207);Object.defineProperty(t,"Progress",{enumerable:!0,get:function(){return r(N).default}});var j=n(210);Object.defineProperty(t,"Radio",{enumerable:!0,get:function(){return r(j).default}});var D=n(213);Object.defineProperty(t,"RefreshControl",{enumerable:!0,get:function(){return r(D).default}});var L=n(215);Object.defineProperty(t,"Result",{enumerable:!0,get:function(){return r(L).default}});var R=n(218);Object.defineProperty(t,"SearchBar",{enumerable:!0,get:function(){return r(R).default}});var I=n(220);Object.defineProperty(t,"SegmentedControl",{enumerable:!0,get:function(){return r(I).default}});var A=n(222);Object.defineProperty(t,"Slider",{enumerable:!0,get:function(){return r(A).default}});var V=n(211);Object.defineProperty(t,"Range",{enumerable:!0,get:function(){return r(V).default}});var B=n(224);Object.defineProperty(t,"Stepper",{enumerable:!0,get:function(){return r(B).default}});var H=n(226);Object.defineProperty(t,"Steps",{enumerable:!0,get:function(){return r(H).default}});var W=n(228);Object.defineProperty(t,"SwipeAction",{enumerable:!0,get:function(){return r(W).default}});var z=n(230);Object.defineProperty(t,"Switch",{enumerable:!0,get:function(){return r(z).default}});var F=n(233);Object.defineProperty(t,"TabBar",{enumerable:!0,get:function(){return r(F).default}});var U=n(87);Object.defineProperty(t,"Tabs",{enumerable:!0,get:function(){return r(U).default}});var Y=n(235);Object.defineProperty(t,"Tag",{enumerable:!0,get:function(){return r(Y).default}});var X=n(237);Object.defineProperty(t,"Text",{enumerable:!0,get:function(){return r(X).default}});var K=n(239);Object.defineProperty(t,"TextareaItem",{enumerable:!0,get:function(){return r(K).default}});var q=n(89);Object.defineProperty(t,"Toast",{enumerable:!0,get:function(){return r(q).default}});var G=n(91);Object.defineProperty(t,"View",{enumerable:!0,get:function(){return r(G).default}});var Z=n(242);Object.defineProperty(t,"WhiteSpace",{enumerable:!0,get:function(){return r(Z).default}});var $=n(92);Object.defineProperty(t,"WingBlank",{enumerable:!0,get:function(){return r($).default}});var Q=n(179);Object.defineProperty(t,"LocaleProvider",{enumerable:!0,get:function(){return r(Q).default}});var J="production";"production"!==J&&"test"!==J&&"undefined"!=typeof console&&console.warn&&"undefined"!=typeof window&&console.warn("You are using a whole package of antd-mobile, please use https://www.npmjs.com/package/babel-plugin-import to reduce app bundle size.")},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(11),v=r(h),m=n(7),g=r(m),y=n(170),b=r(y),_=n(132),C=function(e){function t(){(0,a.default)(this,t);var e=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={focus:!1},e.addBlurListener=function(){document.addEventListener("click",e.doBlur,!1)},e.removeBlurListen=function(){document.removeEventListener("click",e.doBlur,!1)},e.getComponent=function(){var t=e.props,n=t.keyboardPrefixCls,r=t.confirmLabel;return p.default.createElement(b.default,{onClick:e.onKeyboardClick,preixCls:n,confirmLabel:r})},e.renderCustomKeyboard=function(){var t=document.querySelector("#"+e.props.keyboardPrefixCls+"-container");t||(t=document.createElement("div"),t.setAttribute("id",e.props.keyboardPrefixCls+"-container"),document.body.appendChild(t),
window.antmCustomKeyboard=v.default.unstable_renderSubtreeIntoContainer(e,e.getComponent(),t))},e.doBlur=function(t){var n=e.props.value;t.target!==e.inputRef&&e.onInputBlur(n)},e.unLinkInput=function(){var t=window.antmCustomKeyboard;t.linkedInput===e&&(t.linkedInput=null,(0,_.addClass)(t.antmKeyboard,e.props.keyboardPrefixCls+"-wrapper-hide"),e.removeBlurListen())},e.onInputBlur=function(t){var n=e.state.focus;n&&(e.setState({focus:!1}),e.props.onBlur(t),setTimeout(function(){e.unLinkInput()},50))},e.onInputFocus=function(){var t=e.props.value;e.props.onFocus(t),e.setState({focus:!0},function(){var n=window.antmCustomKeyboard;n.linkedInput=e,(0,_.removeClass)(n.antmKeyboard,e.props.keyboardPrefixCls+"-wrapper-hide"),n.confirmDisabled=""===t,""===t?(0,_.addClass)(n.confirmKeyboardItem,e.props.keyboardPrefixCls+"-item-disabled"):(0,_.removeClass)(n.confirmKeyboardItem,e.props.keyboardPrefixCls+"-item-disabled")})},e.onKeyboardClick=function(t){var n=e.props,r=n.value,o=n.onChange,a=n.maxLength,i=void 0;"delete"===t?(i=r.substring(0,r.length-1),o({target:{value:i}})):"confirm"===t?(i=r,o({target:{value:i}}),e.onInputBlur(r)):"hide"===t?(i=r,e.onInputBlur(i)):void 0!==a&&+a>=0&&(r+t).length>a?(i=(r+t).substr(0,a),o({target:{value:i}})):(i=r+t,o({target:{value:i}}));var l=window.antmCustomKeyboard;l.confirmDisabled=""===i,""===i?(0,_.addClass)(l.confirmKeyboardItem,e.props.keyboardPrefixCls+"-item-disabled"):(0,_.removeClass)(l.confirmKeyboardItem,e.props.keyboardPrefixCls+"-item-disabled")},e.onFakeInputClick=function(){e.focus()},e.focus=function(){e.removeBlurListen();var t=e.state.focus;t||e.onInputFocus(),setTimeout(function(){e.addBlurListener()},50)},e}return(0,f.default)(t,e),(0,l.default)(t,[{key:"componentDidMount",value:function(){window.antmCustomKeyboard||this.renderCustomKeyboard()}},{key:"componentWillUnmount",value:function(){this.unLinkInput()}},{key:"render",value:function(){var e=this,t=this.props,n=t.placeholder,r=t.value,o=t.disabled,a=t.editable,i=t.moneyKeyboardAlign,l=this.state.focus,u=o||!a,s=(0,g.default)("fake-input",{focus:l,"fake-input-disabled":o}),c=(0,g.default)("fake-input-container",{"fake-input-container-left":"left"===i});return p.default.createElement("div",{className:c},""===r&&p.default.createElement("div",{className:"fake-input-placeholder"},n),p.default.createElement("div",{className:s,ref:function(t){return e.inputRef=t},onClick:u?function(){}:this.onFakeInputClick},r))}}]),t}(p.default.Component);C.defaultProps={onChange:function(){},onFocus:function(){},onBlur:function(){},placeholder:"",value:"",disabled:!1,editable:!0,prefixCls:"am-input",keyboardPrefixCls:"am-number-keyboard"},t.default=C,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.KeyboardItem=void 0;var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(12),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=t.KeyboardItem=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.onClick,r=e.className,o=(e.disabled,e.children),i=e.tdRef,l=_(e,["prefixCls","onClick","className","disabled","children","tdRef"]),u=o;"keyboard-delete"===r?u="delete":"keyboard-hide"===r?u="hide":"keyboard-confirm"===r&&(u="confirm");var s=(0,g.default)(t+"-item",r);return v.default.createElement(b.default,{activeClassName:t+"-item-active"},v.default.createElement("td",(0,a.default)({ref:i,onClick:function(e){n(e,u)},className:s},l),o))}}]),t}(v.default.Component);C.defaultProps={prefixCls:"am-number-keyboard",onClick:function(){},disabled:!1};var x=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onKeyboardClick=function(t,n){return t.nativeEvent.stopImmediatePropagation(),"confirm"===n&&e.confirmDisabled?null:void(e.linkedInput&&e.linkedInput.onKeyboardClick(n))},e.renderKeyboardItem=function(t,n){return v.default.createElement(C,{onClick:e.onKeyboardClick,key:"item-"+t+"-"+n},t)},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.confirmLabel,o=(0,g.default)(n+"-wrapper",n+"-wrapper-hide");return v.default.createElement("div",{className:o,ref:function(t){return e.antmKeyboard=t}},v.default.createElement("table",null,v.default.createElement("tbody",null,v.default.createElement("tr",null,["1","2","3"].map(function(t,n){return e.renderKeyboardItem(t,n)}),v.default.createElement(C,{className:"keyboard-delete",rowSpan:2,onClick:this.onKeyboardClick})),v.default.createElement("tr",null,["4","5","6"].map(function(t,n){return e.renderKeyboardItem(t,n)})),v.default.createElement("tr",null,["7","8","9"].map(function(t,n){return e.renderKeyboardItem(t,n)}),v.default.createElement(C,{className:"keyboard-confirm",rowSpan:2,onClick:this.onKeyboardClick,tdRef:function(t){return e.confirmKeyboardItem=t}},r)),v.default.createElement("tr",null,[".","0"].map(function(t,n){return e.renderKeyboardItem(t,n)}),v.default.createElement(C,{className:"keyboard-hide",onClick:this.onKeyboardClick})))))}}]),t}(v.default.Component);x.defaultProps={prefixCls:"am-number-keyboard"},t.default=x},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},g=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onInputBlur=function(t){var n=t.target.value;e.props.onBlur&&e.props.onBlur(n)},e.onInputFocus=function(t){var n=t.target.value;e.props.onFocus&&e.props.onFocus(n)},e.focus=function(){e.inputRef.focus()},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=(t.onBlur,t.onFocus,m(t,["onBlur","onFocus"]));return v.default.createElement("input",(0,a.default)({ref:function(t){return e.inputRef=t},onBlur:this.onInputBlur,onFocus:this.onInputFocus},n))}}]),t}(v.default.Component);t.default=g,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(e){return"undefined"==typeof e||null===e?"":e}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),l=r(i),u=n(8),s=r(u),c=n(2),f=r(c),d=n(5),p=r(d),h=n(4),v=r(h),m=n(3),g=r(m),y=n(1),b=r(y),_=n(10),C=r(_),x=n(7),S=r(x),O=n(171),k=r(O),w=n(169),P=r(w),T=n(32),E=n(12),M=r(E),N=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},j=function(e){function t(e){(0,f.default)(this,t);var n=(0,v.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onInputChange=function(e){var t=e.target.value,r=n.props,o=r.onChange,a=r.type;switch(a){case"text":break;case"bankCard":t=t.replace(/\D/g,"").replace(/(....)(?=.)/g,"$1 ");break;case"phone":t=t.replace(/\D/g,"").substring(0,11);var i=t.length;i>3&&i<8?t=t.substr(0,3)+" "+t.substr(3):i>=8&&(t=t.substr(0,3)+" "+t.substr(3,4)+" "+t.substr(7));break;case"number":t=t.replace(/\D/g,"");break;case"password":}o&&o(t)},n.onInputFocus=function(e){n.debounceTimeout&&(clearTimeout(n.debounceTimeout),n.debounceTimeout=null),n.setState({focus:!0}),"input"===document.activeElement.tagName.toLowerCase()&&(n.scrollIntoViewTimeout=setTimeout(function(){try{document.activeElement.scrollIntoViewIfNeeded()}catch(e){}},100)),n.props.onFocus&&n.props.onFocus(e)},n.onInputBlur=function(e){n.debounceTimeout=setTimeout(function(){n.setState({focus:!1})},200),n.props.onBlur&&n.props.onBlur(e)},n.onExtraClick=function(e){n.props.onExtraClick&&n.props.onExtraClick(e)},n.onErrorClick=function(e){n.props.onErrorClick&&n.props.onErrorClick(e)},n.clearInput=function(){"password"!==n.props.type&&n.props.updatePlaceholder&&n.setState({placeholder:n.props.value}),n.props.onChange&&n.props.onChange(""),n.focus()},n.focus=function(){n.inputRef.focus()},n.state={placeholder:e.placeholder},n}return(0,g.default)(t,e),(0,p.default)(t,[{key:"componentWillReceiveProps",value:function(e){"placeholder"in e&&!e.updatePlaceholder&&this.setState({placeholder:e.placeholder})}},{key:"componentWillUnmount",value:function(){this.debounceTimeout&&(clearTimeout(this.debounceTimeout),this.debounceTimeout=null),this.scrollIntoViewTimeout&&(clearTimeout(this.scrollIntoViewTimeout),this.scrollIntoViewTimeout=null)}},{key:"render",value:function(){var e,t,r=this,o=this.props,i=o.prefixCls,u=o.prefixListCls,c=o.editable,f=o.style,d=o.clear,p=o.children,h=o.error,v=o.className,m=o.extra,g=o.labelNumber,y=(o.onExtraClick,o.onErrorClick,o.updatePlaceholder,o.type),_=(o.locale,o.moneyKeyboardAlign),C=N(o,["prefixCls","prefixListCls","editable","style","clear","children","error","className","extra","labelNumber","onExtraClick","onErrorClick","updatePlaceholder","type","locale","moneyKeyboardAlign"]),x=C.value,O=C.defaultValue,w=C.name,E=C.disabled,j=C.maxLength,D=(0,T.getComponentLocale)(this.props,this.context,"InputItem",function(){return n(173)}),L=D.confirmLabel,R=this.state,I=R.placeholder,A=R.focus,V=(0,S.default)(u+"-item",i+"-item",v,(e={},(0,s.default)(e,i+"-disabled",E),(0,s.default)(e,i+"-error",h),(0,s.default)(e,i+"-focus",A),(0,s.default)(e,i+"-android",A),e)),B=(0,S.default)(i+"-label",(t={},(0,s.default)(t,i+"-label-2",2===g),(0,s.default)(t,i+"-label-3",3===g),(0,s.default)(t,i+"-label-4",4===g),(0,s.default)(t,i+"-label-5",5===g),(0,s.default)(t,i+"-label-6",6===g),(0,s.default)(t,i+"-label-7",7===g),t)),H=i+"-control",W="text";"bankCard"===y||"phone"===y?W="tel":"password"===y?W="password":"digit"===y?W="number":"text"!==y&&"number"!==y&&(W=y);var z=void 0;z="value"in this.props?{value:a(x)}:{defaultValue:O};var F=void 0;"number"===y&&(F={pattern:"[0-9]*"});var U=void 0;return"digit"===y&&(U={className:"h5numInput"}),b.default.createElement("div",{className:V},p?b.default.createElement("div",{className:B},p):null,b.default.createElement("div",{className:H},"money"===y?b.default.createElement(P.default,{type:y,ref:function(e){return r.inputRef=e},maxLength:j,placeholder:I,onChange:this.onInputChange,onFocus:this.onInputFocus,onBlur:this.onInputBlur,disabled:E,editable:c,value:a(x),prefixCls:i,style:f,confirmLabel:L,moneyKeyboardAlign:_}):b.default.createElement(k.default,(0,l.default)({},F,C,z,U,{ref:function(e){return r.inputRef=e},style:f,type:W,maxLength:j,name:w,placeholder:I,onChange:this.onInputChange,onFocus:this.onInputFocus,onBlur:this.onInputBlur,readOnly:!c,disabled:E}))),d&&c&&!E&&x&&x.length>0?b.default.createElement(M.default,{activeClassName:i+"-clear-active"},b.default.createElement("div",{className:i+"-clear",onClick:this.clearInput})):null,h?b.default.createElement("div",{className:i+"-error-extra",onClick:this.onErrorClick}):null,""!==m?b.default.createElement("div",{className:i+"-extra",onClick:this.onExtraClick},m):null)}}]),t}(b.default.Component);j.defaultProps={prefixCls:"am-input",prefixListCls:"am-list",type:"text",editable:!0,disabled:!1,placeholder:"",clear:!1,onChange:o,onBlur:o,onFocus:o,extra:"",onExtraClick:o,error:!1,onErrorClick:o,labelNumber:5,updatePlaceholder:!1,moneyKeyboardAlign:"right"},j.contextTypes={antLocale:C.default.object},t.default=j,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={confirmLabel:"\u786e\u5b9a"},e.exports=t.default},[443,320],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(77),g=r(m),y=n(85),b=r(y),_=g.default.IndexedList,C=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.listPrefixCls,o=(0,b.default)(this.props,!0),i=o.restProps,l=o.extraProps;return v.default.createElement(_,(0,a.default)({ref:function(t){return e.indexedListRef=t},sectionHeaderClassName:n+"-section-header "+r+"-body",sectionBodyClassName:n+"-section-body "+r+"-body"},i,l),this.props.children)}}]),t}(v.default.Component);t.default=C,C.defaultProps={prefixCls:"am-indexed-list",listPrefixCls:"am-list",listViewPrefixCls:"am-list-view"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(77),g=r(m),y=n(85),b=r(y),_=n(175),C=r(_),x=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.scrollTo=function(){var t;return(t=e.listviewRef).scrollTo.apply(t,arguments)},e.getInnerViewNode=function(){return e.listviewRef.getInnerViewNode()},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this,t=(0,b.default)(this.props,!1),n=t.restProps,r=t.extraProps,o=this.props,i=o.useZscroller,l=o.refreshControl;return l&&(i=!0),v.default.createElement(g.default,(0,a.default)({ref:function(t){return e.listviewRef=t}},n,r,{useZscroller:i}))}}]),t}(v.default.Component);t.default=x,x.defaultProps={prefixCls:"am-list-view",listPrefixCls:"am-list"},x.DataSource=g.default.DataSource,x.IndexedList=C.default,e.exports=t.default},[443,321],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Brief=void 0;var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(12),C=r(_),x=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},S=t.Brief=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){return g.default.createElement("div",{className:"am-list-brief",style:this.props.style},this.props.children)}}]),t}(g.default.Component),O=function(e){function t(e){(0,s.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onClick=function(e){var t=n.props,r=t.onClick,o=t.platform,a="android"===o;if(r&&a){n.debounceTimeout&&(clearTimeout(n.debounceTimeout),n.debounceTimeout=null);var i=e.currentTarget,l=Math.max(i.offsetHeight,i.offsetWidth),u=e.currentTarget.getBoundingClientRect(),s=e.clientX-u.left-i.offsetWidth/2,c=e.clientY-u.top-i.offsetWidth/2,f={width:l+"px",height:l+"px",left:s+"px",top:c+"px"};n.setState({coverRippleStyle:f,RippleClicked:!0},function(){n.debounceTimeout=setTimeout(function(){n.setState({coverRippleStyle:{display:"none"},RippleClicked:!1})},1e3)})}r&&r(e)},n.state={coverRippleStyle:{display:"none"},RippleClicked:!1},n}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentWillUnmount",value:function(){this.debounceTimeout&&(clearTimeout(this.debounceTimeout),this.debounceTimeout=null)}},{key:"render",value:function(){var e,t,n,r=this,o=this.props,i=o.prefixCls,u=o.className,s=o.activeStyle,c=o.error,f=o.align,d=o.wrap,p=o.disabled,h=o.children,v=o.multipleLine,m=o.thumb,y=o.extra,_=o.arrow,S=o.onClick,O=x(o,["prefixCls","className","activeStyle","error","align","wrap","disabled","children","multipleLine","thumb","extra","arrow","onClick"]),k=(O.platform,x(O,["platform"])),w=this.state,P=w.coverRippleStyle,T=w.RippleClicked,E=(0,b.default)(i+"-item",u,(e={},(0,l.default)(e,i+"-item-disabled",p),(0,l.default)(e,i+"-item-error",c),(0,l.default)(e,i+"-item-top","top"===f),(0,l.default)(e,i+"-item-middle","middle"===f),(0,l.default)(e,i+"-item-bottom","bottom"===f),e)),M=(0,b.default)(i+"-ripple",(0,l.default)({},i+"-ripple-animate",T)),N=(0,b.default)(i+"-line",(t={},(0,l.default)(t,i+"-line-multiple",v),(0,l.default)(t,i+"-line-wrap",d),t)),j=(0,b.default)(i+"-arrow",(n={},(0,l.default)(n,i+"-arrow-horizontal","horizontal"===_),(0,l.default)(n,i+"-arrow-vertical","down"===_||"up"===_),(0,l.default)(n,i+"-arrow-vertical-up","up"===_),n)),D=g.default.createElement("div",(0,a.default)({},k,{onClick:function(e){r.onClick(e)},className:E}),m?g.default.createElement("div",{className:i+"-thumb"},"string"==typeof m?g.default.createElement("img",{src:m}):m):null,g.default.createElement("div",{className:N},void 0!==h&&g.default.createElement("div",{className:i+"-content"},h),void 0!==y&&g.default.createElement("div",{className:i+"-extra"},y),_&&g.default.createElement("div",{className:j,"aria-hidden":"true"})),g.default.createElement("div",{style:P,className:M}));return g.default.createElement(C.default,{disabled:p||!S,activeStyle:s,activeClassName:i+"-item-active"},D)}}]),t}(g.default.Component);O.defaultProps={prefixCls:"am-list",align:"middle",error:!1,multipleLine:!1,wrap:!1,platform:"ios"},O.Brief=S,t.default=O},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(180),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(10),g=r(m),y=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"getChildContext",value:function(){return{antLocale:(0,a.default)({},this.props.locale,{exist:!0})}}},{key:"render",value:function(){return v.default.Children.only(this.props.children)}}]),t}(v.default.Component);t.default=y,y.propTypes={locale:g.default.object},y.childContextTypes={antLocale:g.default.object},e.exports=t.default},[444,323],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=function(t){e.onSel&&e.onSel(t)},n=e.subMenuPrefixCls,r=e.radioPrefixCls,o=e.subMenuData,a=e.showSelect,l=e.selItem,s=function(e){return a&&l.length>0&&l[0].value===e.value};return u.default.createElement(d.default,{style:{paddingTop:0},className:n},o.map(function(e,o){var a;return u.default.createElement(d.default.Item,{className:(0,c.default)(r+"-item",(a={},(0,i.default)(a,n+"-item-selected",s(e)),(0,i.default)(a,n+"-item-disabled",e.disabled),a)),key:o,extra:u.default.createElement(h.default,{checked:s(e),disabled:e.disabled,onChange:function(){return t(e)}})},e.label)}))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a);t.default=o;var l=n(1),u=r(l),s=n(7),c=r(s),f=n(26),d=r(f),p=n(54),h=r(p);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(26),b=r(y),_=n(33),C=r(_),x=n(182),S=r(x),O=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onClickFirstLevelItem=function(e){var t=n.props.onChange;n.setState({firstLevelSelectValue:e.value}),e.isLeaf&&t&&t([e.value])},n.onClickSubMenuItem=function(e){var t=n.props,r=t.level,o=t.onChange,a=2===r?[n.state.firstLevelSelectValue,e.value]:[e.value];n.setState({value:a}),setTimeout(function(){o&&o(a)},300)},n.state={firstLevelSelectValue:n.getNewFsv(e),value:e.value},n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillReceiveProps",value:function(e){e.value!==this.props.value&&this.setState({firstLevelSelectValue:this.getNewFsv(e),value:e.value})}},{key:"getNewFsv",value:function(e){var t=e.value,n=e.data,r="";return t&&t.length?r=t[0]:n[0].isLeaf||(r=n[0].value),r}},{key:"render",value:function(){var e=this,t=this.props,n=t.className,r=t.style,o=t.height,i=t.data,l=void 0===i?[]:i,u=t.prefixCls,s=t.level,c=this.state,f=c.firstLevelSelectValue,d=c.value,p=l;if(2===s){var h=l;f&&""!==f&&(h=l.filter(function(e){return e.value===f})),p=h[0]&&h[0].children&&h[0].isLeaf!==!0?h[0].children:[]}var m=d&&d.length>0&&d[d.length-1],y=d&&d.length>1?d[0]:null,_=p.filter(function(e){return e.value===m}),x=!0;2===s&&y!==f&&(x=!1);var O={height:Math.round(o||document.documentElement.clientHeight/2)+"px"};return v.default.createElement("div",{className:(0,g.default)(u,n),style:(0,a.default)({},r,O)},v.default.createElement(C.default,{align:"start"},2===s&&v.default.createElement(C.default.Item,{style:O},v.default.createElement(b.default,{role:"tablist"},l.map(function(t,n){return v.default.createElement(b.default.Item,{className:t.value===f?u+"-selected":"",onClick:function(){return e.onClickFirstLevelItem(t)},key:"listitem-1-"+n,role:"tab","aria-selected":t.value===f},t.label)}))),v.default.createElement(C.default.Item,{style:O,role:"tabpanel","aria-hidden":"false"},v.default.createElement(S.default,{subMenuPrefixCls:this.props.subMenuPrefixCls,radioPrefixCls:this.props.radioPrefixCls,subMenuData:p,selItem:_,onSel:this.onClickSubMenuItem,showSelect:x}))))}}]),t}(v.default.Component);t.default=O,O.defaultProps={prefixCls:"am-menu",subMenuPrefixCls:"am-sub-menu",radioPrefixCls:"am-radio",data:[],level:2,onChange:function(){}},e.exports=t.default},function(e,t,n){"use strict";n(9),n(84),n(34),n(21),n(86),n(324)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ModalComponent=void 0;var o=n(2),a=r(o),i=n(4),l=r(i),u=n(3),s=r(u),c=n(1),f=r(c);t.ModalComponent=function(e){function t(){return(0,a.default)(this,t),(0,l.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,s.default)(t,e),t}(f.default.Component)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){function n(){u.default.unmountComponentAtNode(l),l&&l.parentNode&&l.parentNode.removeChild(l)}var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[{text:"\u786e\u5b9a"}],o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"ios";if(!e&&!t)return{close:function(){}};var a="am-modal",l=document.createElement("div");document.body.appendChild(l);var s=r.map(function(e){var t=e.onPress||function(){};return e.onPress=function(){var e=t();e&&e.then?e.then(function(){n()}):n()},e});return u.default.render(i.default.createElement(c.default,{visible:!0,transparent:!0,prefixCls:a,title:e,transitionName:"am-zoom",closable:!1,maskClosable:!1,footer:s,maskTransitionName:"am-fade",platform:o},i.default.createElement("div",{style:{zoom:1,overflow:"hidden"}},t)),l),{close:n}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1),i=r(a),l=n(11),u=r(l),s=n(40),c=r(s);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(40),a=r(o),i=n(186),l=r(i),u=n(189),s=r(u),c=n(188),f=r(c);a.default.alert=l.default,a.default.prompt=s.default,a.default.operation=f.default,t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){function e(){u.default.unmountComponentAtNode(o),o&&o.parentNode&&o.parentNode.removeChild(o)}var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[{text:"\u786e\u5b9a"}],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"ios",r="am-modal",o=document.createElement("div");document.body.appendChild(o);var a=t.map(function(t){var n=t.onPress||function(){};return t.onPress=function(){var t=n();t&&t.then?t.then(function(){e()}):e()},t});return u.default.render(i.default.createElement(c.default,{visible:!0,operation:!0,transparent:!0,prefixCls:r,transitionName:"am-zoom",closable:!1,maskClosable:!0,onClose:e,footer:a,maskTransitionName:"am-fade",className:"am-modal-operation",platform:n}),o),{close:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1),i=r(a),l=n(11),u=r(l),s=n(40),c=r(s);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){function r(e){var t=e.target,n=t.getAttribute("type");h[n]=t.value}function o(){u.default.unmountComponentAtNode(y),y&&y.parentNode&&y.parentNode.removeChild(y)}function a(e){var t=h.text||s||"",n=h.password||"";return"login-password"===l?e(t,n):e("secure-text"===l?n||s:t)}var l=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"default",s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",f=arguments.length>5&&void 0!==arguments[5]?arguments[5]:["",""],d=arguments.length>6&&void 0!==arguments[6]?arguments[6]:"ios";if(!n)return{close:function(){}};var p="am-modal",h={},v=void 0,m=function(e){setTimeout(function(){e&&e.focus()},500)};switch(l){case"login-password":v=i.default.createElement("div",{className:p+"-input-container"},i.default.createElement("div",{className:p+"-input"},i.default.createElement("label",null,i.default.createElement("input",{type:"text",value:h.text,defaultValue:s,ref:function(e){return m(e)},onChange:r,placeholder:f[0]}))),i.default.createElement("div",{className:p+"-input"},i.default.createElement("label",null,i.default.createElement("input",{type:"password",value:h.password,defaultValue:"",onChange:r,placeholder:f[1]}))));break;case"secure-text":v=i.default.createElement("div",{className:p+"-input-container"},i.default.createElement("div",{className:p+"-input"},i.default.createElement("label",null,i.default.createElement("input",{type:"password",value:h.password,defaultValue:"",ref:function(e){return m(e)},onChange:r,placeholder:f[0]}))));break;case"plain-text":case"default":default:v=i.default.createElement("div",{className:p+"-input-container"},i.default.createElement("div",{className:p+"-input"},i.default.createElement("label",null,i.default.createElement("input",{type:"text",value:h.text,defaultValue:s,ref:function(e){return m(e)},onChange:r,placeholder:f[0]}))))}var g=i.default.createElement("div",null,t,v),y=document.createElement("div");document.body.appendChild(y);var b=void 0;b="function"==typeof n?[{text:"\u53d6\u6d88"},{text:"\u786e\u5b9a",onPress:function(){a(n)}}]:n.map(function(e){return{text:e.text,onPress:function(){if(e.onPress)return a(e.onPress)}}});var _=b.map(function(e){var t=e.onPress||function(){};return e.onPress=function(){var e=t();e&&e.then?e.then(function(){o()}):o()},e});return u.default.render(i.default.createElement(c.default,{visible:!0,transparent:!0,prefixCls:p,title:e,closable:!1,maskClosable:!1,transitionName:"am-zoom",footer:_,maskTransitionName:"am-fade",platform:d},i.default.createElement("div",{style:{zoom:1,overflow:"hidden"}},g)),y),{close:o}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(1),i=r(a),l=n(11),u=r(l),s=n(40),c=r(s);e.exports=t.default},[441,325],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(14),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.children,o=e.mode,i=e.iconName,l=e.leftContent,u=e.rightContent,s=e.onLeftClick,c=_(e,["prefixCls","className","children","mode","iconName","leftContent","rightContent","onLeftClick"]),f=(0,g.default)(t,t+"-"+o,n);return v.default.createElement("div",(0,a.default)({},c,{className:f}),v.default.createElement("div",{className:t+"-left",role:"button",onClick:s},v.default.createElement("span",{className:t+"-left-icon","aria-hidden":"true"},"string"==typeof i?v.default.createElement(b.default,{type:i}):i),v.default.createElement("span",{className:t+"-left-content"},l)),v.default.createElement("div",{className:t+"-title"},r),v.default.createElement("div",{className:t+"-right"},u))}}]),t}(v.default.Component);t.default=C,C.defaultProps={prefixCls:"am-navbar",mode:"dark",iconName:"left",onLeftClick:function(){}},e.exports=t.default},[442,326],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(11),g=r(m),y=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={animatedWidth:0,overflowWidth:0},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentDidMount",value:function(){this._measureText(),this._startAnimation()}},{key:"componentDidUpdate",value:function(){this._measureText(),this._marqueeTimer||this._startAnimation()}},{key:"componentWillUnmount",value:function(){clearTimeout(this._marqueeTimer)}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.className,o=t.text,i=(0,a.default)({position:"relative",right:this.state.animatedWidth,whiteSpace:"nowrap",display:"inline-block"},this.props.style);return v.default.createElement("div",{className:n+"-marquee-wrap "+r,style:{overflow:"hidden"},role:"marquee"},v.default.createElement("div",{ref:function(t){return e.textRef=t},className:n+"-marquee",style:i},o," "))}},{key:"_startAnimation",value:function(){var e=this;this._marqueeTimer&&clearTimeout(this._marqueeTimer);var t=this.props.fps,n=1/t*1e3,r=0===this.state.animatedWidth,o=r?this.props.leading:n,a=function t(){var r=e.state.overflowWidth,o=e.state.animatedWidth+1,a=o>r;if(a){if(!e.props.loop)return;o=0}a&&e.props.trailing?e._marqueeTimer=setTimeout(function(){e.setState({animatedWidth:o}),e._marqueeTimer=setTimeout(t,n)},e.props.trailing):(e.setState({animatedWidth:o}),e._marqueeTimer=setTimeout(t,n))};0!==this.state.overflowWidth&&(this._marqueeTimer=setTimeout(a,o))}},{key:"_measureText",value:function(){var e=g.default.findDOMNode(this),t=this.textRef;if(e&&t){var n=e.offsetWidth,r=t.offsetWidth,o=r-n;o!==this.state.overflowWidth&&this.setState({overflowWidth:o})}}}]),t}(v.default.Component);t.default=y,y.defaultProps={text:"",loop:!1,leading:500,trailing:800,fps:40,className:""},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(14),b=r(y),_=n(193),C=r(_),x=function(e,t){
var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},S=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onClick=function(){var e=n.props,t=e.mode,r=e.onClick;r&&r(),"closable"===t&&n.setState({show:!1})},n.state={show:!0},n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.mode,n=e.icon,r=e.onClick,o=e.children,i=e.className,l=e.prefixCls,u=e.marqueeProps,s=x(e,["mode","icon","onClick","children","className","prefixCls","marqueeProps"]),c={},f=null;"closable"===t?f=v.default.createElement("div",{className:l+"-operation",onClick:this.onClick,role:"button","aria-label":"close"},v.default.createElement(b.default,{type:"cross",size:"md"})):("link"===t&&(f=v.default.createElement("div",{className:l+"-operation",role:"button","aria-label":"go to detail"},v.default.createElement(b.default,{type:"right",size:"md"}))),c.onClick=r);var d=(0,g.default)(l,i);return this.state.show?v.default.createElement("div",(0,a.default)({className:d},s,c,{role:"alert"}),n&&v.default.createElement("div",{className:l+"-icon","aria-hidden":"true"}," ",n," "),v.default.createElement("div",{className:l+"-content"},v.default.createElement(C.default,(0,a.default)({prefixCls:l,text:o},u))),f):null}}]),t}(v.default.Component);t.default=S,S.defaultProps={prefixCls:"am-notice-bar",mode:"",icon:v.default.createElement(b.default,{type:"voice",size:"xxs"}),onClick:function(){}},e.exports=t.default},[442,327],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(10),g=r(m),y=n(7),b=r(y),_=n(49),C=r(_),x=n(33),S=r(x),O=n(32),k=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={current:e.current},n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillReceiveProps",value:function(e){e.current!==this.state.current&&this.setState({current:e.current})}},{key:"onChange",value:function(e){this.setState({current:e}),this.props.onChange&&this.props.onChange(e)}},{key:"render",value:function(){var e=this,t=this.props,r=t.prefixCls,o=t.className,i=t.style,l=t.mode,u=t.total,s=t.simple,c=this.state.current,f=(0,O.getComponentLocale)(this.props,this.context,"Pagination",function(){return n(197)}),d=f.prevText,p=f.nextText,h=v.default.createElement(S.default,null,v.default.createElement(S.default.Item,{className:r+"-wrap-btn "+r+"-wrap-btn-prev"},v.default.createElement(C.default,{inline:!0,disabled:c<=1,onClick:function(){return e.onChange(c-1)}},d)),this.props.children?v.default.createElement(S.default.Item,null,this.props.children):!s&&v.default.createElement(S.default.Item,{className:r+"-wrap","aria-live":"assertive"},v.default.createElement("span",{className:"active"},c),"/",v.default.createElement("span",null,u)),v.default.createElement(S.default.Item,{className:r+"-wrap-btn "+r+"-wrap-btn-next"},v.default.createElement(C.default,{inline:!0,disabled:c>=u,onClick:function(){return e.onChange(e.state.current+1)}},p)));if("number"===l)h=v.default.createElement("div",{className:r+"-wrap"},v.default.createElement("span",{className:"active"},c),"/",v.default.createElement("span",null,u));else if("pointer"===l){for(var m=[],g=0;g<u;g++)m.push(v.default.createElement("div",{key:"dot-"+g,className:(0,b.default)(r+"-wrap-dot",(0,a.default)({},r+"-wrap-dot-active",g+1===c))},v.default.createElement("span",null)));h=v.default.createElement("div",{className:r+"-wrap"},m)}var y=(0,b.default)(r,o);return v.default.createElement("div",{className:y,style:i},h)}}]),t}(v.default.Component);t.default=k,k.defaultProps={prefixCls:"am-pagination",mode:"button",current:1,total:0,simple:!1,onChange:function(){}},k.contextTypes={antLocale:g.default.object},e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={prevText:"\u4e0a\u4e00\u9875",nextText:"\u4e0b\u4e00\u9875"},e.exports=t.default},function(e,t,n){"use strict";n(9),n(50),n(34),n(328)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){return{prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",cols:3,cascade:!0,value:[],onChange:function(){}}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=r(a),l=n(5),u=r(l),s=n(4),c=r(s),f=n(3),d=r(f),p=n(1),h=r(p),v=n(118),m=r(v),g=n(46),y=r(g),b=n(47),_=r(b),C=function(e){function t(){(0,i.default)(this,t);var e=(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getCol=function(){var t=e.props,n=t.data,r=t.pickerPrefixCls,o=t.indicatorStyle,a=t.itemStyle;return n.map(function(e,t){return h.default.createElement(_.default,{key:t,prefixCls:r,style:{flex:1},indicatorStyle:o,itemStyle:a},e.map(function(e){return h.default.createElement(_.default.Item,{key:e.value,value:e.value},e.label)}))})},e}return(0,d.default)(t,e),(0,u.default)(t,[{key:"render",value:function(){var e=this.props,t=void 0;return t=e.cascade?h.default.createElement(m.default,{prefixCls:e.prefixCls,pickerPrefixCls:e.pickerPrefixCls,data:e.data,value:e.value,onChange:e.onChange,onScrollChange:e.onScrollChange,cols:e.cols,indicatorStyle:e.indicatorStyle,pickerItemStyle:e.itemStyle}):h.default.createElement(y.default,{prefixCls:e.prefixCls,selectedValue:e.value,onValueChange:e.onChange,onScrollChange:e.onScrollChange,style:{flexDirection:"row"}},this.getCol())}}]),t}(h.default.Component);t.default=C,C.defaultProps=o(),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(199),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){var e=function(e){return e.join(",")};return{triggerType:"onClick",prefixCls:"am-picker",pickerPrefixCls:"am-picker-col",popupPrefixCls:"am-picker-popup",format:e,cols:3,cascade:!0,extra:"\u8bf7\u9009\u62e9",okText:"\u786e\u5b9a",dismissText:"\u53d6\u6d88",title:""}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(2),u=r(l),s=n(5),c=r(s),f=n(4),d=r(f),p=n(3),h=r(p);t.getDefaultProps=o;var v=n(1),m=r(v),g=n(403),y=r(g),b=n(118),_=r(b),C=n(46),x=r(C),S=n(47),O=r(S),k=n(79),w=r(k),P=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},T=function(e){function t(){(0,u.default)(this,t);var e=(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getSel=function(){var t=e.props.value||[],n=void 0;return n=e.props.cascade?(0,w.default)(e.props.data,function(e,n){return e.value===t[n]}):t.map(function(t,n){return e.props.data[n].filter(function(e){return e.value===t})[0]}),e.props.format&&e.props.format(n.map(function(e){return e.label}))},e.getPickerCol=function(){var t=e.props,n=t.data,r=t.pickerPrefixCls,o=t.itemStyle,a=t.indicatorStyle;return n.map(function(e,t){return m.default.createElement(O.default,{key:t,prefixCls:r,style:{flex:1},itemStyle:o,indicatorStyle:a},e.map(function(e){return m.default.createElement(O.default.Item,{key:e.value,value:e.value},e.label)}))})},e.onOk=function(t){void 0!==e.scrollValue&&(t=e.scrollValue),e.props.onChange&&e.props.onChange(t),e.props.onOk&&e.props.onOk(t)},e.setScrollValue=function(t){e.scrollValue=t},e.fixOnOk=function(t){t.onOk=e.onOk},e}return(0,h.default)(t,e),(0,c.default)(t,[{key:"render",value:function(){var e=this.props,t=e.children,n=e.value,r=void 0===n?[]:n,o=e.extra,a=e.okText,l=e.dismissText,u=e.popupPrefixCls,s=e.itemStyle,c=e.indicatorStyle,f=e.cascade,d=e.prefixCls,p=e.pickerPrefixCls,h=e.data,v=e.cols,g=e.onPickerChange,b=(e.onOk,P(e,["children","value","extra","okText","dismissText","popupPrefixCls","itemStyle","indicatorStyle","cascade","prefixCls","pickerPrefixCls","data","cols","onPickerChange","onOk"])),C=void 0,S={};return f?C=m.default.createElement(_.default,{prefixCls:d,pickerPrefixCls:p,data:h,cols:v,onChange:g,onScrollChange:this.setScrollValue,pickerItemStyle:s,indicatorStyle:c}):(C=m.default.createElement(x.default,{style:{flexDirection:"row",alignItems:"center"},prefixCls:d,onScrollChange:this.setScrollValue},this.getPickerCol()),S={pickerValueProp:"selectedValue",pickerValueChangeProp:"onValueChange"}),m.default.createElement(y.default,(0,i.default)({cascader:C},this.popupProps,b,{prefixCls:u,value:r,dismissText:l,okText:a},S,{ref:this.fixOnOk}),t&&m.default.cloneElement(t,{extra:this.getSel()||o}))}}]),t}(m.default.Component);t.default=T},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(4),l=r(i),u=n(3),s=r(u),c=n(201),f=r(c),d=n(203),p=r(d),h=function(e){function t(){(0,a.default)(this,t);var e=(0,l.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.popupProps=p.default,e}return(0,s.default)(t,e),t}(f.default);t.default=h,h.defaultProps=(0,c.getDefaultProps)(),e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={WrapComponent:"div",transitionName:"am-slide-up",maskTransitionName:"am-fade"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(12),C=r(_),x=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},S=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this.props,t=e.children,n=e.className,r=e.prefixCls,o=e.icon,i=e.disabled,u=e.firstItem,s=e.activeStyle,c=x(e,["children","className","prefixCls","icon","disabled","firstItem","activeStyle"]),f=(0,b.default)(r+"-item",n,(0,l.default)({},r+"-item-disabled",i)),d=r+"-item-active ";return u&&(d+=r+"-item-fix-active-arrow"),g.default.createElement(C.default,{disabled:i,activeClassName:d,activeStyle:s},g.default.createElement("div",(0,a.default)({className:f},c),g.default.createElement("div",{className:r+"-item-container"},o?g.default.createElement("span",{className:r+"-item-icon","aria-hidden":"true"},o):null,g.default.createElement("span",{className:r+"-item-content"},t))))}}]),t}(g.default.Component);t.default=S,S.defaultProps={prefixCls:"am-popover",disabled:!1},S.myName="PopoverItem",e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(e,t){return e};return m.default.Children.map(e,function(e,n){var r=t(e,n);return r&&r.props&&r.props.children?m.default.cloneElement(r,{},o(r.props.children,t)):r})}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(2),u=r(l),s=n(5),c=r(s),f=n(4),d=r(f),p=n(3),h=r(p),v=n(1),m=r(v),g=n(432),y=r(g),b=n(204),_=r(b),C=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},x=function(e){function t(){return(0,u.default)(this,t),(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,h.default)(t,e),(0,c.default)(t,[{key:"render",value:function(){var e=this.props,t=e.overlay,n=e.onSelect,r=void 0===n?function(){}:n,a=C(e,["overlay","onSelect"]),l=o(t,function(e,t){var n={firstItem:!1};return e&&e.type&&"PopoverItem"===e.type.myName&&!e.props.disabled?(n.onClick=function(){return r(e,t)},n.firstItem=0===t,m.default.cloneElement(e,n)):e});return m.default.createElement(y.default,(0,i.default)({},a,{overlay:l}))}}]),t}(m.default.Component);t.default=x,x.defaultProps={prefixCls:"am-popover",placement:"bottomRight",align:{overflow:{adjustY:0,adjustX:0}},trigger:["click"]},x.Item=_.default,e.exports=t.default},[441,331],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentWillReceiveProps",value:function(){this.noAppearTransition=!0}},{key:"componentDidMount",value:function(){var e=this;this.props.appearTransition&&setTimeout(function(){e.barRef.style.width=e.props.percent+"%"},10)}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.className,o=n.prefixCls,i=n.position,u=n.unfilled,s=n.style,c=void 0===s?{}:s,f=n.barStyle,d=void 0===f?{}:f,p={width:this.noAppearTransition||!this.props.appearTransition?this.props.percent+"%":0,height:0},h=(0,b.default)(o+"-outer",r,(e={},(0,l.default)(e,o+"-fixed-outer","fixed"===i),(0,l.default)(e,o+"-hide-outer",!u),e));return g.default.createElement("div",{style:c,className:h,role:"progressbar","aria-valuenow":this.props.percent,"aria-valuemin":"0","aria-valuemax":"100"},g.default.createElement("div",{ref:function(e){return t.barRef=e},className:o+"-bar",style:(0,a.default)({},d,p)}))}}]),t}(g.default.Component);t.default=_,_.defaultProps={prefixCls:"am-progress",percent:0,position:"fixed",unfilled:!0,appearTransition:!1},e.exports=t.default},[441,332],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(8),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v),g=n(1),y=r(g),b=n(7),_=r(b),C=n(26),x=r(C),S=n(54),O=r(S),k=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},w=x.default.Item,P=function(e){function t(){return(0,c.default)(this,t),(0,h.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,m.default)(t,e),(0,d.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.listPrefixCls,r=(t.onChange,t.disabled),a=t.radioProps,l=t.onClick,s=k(t,["listPrefixCls","onChange","disabled","radioProps","onClick"]),c=s.prefixCls,f=s.className,d=s.children,p=(0,_.default)(c+"-item",f,(0,u.default)({},c+"-item-disabled",r===!0));r||(s.onClick=l||o);var h={};return["name","defaultChecked","checked","onChange","disabled"].forEach(function(t){t in e.props&&(h[t]=e.props[t])}),y.default.createElement(w,(0,i.default)({},s,{prefixCls:n,className:p,extra:y.default.createElement(O.default,(0,i.default)({},a,h))}),d)}}]),t}(y.default.Component);t.default=P,P.defaultProps={prefixCls:"am-radio",listPrefixCls:"am-list",radioProps:{}},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(54),a=r(o),i=n(209),l=r(i);a.default.RadioItem=l.default,t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(379),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement("div",{className:this.props.prefixCls+"-wrapper"},p.default.createElement(v.default,this.props))}}]),t}(p.default.Component);t.default=m,m.defaultProps={prefixCls:"am-slider"},e.exports=t.default},[441,334],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(1),l=r(i),u=n(77),s=r(u),c=n(14),f=r(c);s.default.RefreshControl.defaultProps=(0,a.default)({},s.default.RefreshControl.defaultProps,{prefixCls:"am-refresh-control",icon:[l.default.createElement("div",{key:"0",className:"am-refresh-control-pull"},l.default.createElement("span",null,"\u4e0b\u62c9\u53ef\u4ee5\u5237\u65b0")),l.default.createElement("div",{key:"1",className:"am-refresh-control-release"},l.default.createElement("span",null,"\u677e\u5f00\u7acb\u5373\u5237\u65b0"))],loading:l.default.createElement(f.default,{type:"loading"}),refreshing:!1,distanceToRefresh:25}),t.default=s.default.RefreshControl,e.exports=t.default},[442,335],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(49),v=r(h),m=n(7),g=r(m),y=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.className,r=e.img,o=e.imgUrl,a=e.title,i=e.message,l=e.buttonText,u=e.onButtonClick,s=e.buttonType,c=e.style,f=(0,g.default)(t,n),d=null;return r?d=p.default.createElement("div",{className:t+"-pic"},r):o&&(d=p.default.createElement("div",{className:t+"-pic",style:{backgroundImage:"url("+o+")"}})),p.default.createElement("div",{className:f,style:c,role:"alert"},d,a?p.default.createElement("div",{className:t+"-title"},a):null,i?p.default.createElement("div",{className:t+"-message"},i):null,l?p.default.createElement("div",{className:t+"-button"},p.default.createElement(v.default,{type:s,onClick:u},l)):null)}}]),t}(p.default.Component);t.default=y,y.defaultProps={prefixCls:"am-result",buttonType:"",onButtonClick:function(){}},e.exports=t.default},function(e,t,n){"use strict";n(9),n(50),n(336)},function(e,t){"use strict";function n(){}Object.defineProperty(t,"__esModule",{value:!0});t.defaultProps={prefixCls:"am-search",placeholder:"",onSubmit:n,onChange:n,onFocus:n,onBlur:n,onClear:n,showCancelButton:!1,cancelText:"\u53d6\u6d88",disabled:!1}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(217),C=n(31),x=r(C),S=n(12),O=r(S),k=function(e){function t(e){(0,s.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onSubmit=function(e){e.preventDefault(),n.props.onSubmit&&n.props.onSubmit(n.state.value),n.inputRef.blur()},n.onChange=function(e){n.state.focus||n.setState({focus:!0});var t=e.target.value;"value"in n.props||n.setState({value:t}),n.props.onChange&&n.props.onChange(t)},n.onFocus=function(){n.setState({focus:!0}),n.firstFocus=!0,"focused"in n.props||n.setState({focused:!0}),n.props.onFocus&&n.props.onFocus(),"input"===document.activeElement.tagName.toLowerCase()&&(n.scrollIntoViewTimeout=setTimeout(function(){try{document.activeElement.scrollIntoViewIfNeeded()}catch(e){}},100))},n.onBlur=function(){n.onBlurTimeout=setTimeout(function(){n.blurFromOnClear||n.setState({focus:!1}),n.blurFromOnClear=!1},50),"focused"in n.props||n.setState({focused:!1}),n.props.onBlur&&n.props.onBlur()},n.onClear=function(){n.doClear()},n.doClear=function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];n.blurFromOnClear=e,"value"in n.props||n.setState({value:""}),n.props.onClear&&n.props.onClear(""),n.props.onChange&&n.props.onChange(""),e&&n.inputRef.focus()},n.onCancel=function(){n.props.onCancel?n.props.onCancel(n.state.value):n.doClear(!1)};var r=void 0;return r="value"in e?e.value||"":"defaultValue"in e?e.defaultValue:"",n.state={value:r,focus:!1,focused:e.focused||!1},n}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentDidMount",value:function(){var e=window.getComputedStyle(this.rightBtnRef);this.rightBtnInitMarginleft=e["margin-left"],(this.props.autoFocus||this.state.focused)&&navigator.userAgent.indexOf("AlipayClient")>0&&this.inputRef.focus(),this.componentDidUpdate()}},{key:"componentDidUpdate",value:function(){var e=this.syntheticPhContainerRef.getBoundingClientRect().width;this.inputContainerRef.className.indexOf(this.props.prefixCls+"-start")>-1?(this.syntheticPhRef.style.width=Math.ceil(e)+"px",this.props.showCancelButton||(this.rightBtnRef.style.marginRight=0)):(this.syntheticPhRef.style.width="100%",this.props.showCancelButton||(this.rightBtnRef.style.marginRight="-"+(this.rightBtnRef.offsetWidth+parseInt(this.rightBtnInitMarginleft,10))+"px")),this.state.focused&&this.inputRef.focus()}},{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value}),"focused"in e&&this.setState({focused:e.focused})}},{key:"componentWillUnmount",value:function(){this.scrollIntoViewTimeout&&(clearTimeout(this.scrollIntoViewTimeout),this.scrollIntoViewTimeout=null),this.onBlurTimeout&&(clearTimeout(this.onBlurTimeout),this.onBlurTimeout=null)}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.showCancelButton,i=n.disabled,u=n.placeholder,s=n.cancelText,c=n.className,f=n.style,d=n.maxLength,p=this.state,h=p.value,v=p.focus,m=(0,b.default)(r,c,(0,l.default)({},r+"-start",!!(v||h&&h.length>0))),y=(0,b.default)(r+"-clear",(0,l.default)({},r+"-clear-show",!!(v&&h&&h.length>0))),_=(0,b.default)(r+"-cancel",(e={},(0,l.default)(e,r+"-cancel-show",o||v||h&&h.length>0),(0,l.default)(e,r+"-cancel-anim",this.firstFocus),e));return g.default.createElement("form",{onSubmit:this.onSubmit,className:m,style:f,ref:function(e){return t.inputContainerRef=e},action:"#"},g.default.createElement("div",{className:r+"-input"},g.default.createElement("div",{className:r+"-synthetic-ph",ref:function(e){return t.syntheticPhRef=e}},g.default.createElement("span",{className:r+"-synthetic-ph-container",ref:function(e){return t.syntheticPhContainerRef=e}},g.default.createElement("i",{className:r+"-synthetic-ph-icon"}),g.default.createElement("span",{className:r+"-synthetic-ph-placeholder",style:{visibility:u&&!h?"visible":"hidden"}},u))),g.default.createElement("input",(0,a.default)({type:"search",className:r+"-value",value:h,disabled:i,placeholder:u,onChange:this.onChange,onFocus:this.onFocus,onBlur:this.onBlur,ref:function(e){return t.inputRef=e},maxLength:d},(0,x.default)(this.props))),g.default.createElement(O.default,{activeClassName:r+"-clear-active"},g.default.createElement("a",{onClick:this.onClear,className:y}))),g.default.createElement("div",{className:_,onClick:this.onCancel,ref:function(e){return t.rightBtnRef=e}},s))}}]),t}(g.default.Component);t.default=k,k.defaultProps=_.defaultProps,e.exports=t.default},[441,337],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(12),b=r(y),_=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={selectedIndex:e.selectedIndex},n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillReceiveProps",value:function(e){e.selectedIndex!==this.state.selectedIndex&&this.setState({selectedIndex:e.selectedIndex})}},{key:"onClick",value:function(e,t,n){var r=this.props,o=r.disabled,a=r.onChange,i=r.onValueChange;o||this.state.selectedIndex===t||(e.nativeEvent=e.nativeEvent?e.nativeEvent:{},e.nativeEvent.selectedSegmentIndex=t,e.nativeEvent.value=n,a&&a(e),i&&i(n),this.setState({selectedIndex:t}))}},{key:"renderSegmentItem",value:function(e,t,n){var r=this,o=this.props,i=o.prefixCls,l=o.disabled,u=o.tintColor,s=(0,g.default)(i+"-item",(0,a.default)({},i+"-item-selected",n)),c={color:n?"#fff":u,backgroundColor:n?u:"transparent",borderColor:u},f=u?{backgroundColor:u}:{};return v.default.createElement(b.default,{key:e,disabled:l,activeClassName:i+"-item-active"},v.default.createElement("div",{className:s,style:c,role:"tab","aria-selected":n&&!l,"aria-disabled":l,onClick:l?void 0:function(n){return r.onClick(n,e,t)}},v.default.createElement("div",{className:i+"-item-inner",style:f}),t))}},{key:"render",value:function(){var e=this,t=this.props,n=t.className,r=t.prefixCls,o=t.style,i=t.disabled,l=t.values,u=void 0===l?[]:l,s=(0,g.default)(n,r,(0,a.default)({},r+"-disabled",i));return v.default.createElement("div",{className:s,style:o,role:"tablist"},u.map(function(t,n){return e.renderSegmentItem(n,t,n===e.state.selectedIndex)}))}}]),t}(v.default.Component);t.default=_,_.defaultProps={prefixCls:"am-segment",selectedIndex:0,disabled:!1,values:[],onChange:function(){},onValueChange:function(){},style:{},tintColor:""},e.exports=t.default},[441,338],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(380),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement("div",{className:this.props.prefixCls+"-wrapper"},p.default.createElement(v.default,this.props))}}]),t}(p.default.Component);t.default=m,m.defaultProps={prefixCls:"am-slider"},e.exports=t.default},[444,339],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(412),C=r(_),x=n(14),S=r(x),O=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},k=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this,t=this.props,n=t.className,r=t.showNumber,o=O(t,["className","showNumber"]),i=(0,b.default)(n,(0,l.default)({},"showNumber",!!r));return g.default.createElement(C.default,(0,a.default)({upHandler:g.default.createElement(S.default,{type:"plus",size:"xxs"}),downHandler:g.default.createElement(S.default,{type:"minus",size:"xxs"})},o,{ref:function(t){return e.stepperRef=t},className:i}))}}]),t}(g.default.Component);t.default=k,k.defaultProps={prefixCls:"am-stepper",step:1,readOnly:!1,showNumber:!1,focusOnUpDown:!1,useTouch:!0},e.exports=t.default},[442,340],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(425),g=r(m),y=n(14),b=r(y),_=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentDidUpdate",value:function(){"horizontal"===this.props.direction&&this.stepRefs.forEach(function(e){e.refs.tail&&(e.refs.tail.style.left=e.refs.main.offsetWidth/2+"px")})}},{key:"render",value:function(){var e=this;this.stepRefs=[];var t=this.props,n=t.children,r=t.status,o=t.size,i=this.props.current,l=v.default.Children.map(n,function(e){return e});return l=v.default.Children.map(l,function(t,n){var a=t.props.className;n<l.length-1&&"error"===l[n+1].props.status&&(a=a?a+" error-tail":"error-tail");var u=t.props.icon;return u||(n<i?u="check-circle-o":n>i&&(u="ellipsis",a=a?a+" ellipsis-item":"ellipsis-item"),("error"===r&&n===i||"error"===t.props.status)&&(u="cross-circle-o")),u="string"==typeof u?v.default.createElement(b.default,{type:u,size:"small"===o?"wait"===r?"xxs":"xs":"md"}):u,v.default.cloneElement(t,{icon:u,className:a,ref:function(t){return e.stepRefs[n]=t}})}),v.default.createElement(g.default,(0,a.default)({ref:function(t){return e.stepsRef=t}},this.props),l)}}]),t}(v.default.Component);t.default=_,_.Step=g.default.Step,_.defaultProps={prefixCls:"am-steps",iconPrefix:"ant",labelPlacement:"vertical",direction:"vertical",current:0},e.exports=t.default},[442,341],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(385),v=r(h),m=n(7),g=r(m),y=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.style,r=e.prefixCls,o=e.left,a=void 0===o?[]:o,i=e.right,l=void 0===i?[]:i,u=e.autoClose,s=e.disabled,c=e.onOpen,f=e.onClose,d=e.children,h=(0,g.default)(r,t);return a.length||l.length?p.default.createElement("div",{style:n,className:t},p.default.createElement(v.default,{prefixCls:r,left:a,right:l,autoClose:u,disabled:s,onOpen:c,onClose:f},d)):p.default.createElement("div",{style:n,className:h},d)}}]),t}(p.default.Component);y.defaultProps={prefixCls:"am-swipe",title:"\u8bf7\u786e\u8ba4\u64cd\u4f5c",autoClose:!1,disabled:!1,left:[],right:[],onOpen:function(){},onClose:function(){}},t.default=y,e.exports=t.default},[441,343],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){(0,s.default)(this,t);var e=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onChange=function(t){var n=t.target.checked;e.props.onChange&&e.props.onChange(n)},e.onClick=function(t){if(e.props.onClick){var n=void 0;n=t&&t.target&&void 0!==t.target.checked?t.target.checked:e.props.checked,e.props.onClick(n)}},e}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.name,r=e.checked,o=e.disabled,i=e.className,u=e.platform,s=e.color,c=_(e,["prefixCls","name","checked","disabled","className","platform","color"]),f=(0,b.default)(t,i,(0,l.default)({},t+"-android","android"===u)),d=(0,b.default)("checkbox",(0,l.default)({},"checkbox-disabled",o)),p=Object.keys(c).reduce(function(e,t){return"aria-"!==t.substr(0,5)&&"data-"!==t.substr(0,5)&&"role"!==t||(e[t]=c[t]),
e},{}),h=this.props.style||{};return s&&r&&(h.backgroundColor=s),g.default.createElement("label",{className:f},g.default.createElement("input",(0,a.default)({type:"checkbox",name:n,className:t+"-checkbox",disabled:o,checked:r,onChange:this.onChange,value:r?"on":"off"},o?{}:{onClick:this.onClick},p)),g.default.createElement("div",(0,a.default)({className:d,style:h},o?{onClick:this.onClick}:{})))}}]),t}(g.default.Component);t.default=C,C.defaultProps={prefixCls:"am-switch",name:"",checked:!1,disabled:!1,onChange:function(){},platform:"ios",onClick:function(){}},e.exports=t.default},[441,344],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(80),g=r(m),y=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.renderIcon=function(){var t=e.props,n=t.dot,r=t.badge,o=t.selected,a=t.selectedIcon,i=t.icon,l=t.title,u=t.prefixCls,s=o?a:i,c=v.default.isValidElement(s)?s:v.default.createElement("img",{className:u+"-image",src:s.uri||s,alt:l});return r?v.default.createElement(g.default,{text:r,className:u+"-badge tab-badge"}," ",c," "):n?v.default.createElement(g.default,{dot:!0,className:u+"-badge tab-dot"},c):c},e.onClick=function(){var t=e.props.onClick;t&&t()},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.title,n=e.prefixCls,r=e.selected,o=e.unselectedTintColor,i=e.tintColor,l=r?i:o;return v.default.createElement("div",(0,a.default)({},this.props.dataAttrs,{onClick:this.onClick,className:""+n}),v.default.createElement("div",{className:n+"-icon",style:{color:l}},this.renderIcon()),v.default.createElement("p",{className:n+"-title",style:{color:r?i:o}},t))}}]),t}(v.default.PureComponent);t.default=y,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Item=void 0;var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(87),g=r(m),y=n(232),b=r(y),_=n(31),C=r(_),x=t.Item=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){return v.default.createElement("div",null,this.props.children)}}]),t}(v.default.Component),S=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getTabs=function(){return v.default.Children.map(e.props.children,function(e){return(0,a.default)({},e.props)})},e.renderTabBar=function(){var t=e.props,n=t.barTintColor,r=t.prefixCls,o=t.tintColor,a=t.unselectedTintColor,i=e.getTabs(),l=i.map(function(t,n){return v.default.createElement(b.default,{key:n,prefixCls:e.props.prefixCls+"-tab",badge:t.badge,dot:t.dot,selected:t.selected,icon:t.icon,selectedIcon:t.selectedIcon,title:t.title,tintColor:o,unselectedTintColor:a,dataAttrs:(0,C.default)(t),onClick:function(){return t.onPress&&t.onPress()}})});return v.default.createElement("div",{className:r+"-bar",style:{backgroundColor:n}},l)},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e=this.props,t=e.children,n=e.hidden,r=this.getTabs(),o=0;return r.forEach(function(e,t){e.selected&&(o=t)}),v.default.createElement("div",{className:this.props.prefixCls},v.default.createElement(g.default,{tabs:r,renderTabBar:!n&&this.renderTabBar,tabBarPosition:"bottom",page:o<0?void 0:o,animated:!1,swipeable:!1},t))}}]),t}(v.default.Component);S.defaultProps={prefixCls:"am-tab-bar",barTintColor:"white",tintColor:"#108ee9",hidden:!1,unselectedTintColor:"#888",placeholder:"\u6b63\u5728\u52a0\u8f7d"},S.Item=x,t.default=S},function(e,t,n){"use strict";n(9),n(88),n(345),n(81)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=n(14),C=r(_),x=n(31),S=r(x),O=n(12),k=r(O),w=function(e){function t(e){(0,s.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onClick=function(){var e=n.props,t=e.disabled,r=e.onChange;if(!t){var o=n.state.selected;n.setState({selected:!o},function(){r&&r(!o)})}},n.onTagClose=function(){n.props.onClose&&n.props.onClose(),n.setState({closed:!0},n.props.afterClose)},n.state={selected:e.selected,closed:!1},n}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentWillReceiveProps",value:function(e){this.props.selected!==e.selected&&this.setState({selected:e.selected})}},{key:"render",value:function(){var e,t=this.props,n=t.children,r=t.className,o=t.prefixCls,i=t.disabled,u=t.closable,s=t.small,c=t.style,f=(0,b.default)(r,o,(e={},(0,l.default)(e,o+"-normal",!i&&(!this.state.selected||s||u)),(0,l.default)(e,o+"-small",s),(0,l.default)(e,o+"-active",this.state.selected&&!i&&!s&&!u),(0,l.default)(e,o+"-disabled",i),(0,l.default)(e,o+"-closable",u),e)),d=!u||i||s?null:g.default.createElement(k.default,{activeClassName:o+"-close-active"},g.default.createElement("div",{className:o+"-close",role:"button",onClick:this.onTagClose,"aria-label":"remove tag"},g.default.createElement(C.default,{type:"cross-circle",size:"xs","aria-hidden":"true"})));return this.state.closed?null:g.default.createElement("div",(0,a.default)({},(0,S.default)(this.props),{className:f,onClick:this.onClick,style:c}),g.default.createElement("div",{className:o+"-text"},n),d)}}]),t}(g.default.Component);t.default=w,w.defaultProps={prefixCls:"am-tag",disabled:!1,selected:!1,closable:!1,small:!1,onChange:function(){},onClose:function(){},afterClose:function(){}},e.exports=t.default},[442,347],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(91),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement(v.default,this.props)}}]),t}(p.default.Component);t.default=m,m.defaultProps={Component:"span"},e.exports=t.default},function(e,t){"use strict"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(e){return"undefined"==typeof e||null===e?"":e}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return e.replace(w,"_").length}Object.defineProperty(t,"__esModule",{value:!0});var l=n(6),u=r(l),s=n(8),c=r(s),f=n(2),d=r(f),p=n(5),h=r(p),v=n(4),m=r(v),g=n(3),y=r(g),b=n(1),_=r(b),C=n(7),x=r(C),S=n(12),O=r(S),k=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},w=/[\uD800-\uDBFF][\uDC00-\uDFFF]|\n/g,P=function(e){function t(){(0,d.default)(this,t);var e=(0,m.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={focus:!1},e.focus=function(){e.textareaRef.focus()},e.onChange=function(t){var n=t.target.value,r=e.props.onChange;r&&r(n),e.componentDidUpdate()},e.onBlur=function(t){e.debounceTimeout=setTimeout(function(){e.setState({focus:!1})},100),e.setState({focus:!1});var n=t.target.value;e.props.onBlur&&e.props.onBlur(n)},e.onFocus=function(t){e.debounceTimeout&&(clearTimeout(e.debounceTimeout),e.debounceTimeout=null),e.setState({focus:!0});var n=t.target.value;e.props.onFocus&&e.props.onFocus(n),"textarea"===document.activeElement.tagName.toLowerCase()&&(e.scrollIntoViewTimeout=setTimeout(function(){try{document.activeElement.scrollIntoViewIfNeeded()}catch(e){}},100))},e.onErrorClick=function(){e.props.onErrorClick&&e.props.onErrorClick()},e.clearInput=function(){e.props.onChange&&e.props.onChange("")},e}return(0,y.default)(t,e),(0,h.default)(t,[{key:"componentDidUpdate",value:function(){if(this.props.autoHeight&&this.state.focus){var e=this.textareaRef;e.style.height="",e.style.height=e.scrollHeight+"px"}}},{key:"componentWillUnmount",value:function(){this.debounceTimeout&&(clearTimeout(this.debounceTimeout),this.debounceTimeout=null),this.scrollIntoViewTimeout&&(clearTimeout(this.scrollIntoViewTimeout),this.scrollIntoViewTimeout=null)}},{key:"render",value:function(){var e,t,n=this,r=this.props,o=r.prefixCls,l=r.prefixListCls,s=r.editable,f=r.style,d=r.clear,p=(r.children,r.error),h=r.className,v=r.count,m=r.labelNumber,g=r.title,y=(r.onErrorClick,r.autoHeight),b=k(r,["prefixCls","prefixListCls","editable","style","clear","children","error","className","count","labelNumber","title","onErrorClick","autoHeight"]),C=b.value,S=b.defaultValue,w=b.disabled,P=void 0;P="value"in this.props?{value:a(C)}:{defaultValue:S};var T=this.state.focus,E=(0,x.default)(h,l+"-item",o+"-item",(e={},(0,c.default)(e,o+"-disabled",w),(0,c.default)(e,o+"-item-single-line",1===this.props.rows&&!y),(0,c.default)(e,o+"-error",p),(0,c.default)(e,o+"-focus",T),e)),M=(0,x.default)(o+"-label",(t={},(0,c.default)(t,o+"-label-2",2===m),(0,c.default)(t,o+"-label-3",3===m),(0,c.default)(t,o+"-label-4",4===m),(0,c.default)(t,o+"-label-5",5===m),(0,c.default)(t,o+"-label-6",6===m),(0,c.default)(t,o+"-label-7",7===m),t)),N=i(C),j={};return v>0&&(j.maxLength=v-N+(C?C.length:0)),_.default.createElement("div",{className:E},g&&_.default.createElement("div",{className:M},g),_.default.createElement("div",{className:o+"-control"},_.default.createElement("textarea",(0,u.default)({ref:function(e){return n.textareaRef=e}},j,b,P,{onChange:this.onChange,onBlur:this.onBlur,onFocus:this.onFocus,readOnly:!s,style:f}))),d&&s&&C&&N>0&&_.default.createElement(O.default,{activeClassName:o+"-clear-active"},_.default.createElement("div",{className:o+"-clear",onClick:this.clearInput,onTouchStart:this.clearInput})),p&&_.default.createElement("div",{className:o+"-error-extra",onClick:this.onErrorClick}),v>0&&this.props.rows>1&&_.default.createElement("span",{className:o+"-count"},_.default.createElement("span",null,C?N:0),"/",v))}}]),t}(_.default.Component);t.default=P,P.defaultProps={prefixCls:"am-textarea",prefixListCls:"am-list",autoHeight:!1,editable:!0,disabled:!1,placeholder:"",clear:!1,rows:1,onChange:o,onBlur:o,onFocus:o,onErrorClick:o,error:!1,labelNumber:5},e.exports=t.default},[443,348],238,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(7),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.size,r=e.className,o=e.style,a=e.onClick,i=(0,v.default)(t,t+"-"+n,r);return p.default.createElement("div",{className:i,style:o,onClick:a})}}]),t}(p.default.Component);t.default=m,m.defaultProps={prefixCls:"am-whitespace",size:"md"},e.exports=t.default},[441,350],function(e,t,n){e.exports={default:n(253),__esModule:!0}},function(e,t,n){e.exports={default:n(254),__esModule:!0}},function(e,t,n){e.exports={default:n(255),__esModule:!0}},function(e,t,n){e.exports={default:n(257),__esModule:!0}},function(e,t,n){e.exports={default:n(258),__esModule:!0}},function(e,t,n){e.exports={default:n(259),__esModule:!0}},function(e,t,n){e.exports={default:n(260),__esModule:!0}},function(e,t,n){e.exports={default:n(261),__esModule:!0}},function(e,t,n){function r(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var o=n(96)}catch(e){var o=n(96)}var a=/\s+/,i=Object.prototype.toString;e.exports=function(e){return new r(e)},r.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array(),n=o(t,e);return~n||t.push(e),this.el.className=t.join(" "),this},r.prototype.remove=function(e){if("[object RegExp]"==i.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=o(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},r.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},r.prototype.toggle=function(e,t){return this.list?("undefined"!=typeof t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):("undefined"!=typeof t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},r.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(a);return""===n[0]&&n.shift(),n},r.prototype.has=r.prototype.contains=function(e){return this.list?this.list.contains(e):!!~o(this.array(),e)}},function(e,t,n){n(107),n(283),e.exports=n(13).Array.from},function(e,t,n){n(285),e.exports=n(13).Object.assign},function(e,t,n){n(286);var r=n(13).Object;e.exports=function(e,t){return r.create(e,t)}},function(e,t,n){n(287);var r=n(13).Object;e.exports=function(e,t,n){return r.defineProperty(e,t,n)}},function(e,t,n){n(288);var r=n(13).Object;e.exports=function(e,t){return r.getOwnPropertyDescriptor(e,t)}},function(e,t,n){n(289),e.exports=n(13).Object.getPrototypeOf},function(e,t,n){n(290),e.exports=n(13).Object.setPrototypeOf},function(e,t,n){n(292),n(291),n(293),n(294),e.exports=n(13).Symbol},function(e,t,n){n(107),n(295),e.exports=n(69).f("iterator")},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t){e.exports=function(){}},function(e,t,n){var r=n(25),o=n(106),a=n(281);e.exports=function(e){return function(t,n,i){var l,u=r(t),s=o(u.length),c=a(i,s);if(e&&n!=n){for(;s>c;)if(l=u[c++],l!=l)return!0}else for(;s>c;c++)if((e||c in u)&&u[c]===n)return e||c||0;return!e&&-1}}},function(e,t,n){var r=n(55),o=n(16)("toStringTag"),a="Arguments"==r(function(){return arguments}()),i=function(e,t){try{return e[t]}catch(e){}};e.exports=function(e){var t,n,l;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=i(t=Object(e),o))?n:a?r(t):"Object"==(l=r(t))&&"function"==typeof t.callee?"Arguments":l}},function(e,t,n){"use strict";var r=n(20),o=n(38);e.exports=function(e,t,n){t in e?r.f(e,t,o(0,n)):e[t]=n}},function(e,t,n){var r=n(41),o=n(62),a=n(42);e.exports=function(e){var t=r(e),n=o.f;if(n)for(var i,l=n(e),u=a.f,s=0;l.length>s;)u.call(e,i=l[s++])&&t.push(i);return t}},function(e,t,n){var r=n(19).document;e.exports=r&&r.documentElement},function(e,t,n){var r=n(37),o=n(16)("iterator"),a=Array.prototype;e.exports=function(e){return void 0!==e&&(r.Array===e||a[o]===e)}},function(e,t,n){var r=n(55);e.exports=Array.isArray||function(e){return"Array"==r(e)}},function(e,t,n){var r=n(27);e.exports=function(e,t,n,o){try{return o?t(r(n)[0],n[1]):t(n)}catch(t){var a=e.return;throw void 0!==a&&r(a.call(e)),t}}},function(e,t,n){"use strict";var r=n(60),o=n(38),a=n(63),i={};n(29)(i,n(16)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(i,{next:o(1,n)}),a(e,t+" Iterator")}},function(e,t,n){var r=n(16)("iterator"),o=!1;try{var a=[7][r]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch(e){}e.exports=function(e,t){if(!t&&!o)return!1;var n=!1;try{var a=[7],i=a[r]();i.next=function(){return{done:n=!0}},a[r]=function(){return i},e(a)}catch(e){}return n}},function(e,t){e.exports=function(e,t){return{value:t,done:!!e}}},function(e,t,n){var r=n(44)("meta"),o=n(36),a=n(24),i=n(20).f,l=0,u=Object.isExtensible||function(){return!0},s=!n(28)(function(){return u(Object.preventExtensions({}))}),c=function(e){i(e,r,{value:{i:"O"+ ++l,w:{}}})},f=function(e,t){if(!o(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!a(e,r)){if(!u(e))return"F";if(!t)return"E";c(e)}return e[r].i},d=function(e,t){if(!a(e,r)){if(!u(e))return!0;if(!t)return!1;c(e)}return e[r].w},p=function(e){return s&&h.NEED&&u(e)&&!a(e,r)&&c(e),e},h=e.exports={KEY:r,NEED:!1,fastKey:f,getWeak:d,onFreeze:p}},function(e,t,n){"use strict";var r=n(41),o=n(62),a=n(42),i=n(43),l=n(99),u=Object.assign;e.exports=!u||n(28)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=i(e),u=arguments.length,s=1,c=o.f,f=a.f;u>s;)for(var d,p=l(arguments[s++]),h=c?r(p).concat(c(p)):r(p),v=h.length,m=0;v>m;)f.call(p,d=h[m++])&&(n[d]=p[d]);return n}:u},function(e,t,n){var r=n(20),o=n(27),a=n(41);e.exports=n(23)?Object.defineProperties:function(e,t){o(e);for(var n,i=a(t),l=i.length,u=0;l>u;)r.f(e,n=i[u++],t[n]);return e}},function(e,t,n){var r=n(25),o=n(101).f,a={}.toString,i="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],l=function(e){try{return o(e)}catch(e){return i.slice()}};e.exports.f=function(e){return i&&"[object Window]"==a.call(e)?l(e):o(r(e))}},function(e,t,n){var r=n(36),o=n(27),a=function(e,t){if(o(e),!r(t)&&null!==t)throw TypeError(t+": can't set as prototype!")};e.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(e,t,r){try{r=n(56)(Function.call,n(61).f(Object.prototype,"__proto__").set,2),r(e,[]),t=!(e instanceof Array)}catch(e){t=!0}return function(e,n){return a(e,n),t?e.__proto__=n:r(e,n),e}}({},!1):void 0),check:a}},function(e,t,n){var r=n(66),o=n(57);e.exports=function(e){return function(t,n){var a,i,l=String(o(t)),u=r(n),s=l.length;return u<0||u>=s?e?"":void 0:(a=l.charCodeAt(u),a<55296||a>56319||u+1===s||(i=l.charCodeAt(u+1))<56320||i>57343?e?l.charAt(u):a:e?l.slice(u,u+2):(a-55296<<10)+(i-56320)+65536)}}},function(e,t,n){var r=n(66),o=Math.max,a=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):a(e,t)}},function(e,t,n){var r=n(265),o=n(16)("iterator"),a=n(37);e.exports=n(13).getIteratorMethod=function(e){if(void 0!=e)return e[o]||e["@@iterator"]||a[r(e)]}},function(e,t,n){"use strict";var r=n(56),o=n(18),a=n(43),i=n(271),l=n(269),u=n(106),s=n(266),c=n(282);o(o.S+o.F*!n(273)(function(e){Array.from(e)}),"Array",{from:function(e){var t,n,o,f,d=a(e),p="function"==typeof this?this:Array,h=arguments.length,v=h>1?arguments[1]:void 0,m=void 0!==v,g=0,y=c(d);if(m&&(v=r(v,h>2?arguments[2]:void 0,2)),void 0==y||p==Array&&l(y))for(t=u(d.length),n=new p(t);t>g;g++)s(n,g,m?v(d[g],g):d[g]);else for(f=y.call(d),n=new p;!(o=f.next()).done;g++)s(n,g,m?i(f,v,[o.value,g],!0):o.value);return n.length=g,n}})},function(e,t,n){"use strict";var r=n(263),o=n(274),a=n(37),i=n(25);e.exports=n(100)(Array,"Array",function(e,t){this._t=i(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,o(1)):"keys"==t?o(0,n):"values"==t?o(0,e[n]):o(0,[n,e[n]])},"values"),a.Arguments=a.Array,r("keys"),r("values"),r("entries")},function(e,t,n){var r=n(18);r(r.S+r.F,"Object",{assign:n(276)})},function(e,t,n){var r=n(18);r(r.S,"Object",{create:n(60)})},function(e,t,n){var r=n(18);r(r.S+r.F*!n(23),"Object",{defineProperty:n(20).f})},function(e,t,n){var r=n(25),o=n(61).f;n(104)("getOwnPropertyDescriptor",function(){return function(e,t){return o(r(e),t)}})},function(e,t,n){var r=n(43),o=n(102);n(104)("getPrototypeOf",function(){return function(e){return o(r(e))}})},function(e,t,n){var r=n(18);r(r.S,"Object",{setPrototypeOf:n(279).set})},function(e,t){},function(e,t,n){"use strict";var r=n(19),o=n(24),a=n(23),i=n(18),l=n(105),u=n(275).KEY,s=n(28),c=n(65),f=n(63),d=n(44),p=n(16),h=n(69),v=n(68),m=n(267),g=n(270),y=n(27),b=n(25),_=n(67),C=n(38),x=n(60),S=n(278),O=n(61),k=n(20),w=n(41),P=O.f,T=k.f,E=S.f,M=r.Symbol,N=r.JSON,j=N&&N.stringify,D="prototype",L=p("_hidden"),R=p("toPrimitive"),I={}.propertyIsEnumerable,A=c("symbol-registry"),V=c("symbols"),B=c("op-symbols"),H=Object[D],W="function"==typeof M,z=r.QObject,F=!z||!z[D]||!z[D].findChild,U=a&&s(function(){return 7!=x(T({},"a",{get:function(){return T(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=P(H,t);r&&delete H[t],T(e,t,n),r&&e!==H&&T(H,t,r)}:T,Y=function(e){var t=V[e]=x(M[D]);return t._k=e,t},X=W&&"symbol"==typeof M.iterator?function(e){return"symbol"==typeof e}:function(e){return e instanceof M},K=function(e,t,n){return e===H&&K(B,t,n),y(e),t=_(t,!0),y(n),o(V,t)?(n.enumerable?(o(e,L)&&e[L][t]&&(e[L][t]=!1),n=x(n,{enumerable:C(0,!1)})):(o(e,L)||T(e,L,C(1,{})),e[L][t]=!0),U(e,t,n)):T(e,t,n)},q=function(e,t){y(e);for(var n,r=m(t=b(t)),o=0,a=r.length;a>o;)K(e,n=r[o++],t[n]);return e},G=function(e,t){return void 0===t?x(e):q(x(e),t)},Z=function(e){var t=I.call(this,e=_(e,!0));return!(this===H&&o(V,e)&&!o(B,e))&&(!(t||!o(this,e)||!o(V,e)||o(this,L)&&this[L][e])||t)},$=function(e,t){if(e=b(e),t=_(t,!0),e!==H||!o(V,t)||o(B,t)){var n=P(e,t);return!n||!o(V,t)||o(e,L)&&e[L][t]||(n.enumerable=!0),n}},Q=function(e){for(var t,n=E(b(e)),r=[],a=0;n.length>a;)o(V,t=n[a++])||t==L||t==u||r.push(t);return r},J=function(e){for(var t,n=e===H,r=E(n?B:b(e)),a=[],i=0;r.length>i;)!o(V,t=r[i++])||n&&!o(H,t)||a.push(V[t]);return a};W||(M=function(){if(this instanceof M)throw TypeError("Symbol is not a constructor!");var e=d(arguments.length>0?arguments[0]:void 0),t=function(n){this===H&&t.call(B,n),o(this,L)&&o(this[L],e)&&(this[L][e]=!1),U(this,e,C(1,n))};return a&&F&&U(H,e,{configurable:!0,set:t}),Y(e)},l(M[D],"toString",function(){return this._k}),O.f=$,k.f=K,n(101).f=S.f=Q,n(42).f=Z,n(62).f=J,a&&!n(59)&&l(H,"propertyIsEnumerable",Z,!0),h.f=function(e){return Y(p(e))}),i(i.G+i.W+i.F*!W,{Symbol:M});for(var ee="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),te=0;ee.length>te;)p(ee[te++]);for(var ne=w(p.store),re=0;ne.length>re;)v(ne[re++]);i(i.S+i.F*!W,"Symbol",{for:function(e){return o(A,e+="")?A[e]:A[e]=M(e)},keyFor:function(e){if(!X(e))throw TypeError(e+" is not a symbol!");for(var t in A)if(A[t]===e)return t},useSetter:function(){F=!0},useSimple:function(){F=!1}}),i(i.S+i.F*!W,"Object",{create:G,defineProperty:K,defineProperties:q,getOwnPropertyDescriptor:$,getOwnPropertyNames:Q,getOwnPropertySymbols:J}),N&&i(i.S+i.F*(!W||s(function(){var e=M();return"[null]"!=j([e])||"{}"!=j({a:e})||"{}"!=j(Object(e))})),"JSON",{stringify:function(e){if(void 0!==e&&!X(e)){for(var t,n,r=[e],o=1;arguments.length>o;)r.push(arguments[o++]);return t=r[1],"function"==typeof t&&(n=t),!n&&g(t)||(t=function(e,t){if(n&&(t=n.call(this,e,t)),!X(t))return t}),r[1]=t,j.apply(N,r)}}}),M[D][R]||n(29)(M[D],R,M[D].valueOf),f(M,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0)},function(e,t,n){n(68)("asyncIterator")},function(e,t,n){n(68)("observable")},function(e,t,n){n(284);for(var r=n(19),o=n(29),a=n(37),i=n(16)("toStringTag"),l="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),u=0;u<l.length;u++){var s=l[u],c=r[s],f=c&&c.prototype;f&&!f[i]&&o(f,i,s),a[s]=a.Array}},function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a)if(a.hasOwnProperty(n)){var r=a[n];for(var o in r)if(o in t){i.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}Object.defineProperty(t,"__esModule",{value:!0});var a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},i=[];"undefined"!=typeof window&&"undefined"!=typeof document&&n();var l={addEndEventListener:function(e,t){return 0===i.length?void window.setTimeout(t,0):void i.forEach(function(n){r(e,n,t)})},endEvents:i,removeEndEventListener:function(e,t){0!==i.length&&i.forEach(function(n){o(e,n,t)})}};t.default=l,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n,r){var o=i.default.clone(e),a={width:t.width,height:t.height};return r.adjustX&&o.left<n.left&&(o.left=n.left),r.resizeWidth&&o.left>=n.left&&o.left+a.width>n.right&&(a.width-=o.left+a.width-n.right),r.adjustX&&o.left+a.width>n.right&&(o.left=Math.max(n.right-a.width,n.left)),r.adjustY&&o.top<n.top&&(o.top=n.top),r.resizeHeight&&o.top>=n.top&&o.top+a.height>n.bottom&&(a.height-=o.top+a.height-n.bottom),r.adjustY&&o.top+a.height>n.bottom&&(o.top=Math.max(n.bottom-a.height,n.top)),i.default.mix(o,a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(30),i=r(a);t.default=o,e.exports=t.default},function(e,t){"use strict";function n(e,t){var n=t.charAt(0),r=t.charAt(1),o=e.width,a=e.height,i=e.left,l=e.top;return"c"===n?l+=a/2:"b"===n&&(l+=a),"c"===r?i+=o/2:"r"===r&&(i+=o),{left:i,top:l}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n,r,o){var a=(0,i.default)(t,n[1]),l=(0,i.default)(e,n[0]),u=[l.left-a.left,l.top-a.top];return{left:e.left-u[0]+r[0]-o[0],top:e.top-u[1]+r[1]-o[1]}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(298),i=r(a);t.default=o,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=void 0,n=void 0,r=void 0;if(i.default.isWindow(e)||9===e.nodeType){var o=i.default.getWindow(e);t={left:i.default.getWindowScrollLeft(o),top:i.default.getWindowScrollTop(o)},n=i.default.viewportWidth(o),r=i.default.viewportHeight(o)}else t=i.default.offset(e),n=i.default.outerWidth(e),r=i.default.outerHeight(e);return t.width=n,t.height=r,t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(30),i=r(a);t.default=o,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=(0,u.default)(e),r=i.default.getDocument(e),o=r.defaultView||r.parentWindow,a=r.body,l=r.documentElement;n;){if(navigator.userAgent.indexOf("MSIE")!==-1&&0===n.clientWidth||n===a||n===l||"visible"===i.default.css(n,"overflow")){if(n===a||n===l)break}else{var s=i.default.offset(n);s.left+=n.clientLeft,s.top+=n.clientTop,t.top=Math.max(t.top,s.top),t.right=Math.min(t.right,s.left+n.clientWidth),t.bottom=Math.min(t.bottom,s.top+n.clientHeight),t.left=Math.max(t.left,s.left)}n=(0,u.default)(n)}var f=null;if(!i.default.isWindow(e)&&9!==e.nodeType){f=e.style.position;var d=i.default.css(e,"position");"absolute"===d&&(e.style.position="fixed")}var p=i.default.getWindowScrollLeft(o),h=i.default.getWindowScrollTop(o),v=i.default.viewportWidth(o),m=i.default.viewportHeight(o),g=l.scrollWidth,y=l.scrollHeight;if(e.style&&(e.style.position=f),(0,c.default)(e))t.left=Math.max(t.left,p),t.top=Math.max(t.top,h),t.right=Math.min(t.right,p+v),t.bottom=Math.min(t.bottom,h+m);else{var b=Math.max(g,p+v);t.right=Math.min(t.right,b);var _=Math.max(y,h+m);t.bottom=Math.min(t.bottom,_)}return t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(30),i=r(a),l=n(109),u=r(l),s=n(303),c=r(s);t.default=o,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return e.left<n.left||e.left+t.width>n.right}function a(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function i(e,t,n){return e.left>n.right||e.left+t.width<n.left}function l(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function u(e){var t=(0,b.default)(e),n=(0,S.default)(e);return!t||n.left+n.width<=t.left||n.top+n.height<=t.top||n.left>=t.right||n.top>=t.bottom}function s(e,t,n){var r=[];return v.default.each(e,function(e){r.push(e.replace(t,function(e){return n[e]}))}),r}function c(e,t){return e[t]=-e[t],e}function f(e,t){var n=void 0;return n=/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10),n||0}function d(e,t){e[0]=f(e[0],t.width),e[1]=f(e[1],t.height)}function p(e,t,n){var r=n.points,f=n.offset||[0,0],p=n.targetOffset||[0,0],h=n.overflow,m=n.target||t,g=n.source||e;f=[].concat(f),p=[].concat(p),h=h||{};var y={},_=0,x=(0,b.default)(g),O=(0,S.default)(g),w=(0,S.default)(m);d(f,O),d(p,w);var P=(0,k.default)(O,w,r,f,p),T=v.default.merge(O,P),E=!u(m);if(x&&(h.adjustX||h.adjustY)&&E){if(h.adjustX&&o(P,O,x)){var M=s(r,/[lr]/gi,{l:"r",r:"l"}),N=c(f,0),j=c(p,0),D=(0,k.default)(O,w,M,N,j);i(D,O,x)||(_=1,r=M,f=N,p=j)}if(h.adjustY&&a(P,O,x)){var L=s(r,/[tb]/gi,{t:"b",b:"t"}),R=c(f,1),I=c(p,1),A=(0,k.default)(O,w,L,R,I);l(A,O,x)||(_=1,r=L,f=R,p=I)}_&&(P=(0,k.default)(O,w,r,f,p),v.default.mix(T,P)),y.adjustX=h.adjustX&&o(P,O,x),y.adjustY=h.adjustY&&a(P,O,x),(y.adjustX||y.adjustY)&&(T=(0,C.default)(P,O,x,y))}return T.width!==O.width&&v.default.css(g,"width",v.default.width(g)+T.width-O.width),T.height!==O.height&&v.default.css(g,"height",v.default.height(g)+T.height-O.height),v.default.offset(g,{left:T.left,top:T.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform}),{points:r,offset:f,targetOffset:p,overflow:y}}Object.defineProperty(t,"__esModule",{value:!0});var h=n(30),v=r(h),m=n(109),g=r(m),y=n(301),b=r(y),_=n(297),C=r(_),x=n(300),S=r(x),O=n(299),k=r(O);p.__getOffsetParent=g.default,p.__getVisibleRectForElement=b.default,t.default=p,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){if(i.default.isWindow(e)||9===e.nodeType)return!1;var t=i.default.getDocument(e),n=t.body,r=null;for(r=e.parentNode;r&&r!==n;r=r.parentNode){var o=i.default.css(r,"position");if("fixed"===o)return!0}return!1}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=n(30),i=r(a);e.exports=t.default},function(e,t){"use strict";function n(){if(void 0!==c)return c;c="";var e=document.createElement("p").style,t="Transform";for(var n in f)n+t in e&&(c=n);return c}function r(){return n()?n()+"TransitionProperty":"transitionProperty"}function o(){return n()?n()+"Transform":"transform"}function a(e,t){var n=r();n&&(e.style[n]=t,"transitionProperty"!==n&&(e.style.transitionProperty=t))}function i(e,t){var n=o();n&&(e.style[n]=t,"transform"!==n&&(e.style.transform=t))}function l(e){return e.style.transitionProperty||e.style[r()]}function u(e){var t=window.getComputedStyle(e,null),n=t.getPropertyValue("transform")||t.getPropertyValue(o());if(n&&"none"!==n){var r=n.replace(/[^0-9\-.,]/g,"").split(",");return{x:parseFloat(r[12]||r[4],0),y:parseFloat(r[13]||r[5],0)}}return{x:0,y:0}}function s(e,t){var n=window.getComputedStyle(e,null),r=n.getPropertyValue("transform")||n.getPropertyValue(o());if(r&&"none"!==r){var a=void 0,l=r.match(d);if(l)l=l[1],a=l.split(",").map(function(e){return parseFloat(e,10)}),a[4]=t.x,a[5]=t.y,i(e,"matrix("+a.join(",")+")");else{var u=r.match(p)[1];a=u.split(",").map(function(e){return parseFloat(e,10)}),a[12]=t.x,a[13]=t.y,i(e,"matrix3d("+a.join(",")+")")}}else i(e,"translateX("+t.x+"px) translateY("+t.y+"px) translateZ(0)")}Object.defineProperty(t,"__esModule",{value:!0}),t.getTransformName=o,t.setTransitionProperty=a,t.getTransitionProperty=l,t.getTransformXY=u,t.setTransformXY=s;
var c=void 0,f={Webkit:"-webkit-",Moz:"-moz-",ms:"-ms-",O:"-o-"},d=/matrix\((.*)\)/,p=/matrix3d\((.*)\)/},function(e,t,n){var r;/*!
Copyright (c) 2015 Jed Watson.
Based on code that is Copyright 2013-2015, Facebook, Inc.
All rights reserved.
*/
!function(){"use strict";var o=!("undefined"==typeof window||!window.document||!window.document.createElement),a={canUseDOM:o,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:o&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:o&&!!window.screen};r=function(){return a}.call(t,n,t,e),!(void 0!==r&&(e.exports=r))}()},function(e,t){},306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,306,function(e,t){"use strict";function n(e){return function(){return e}}var r=function(){};r.thatReturns=n,r.thatReturnsFalse=n(!1),r.thatReturnsTrue=n(!0),r.thatReturnsNull=n(null),r.thatReturnsThis=function(){return this},r.thatReturnsArgument=function(e){return e},e.exports=r},function(e,t,n){"use strict";function r(e){if(Array.isArray(e))return 0===e.length;if("object"==typeof e){if(e){o(e)&&void 0!==e.size?a(!1):void 0;for(var t in e)return!1}return!0}return!e}function o(e){return"undefined"!=typeof Symbol&&e[Symbol.iterator]}var a=n(70);e.exports=r},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return i(n)?n:void 0}function o(e){return a(e)&&d.call(e)==l}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function i(e){return null!=e&&(o(e)?p.test(c.call(e)):n(e)&&u.test(e))}var l="[object Function]",u=/^\[object .+?Constructor\]$/,s=Object.prototype,c=Function.prototype.toString,f=s.hasOwnProperty,d=s.toString,p=RegExp("^"+c.call(f).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t){function n(e){return o(e)&&h.call(e,"callee")&&(!m.call(e,"callee")||v.call(e)==c)}function r(e){return null!=e&&i(e.length)&&!a(e)}function o(e){return u(e)&&r(e)}function a(e){var t=l(e)?v.call(e):"";return t==f||t==d}function i(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=s}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){return!!e&&"object"==typeof e}var s=9007199254740991,c="[object Arguments]",f="[object Function]",d="[object GeneratorFunction]",p=Object.prototype,h=p.hasOwnProperty,v=p.toString,m=p.propertyIsEnumerable;e.exports=n},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return l(n)?n:void 0}function o(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=g}function a(e){return i(e)&&h.call(e)==s}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function l(e){return null!=e&&(a(e)?v.test(d.call(e)):n(e)&&c.test(e))}var u="[object Array]",s="[object Function]",c=/^\[object .+?Constructor\]$/,f=Object.prototype,d=Function.prototype.toString,p=f.hasOwnProperty,h=f.toString,v=RegExp("^"+d.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),m=r(Array,"isArray"),g=9007199254740991,y=m||function(e){return n(e)&&o(e.length)&&h.call(e)==u};e.exports=y},function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}function o(e){return null!=e&&i(y(e))}function a(e,t){return e="number"==typeof e||p.test(e)?+e:-1,t=null==t?g:t,e>-1&&e%1==0&&e<t}function i(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=g}function l(e){for(var t=s(e),n=t.length,r=n&&e.length,o=!!r&&i(r)&&(d(e)||f(e)),l=-1,u=[];++l<n;){var c=t[l];(o&&a(c,r)||v.call(e,c))&&u.push(c)}return u}function u(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){if(null==e)return[];u(e)||(e=Object(e));var t=e.length;t=t&&i(t)&&(d(e)||f(e))&&t||0;for(var n=e.constructor,r=-1,o="function"==typeof n&&n.prototype===e,l=Array(t),s=t>0;++r<t;)l[r]=r+"";for(var c in e)s&&a(c,t)||"constructor"==c&&(o||!v.call(e,c))||l.push(c);return l}var c=n(355),f=n(356),d=n(357),p=/^\d+$/,h=Object.prototype,v=h.hasOwnProperty,m=c(Object,"keys"),g=9007199254740991,y=r("length"),b=m?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?l(e):u(e)?m(e):[]}:l;e.exports=b},function(e,t){/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(e){return!1}}var o=Object.getOwnPropertySymbols,a=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,l,u=n(e),s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var c in r)a.call(r,c)&&(u[c]=r[c]);if(o){l=o(r);for(var f=0;f<l.length;f++)i.call(r,l[f])&&(u[l[f]]=r[l[f]])}}return u}},function(e,t,n){(function(t){(function(){var n,r,o,a,i,l;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:"undefined"!=typeof t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-i)/1e6},r=t.hrtime,n=function(){var e;return e=r(),1e9*e[0]+e[1]},a=n(),l=1e9*t.uptime(),i=a-l):Date.now?(e.exports=function(){return Date.now()-o},o=Date.now()):(e.exports=function(){return(new Date).getTime()-o},o=(new Date).getTime())}).call(this)}).call(t,n(361))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(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 a(e){if(f===clearTimeout)return clearTimeout(e);if((f===r||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(e);try{return f(e)}catch(t){try{return f.call(null,e)}catch(t){return f.call(this,e)}}}function i(){v&&p&&(v=!1,p.length?h=p.concat(h):m=-1,h.length&&l())}function l(){if(!v){var e=o(i);v=!0;for(var t=h.length;t;){for(p=h,h=[];++m<t;)p&&p[m].run();m=-1,t=h.length}p=null,v=!1,a(e)}}function u(e,t){this.fun=e,this.array=t}function s(){}var c,f,d=e.exports={};!function(){try{c="function"==typeof setTimeout?setTimeout:n}catch(e){c=n}try{f="function"==typeof clearTimeout?clearTimeout:r}catch(e){f=r}}();var p,h=[],v=!1,m=-1;d.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];h.push(new u(e,t)),1!==h.length||v||o(l)},u.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=s,d.addListener=s,d.once=s,d.off=s,d.removeListener=s,d.removeAllListeners=s,d.emit=s,d.prependListener=s,d.prependOnceListener=s,d.listeners=function(e){return[]},d.binding=function(e){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(e){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},function(e,t,n){"use strict";var r=n(353),o=n(70),a=n(363);e.exports=function(){function e(e,t,n,r,i,l){l!==a&&o(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=r,n.PropTypes=n,n}},function(e,t){"use strict";var n="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(17),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(11),g=r(m),y=n(10),b=r(y),_=n(108),C=r(_),x=n(111),S=r(x),O={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},k=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillUnmount",value:function(){this.stop()}},{key:"componentWillEnter",value:function(e){S.default.isEnterSupported(this.props)?this.transition("enter",e):e()}},{key:"componentWillAppear",value:function(e){S.default.isAppearSupported(this.props)?this.transition("appear",e):e()}},{key:"componentWillLeave",value:function(e){S.default.isLeaveSupported(this.props)?this.transition("leave",e):e()}},{key:"transition",value:function(e,t){var n=this,r=g.default.findDOMNode(this),o=this.props,i=o.transitionName,l="object"===("undefined"==typeof i?"undefined":(0,a.default)(i));this.stop();var u=function(){n.stopper=null,t()};if((_.isCssAnimationSupported||!o.animation[e])&&i&&o[O[e]]){var s=l?i[e]:i+"-"+e,c=s+"-active";l&&i[e+"Active"]&&(c=i[e+"Active"]),this.stopper=(0,C.default)(r,{name:s,active:c},u)}else this.stopper=o.animation[e](r,u)}},{key:"stop",value:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())}},{key:"render",value:function(){return this.props.children}}]),t}(v.default.Component);k.propTypes={children:b.default.any},t.default=k,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=[];return f.default.Children.forEach(e,function(e){t.push(e)}),t}function a(e,t){var n=null;return e&&e.forEach(function(e){n||e&&e.key===t&&(n=e)}),n}function i(e,t,n){var r=null;return e&&e.forEach(function(e){if(e&&e.key===t&&e.props[n]){if(r)throw new Error("two child with same key for <rc-animate> children");r=e}}),r}function l(e,t,n){var r=0;return e&&e.forEach(function(e){r||(r=e&&e.key===t&&!e.props[n])}),r}function u(e,t,n){var r=e.length===t.length;return r&&e.forEach(function(e,o){var a=t[o];e&&a&&(e&&!a||!e&&a?r=!1:e.key!==a.key?r=!1:n&&e.props[n]!==a.props[n]&&(r=!1))}),r}function s(e,t){var n=[],r={},o=[];return e.forEach(function(e){e&&a(t,e.key)?o.length&&(r[e.key]=o,o=[]):o.push(e)}),t.forEach(function(e){e&&r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e)}),n=n.concat(o)}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=o,t.findChildInChildrenByKey=a,t.findShownChildInChildrenByKey=i,t.findHiddenChildInChildrenByKey=l,t.isSameChildren=u,t.mergeChildren=s;var c=n(1),f=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(22),s=r(u),c=n(2),f=r(c),d=n(5),p=r(d),h=n(4),v=r(h),m=n(3),g=r(m),y=n(1),b=r(y),_=n(10),C=r(_),x=n(387),S=r(x),O=n(7),k=r(O),w=function(e){function t(e){(0,f.default)(this,t);var n=(0,v.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));P.call(n);var r="checked"in e?e.checked:e.defaultChecked;return n.state={checked:r},n}return(0,g.default)(t,e),(0,p.default)(t,[{key:"componentWillReceiveProps",value:function(e){"checked"in e&&this.setState({checked:e.checked})}},{key:"shouldComponentUpdate",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return S.default.shouldComponentUpdate.apply(this,t)}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.style,i=t.name,u=t.type,c=t.disabled,f=t.readOnly,d=t.tabIndex,p=t.onClick,h=t.onFocus,v=t.onBlur,m=(0,s.default)(t,["prefixCls","className","style","name","type","disabled","readOnly","tabIndex","onClick","onFocus","onBlur"]),g=Object.keys(m).reduce(function(e,t){return"aria-"!==t.substr(0,5)&&"data-"!==t.substr(0,5)&&"role"!==t||(e[t]=m[t]),e},{}),y=this.state.checked,_=(0,k.default)(n,r,(e={},(0,l.default)(e,n+"-checked",y),(0,l.default)(e,n+"-disabled",c),e));return b.default.createElement("span",{className:_,style:o},b.default.createElement("input",(0,a.default)({name:i,type:u,readOnly:f,disabled:c,tabIndex:d,className:n+"-input",checked:!!y,onClick:p,onFocus:h,onBlur:v,onChange:this.handleChange},g)),b.default.createElement("span",{className:n+"-inner"}))}}]),t}(b.default.Component);w.propTypes={prefixCls:C.default.string,className:C.default.string,style:C.default.object,name:C.default.string,type:C.default.string,defaultChecked:C.default.oneOfType([C.default.number,C.default.bool]),checked:C.default.oneOfType([C.default.number,C.default.bool]),disabled:C.default.bool,onFocus:C.default.func,onBlur:C.default.func,onChange:C.default.func,onClick:C.default.func,tabIndex:C.default.string,readOnly:C.default.bool},w.defaultProps={prefixCls:"rc-checkbox",className:"",style:{},type:"checkbox",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}};var P=function(){var e=this;this.handleChange=function(t){var n=e.props;n.disabled||("checked"in n||e.setState({checked:t.target.checked}),n.onChange({target:(0,a.default)({},n,{checked:t.target.checked}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()}}))}};t.default=w,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}Object.defineProperty(t,"__esModule",{value:!0});var c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),f=n(1),d=r(f),p=n(10),h=r(p),v=n(368),m=r(v),g=n(371),y=r(g),b=n(7),_=r(b),C=function(e){function t(e){i(this,t);var n=l(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e)),r=n.props,o=r.activeKey,a=r.defaultActiveKey,u=a;return"activeKey"in n.props&&(u=o),n.state={openAnimation:n.props.openAnimation||(0,y.default)(n.props.prefixCls),activeKey:s(u)},n}return u(t,e),c(t,[{key:"componentWillReceiveProps",value:function(e){"activeKey"in e&&this.setState({activeKey:s(e.activeKey)}),"openAnimation"in e&&this.setState({openAnimation:e.openAnimation})}},{key:"onClickItem",value:function(e){var t=this.state.activeKey;if(this.props.accordion)t=t[0]===e?[]:[e];else{t=[].concat(a(t));var n=t.indexOf(e),r=n>-1;r?t.splice(n,1):t.push(e)}this.setActiveKey(t)}},{key:"getItems",value:function(){var e=this,t=this.state.activeKey,n=this.props,r=n.prefixCls,o=n.accordion,a=n.destroyInactivePanel,i=[];return f.Children.forEach(this.props.children,function(n,l){if(n){var u=n.key||String(l),s=n.props,c=s.header,f=s.headerClass,p=s.disabled,h=!1;h=o?t[0]===u:t.indexOf(u)>-1;var v={key:u,header:c,headerClass:f,isActive:h,prefixCls:r,destroyInactivePanel:a,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:p?null:function(){return e.onClickItem(u)}};i.push(d.default.cloneElement(n,v))}}),i}},{key:"setActiveKey",value:function(e){"activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(this.props.accordion?e[0]:e)}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.className,a=t.style,i=(0,_.default)((e={},o(e,n,!0),o(e,r,!!r),e));return d.default.createElement("div",{className:i,style:a},this.getItems())}}]),t}(f.Component);C.propTypes={children:h.default.any,prefixCls:h.default.string,activeKey:h.default.oneOfType([h.default.string,h.default.arrayOf(h.default.string)]),defaultActiveKey:h.default.oneOfType([h.default.string,h.default.arrayOf(h.default.string)]),openAnimation:h.default.object,onChange:h.default.func,accordion:h.default.bool,className:h.default.string,style:h.default.object,destroyInactivePanel:h.default.bool},C.defaultProps={prefixCls:"rc-collapse",onChange:function(){},accordion:!1,destroyInactivePanel:!1},C.Panel=m.default,t.default=C,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(1),c=r(s),f=n(10),d=r(f),p=n(7),h=r(p),v=n(369),m=r(v),g=n(39),y=r(g),b=function(e){function t(){return a(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return l(t,e),u(t,[{key:"handleItemClick",value:function(){this.props.onItemClick&&this.props.onItemClick()}},{key:"render",value:function(){var e,t=this.props,n=t.className,r=t.id,a=t.style,i=t.prefixCls,l=t.header,u=t.headerClass,s=t.children,f=t.isActive,d=t.showArrow,p=t.destroyInactivePanel,v=t.disabled,g=(0,h.default)(i+"-header",o({},u,u)),b=(0,h.default)((e={},o(e,i+"-item",!0),o(e,i+"-item-active",f),o(e,i+"-item-disabled",v),e),n);return c.default.createElement("div",{className:b,style:a,id:r},c.default.createElement("div",{className:g,onClick:this.handleItemClick.bind(this),role:"tab","aria-expanded":f},d&&c.default.createElement("i",{className:"arrow"}),l),c.default.createElement(y.default,{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},c.default.createElement(m.default,{prefixCls:i,isActive:f,destroyInactivePanel:p},s)))}}]),t}(s.Component);b.propTypes={className:d.default.oneOfType([d.default.string,d.default.object]),id:d.default.string,children:d.default.any,openAnimation:d.default.object,prefixCls:d.default.string,header:d.default.oneOfType([d.default.string,d.default.number,d.default.node]),headerClass:d.default.string,showArrow:d.default.bool,isActive:d.default.bool,onItemClick:d.default.func,style:d.default.object,destroyInactivePanel:d.default.bool,disabled:d.default.bool},b.defaultProps={showArrow:!0,isActive:!1,destroyInactivePanel:!1,onItemClick:function(){},headerClass:""},t.default=b,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(1),c=r(s),f=n(10),d=r(f),p=n(7),h=r(p),v=function(e){function t(){return a(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return l(t,e),u(t,[{key:"shouldComponentUpdate",value:function(e){return this.props.isActive||e.isActive}},{key:"render",value:function(){var e;if(this._isActived=this._isActived||this.props.isActive,!this._isActived)return null;var t=this.props,n=t.prefixCls,r=t.isActive,a=t.children,i=t.destroyInactivePanel,l=(0,h.default)((e={},o(e,n+"-content",!0),o(e,n+"-content-active",r),o(e,n+"-content-inactive",!r),e)),u=!r&&i?null:c.default.createElement("div",{className:n+"-content-box"},a);return c.default.createElement("div",{className:l,role:"tabpanel"},u)}}]),t}(s.Component);v.propTypes={prefixCls:d.default.string,isActive:d.default.bool,children:d.default.any,destroyInactivePanel:d.default.bool},t.default=v,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Panel=void 0;var o=n(367),a=r(o);t.default=a.default;t.Panel=a.default.Panel},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n,r){var o=void 0;return(0,l.default)(e,n,{start:function(){t?(o=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?o:0)+"px"},end:function(){e.style.height="",r()}})}function a(e){return{enter:function(t,n){return o(t,!0,e+"-anim",n)},leave:function(t,n){return o(t,!1,e+"-anim",n)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(108),l=r(i);t.default=a,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){for(var t=e,n=0,r=0;t&&!isNaN(t.offsetLeft)&&!isNaN(t.offsetTop);)n+=t.offsetLeft-t.scrollLeft,r+=t.offsetTop-t.scrollTop,t=t.offsetParent;return{top:r,left:n}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),l=n(6),u=r(l),s=n(17),c=r(s),f=n(2),d=r(f),p=n(5),h=r(p),v=n(4),m=r(v),g=n(3),y=r(g),b=n(1),_=r(b),C=n(10),x=r(C),S=n(11),O=r(S),k=n(7),w=r(k),P=20,T=function(e){function t(e){(0,d.default)(this,t);var n=(0,m.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onOverlayClicked=function(){n.props.open&&setTimeout(function(){n.props.onOpenChange(!1,{overlayClicked:!0})},0)},n.onTouchStart=function(e){if(!n.isTouching()){var t=e.targetTouches[0];n.setState({touchIdentifier:n.notTouch?null:t.identifier,touchStartX:t.clientX,touchStartY:t.clientY,touchCurrentX:t.clientX,touchCurrentY:t.clientY})}},n.onTouchMove=function(e){if(n.isTouching())for(var t=0;t<e.targetTouches.length;t++)if(e.targetTouches[t].identifier===n.state.touchIdentifier){n.setState({touchCurrentX:e.targetTouches[t].clientX,touchCurrentY:e.targetTouches[t].clientY});break}},n.onTouchEnd=function(){if(n.notTouch=!1,n.isTouching()){var e=n.touchSidebarWidth();(n.props.open&&e<n.state.sidebarWidth-n.props.dragToggleDistance||!n.props.open&&e>n.props.dragToggleDistance)&&n.props.onOpenChange(!n.props.open);var t=n.touchSidebarHeight();(n.props.open&&t<n.state.sidebarHeight-n.props.dragToggleDistance||!n.props.open&&t>n.props.dragToggleDistance)&&n.props.onOpenChange(!n.props.open),n.setState({touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null})}},n.onScroll=function(){n.isTouching()&&n.inCancelDistanceOnScroll()&&n.setState({touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null})},n.inCancelDistanceOnScroll=function(){var e=void 0;switch(n.props.position){case"right":e=Math.abs(n.state.touchCurrentX-n.state.touchStartX)<P;break;case"bottom":e=Math.abs(n.state.touchCurrentY-n.state.touchStartY)<P;break;case"top":e=Math.abs(n.state.touchStartY-n.state.touchCurrentY)<P;break;case"left":default:e=Math.abs(n.state.touchStartX-n.state.touchCurrentX)<P}return e},n.isTouching=function(){return null!==n.state.touchIdentifier},n.saveSidebarSize=function(){var e=O.default.findDOMNode(n.refs.sidebar),t=e.offsetWidth,r=e.offsetHeight,a=o(O.default.findDOMNode(n.refs.sidebar)).top,i=o(O.default.findDOMNode(n.refs.dragHandle)).top;t!==n.state.sidebarWidth&&n.setState({sidebarWidth:t}),r!==n.state.sidebarHeight&&n.setState({sidebarHeight:r}),a!==n.state.sidebarTop&&n.setState({sidebarTop:a}),i!==n.state.dragHandleTop&&n.setState({dragHandleTop:i})},n.touchSidebarWidth=function(){return"right"===n.props.position?n.props.open&&window.innerWidth-n.state.touchStartX<n.state.sidebarWidth?n.state.touchCurrentX>n.state.touchStartX?n.state.sidebarWidth+n.state.touchStartX-n.state.touchCurrentX:n.state.sidebarWidth:Math.min(window.innerWidth-n.state.touchCurrentX,n.state.sidebarWidth):"left"===n.props.position?n.props.open&&n.state.touchStartX<n.state.sidebarWidth?n.state.touchCurrentX>n.state.touchStartX?n.state.sidebarWidth:n.state.sidebarWidth-n.state.touchStartX+n.state.touchCurrentX:Math.min(n.state.touchCurrentX,n.state.sidebarWidth):void 0},n.touchSidebarHeight=function(){if("bottom"===n.props.position)return n.props.open&&window.innerHeight-n.state.touchStartY<n.state.sidebarHeight?n.state.touchCurrentY>n.state.touchStartY?n.state.sidebarHeight+n.state.touchStartY-n.state.touchCurrentY:n.state.sidebarHeight:Math.min(window.innerHeight-n.state.touchCurrentY,n.state.sidebarHeight);if("top"===n.props.position){var e=n.state.touchStartY-n.state.sidebarTop;return n.props.open&&e<n.state.sidebarHeight?n.state.touchCurrentY>n.state.touchStartY?n.state.sidebarHeight:n.state.sidebarHeight-n.state.touchStartY+n.state.touchCurrentY:Math.min(n.state.touchCurrentY-n.state.dragHandleTop,n.state.sidebarHeight)}},n.renderStyle=function(e){var t=e.sidebarStyle,r=e.isTouching,o=e.overlayStyle,a=e.contentStyle;if("right"===n.props.position||"left"===n.props.position){if(t.transform="translateX(0%)",t.WebkitTransform="translateX(0%)",r){var i=n.touchSidebarWidth()/n.state.sidebarWidth;"right"===n.props.position&&(t.transform="translateX("+100*(1-i)+"%)",t.WebkitTransform="translateX("+100*(1-i)+"%)"),"left"===n.props.position&&(t.transform="translateX(-"+100*(1-i)+"%)",t.WebkitTransform="translateX(-"+100*(1-i)+"%)"),o.opacity=i,o.visibility="visible"}a&&(a[n.props.position]=n.state.sidebarWidth+"px")}if("top"===n.props.position||"bottom"===n.props.position){if(t.transform="translateY(0%)",t.WebkitTransform="translateY(0%)",r){var l=n.touchSidebarHeight()/n.state.sidebarHeight;"bottom"===n.props.position&&(t.transform="translateY("+100*(1-l)+"%)",t.WebkitTransform="translateY("+100*(1-l)+"%)"),"top"===n.props.position&&(t.transform="translateY(-"+100*(1-l)+"%)",t.WebkitTransform="translateY(-"+100*(1-l)+"%)"),o.opacity=l,o.visibility="visible"}a&&(a[n.props.position]=n.state.sidebarHeight+"px")}},n.state={sidebarWidth:0,sidebarHeight:0,sidebarTop:0,dragHandleTop:0,touchIdentifier:null,touchStartX:null,touchStartY:null,touchCurrentX:null,touchCurrentY:null,touchSupported:"object"===("undefined"==typeof window?"undefined":(0,c.default)(window))&&"ontouchstart"in window},n}return(0,y.default)(t,e),(0,h.default)(t,[{key:"componentDidMount",value:function(){this.saveSidebarSize()}},{key:"componentDidUpdate",value:function(){this.isTouching()||this.saveSidebarSize()}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.className,o=n.style,a=n.prefixCls,l=n.position,s=n.transitions,c=n.touch,f=n.enableDragHandle,d=n.sidebar,p=n.children,h=n.docked,v=n.open,m=(0,u.default)({},this.props.sidebarStyle),g=(0,u.default)({},this.props.contentStyle),y=(0,u.default)({},this.props.overlayStyle),b=(e={},(0,i.default)(e,r,!!r),(0,i.default)(e,a,!0),(0,i.default)(e,a+"-"+l,!0),e),C={style:o},x=this.isTouching();x?this.renderStyle({sidebarStyle:m,isTouching:!0,overlayStyle:y}):h?0!==this.state.sidebarWidth&&(b[a+"-docked"]=!0,this.renderStyle({sidebarStyle:m,contentStyle:g})):v&&(b[a+"-open"]=!0,this.renderStyle({sidebarStyle:m}),y.opacity=1,y.visibility="visible"),!x&&s||(m.transition="none",m.WebkitTransition="none",g.transition="none",y.transition="none");var S=null;return this.state.touchSupported&&c&&(v?(C.onTouchStart=function(e){t.notTouch=!0,t.onTouchStart(e)},C.onTouchMove=this.onTouchMove,C.onTouchEnd=this.onTouchEnd,C.onTouchCancel=this.onTouchEnd,C.onScroll=this.onScroll):f&&(S=_.default.createElement("div",{className:a+"-draghandle",style:this.props.dragHandleStyle,onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd,ref:"dragHandle"}))),_.default.createElement("div",(0,u.default)({className:(0,w.default)(b)},C),_.default.createElement("div",{className:a+"-sidebar",style:m,ref:"sidebar"},d),_.default.createElement("div",{className:a+"-overlay",style:y,role:"presentation",ref:"overlay",onClick:this.onOverlayClicked}),_.default.createElement("div",{className:a+"-content",style:g,ref:"content"},S,p))}}]),t}(_.default.Component);T.propTypes={prefixCls:x.default.string,className:x.default.string,children:x.default.node.isRequired,style:x.default.object,sidebarStyle:x.default.object,contentStyle:x.default.object,overlayStyle:x.default.object,dragHandleStyle:x.default.object,sidebar:x.default.node.isRequired,docked:x.default.bool,open:x.default.bool,transitions:x.default.bool,touch:x.default.bool,enableDragHandle:x.default.bool,position:x.default.oneOf(["left","right","top","bottom"]),dragToggleDistance:x.default.number,onOpenChange:x.default.func},T.defaultProps={prefixCls:"rc-drawer",sidebarStyle:{},contentStyle:{},overlayStyle:{},dragHandleStyle:{},docked:!1,open:!1,transitions:!0,touch:!0,enableDragHandle:!0,position:"left",dragToggleDistance:30,onOpenChange:function(){}},t.default=T,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(372),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e,t){return Math.sqrt(e*e+t*t)}function o(e,t){var n=Math.atan2(t,e);return 180/(Math.PI/n)}function a(){return Date.now()}function i(e){if(!(e.length<2)){var t=e[0],n=t.x,a=t.y,i=e[1],l=i.x,u=i.y,s=l-n,c=u-a;return{x:s,y:c,z:r(s,c),angle:o(s,c)}}}function l(e,t,n){var a=e[0],i=a.x,l=a.y,u=t[0],s=u.x,c=u.y,f=s-i,d=c-l,p=r(f,d);return{x:f,y:d,z:p,time:n,velocity:p/n,angle:o(f,d)}}function u(e,t){var n=e.angle,r=t.angle;return r-n}function s(e,t){return e+t[0].toUpperCase()+t.slice(1)}function c(e,t){return Math.abs(e)>=h.SWIPE.threshold&&Math.abs(t)>h.SWIPE.velocity}function f(e,t){return!!(t&e)}function d(e,t){return e===t?h.DIRECTION_NONE:Math.abs(e)>=Math.abs(t)?e<0?h.DIRECTION_LEFT:h.DIRECTION_RIGHT:t<0?h.DIRECTION_UP:h.DIRECTION_DOWN}function p(e){var t=void 0;switch(e){case h.DIRECTION_NONE:break;case h.DIRECTION_LEFT:t="left";break;case h.DIRECTION_RIGHT:t="right";break;case h.DIRECTION_UP:t="up";break;case h.DIRECTION_DOWN:t="down"}return t}Object.defineProperty(t,"__esModule",{value:!0}),t.now=a,t.calcMutliFingerStatus=i,t.calcMoveStatus=l,t.calcRotation=u,t.getEventName=s,t.shouldTriggerSwipe=c,t.shouldTriggerDirection=f,t.getDirection=d,t.getDirectionEventName=p;var h=n(113)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(7),g=r(m),y=n(10),b=r(y),_=function(e){function t(){var e,n,r,o;(0,l.default)(this,t);for(var a=arguments.length,i=Array(a),u=0;u<a;u++)i[u]=arguments[u];return n=r=(0,f.default)(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(i))),r.close=function(){r.clearCloseTimer(),r.props.onClose()},r.startCloseTimer=function(){r.props.duration&&(r.closeTimer=setTimeout(function(){r.close()},1e3*r.props.duration))},r.clearCloseTimer=function(){r.closeTimer&&(clearTimeout(r.closeTimer),r.closeTimer=null)},o=n,(0,f.default)(r,o)}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentDidMount",value:function(){this.startCloseTimer()}},{key:"componentWillUnmount",value:function(){this.clearCloseTimer()}},{key:"render",value:function(){var e,t=this.props,n=t.prefixCls+"-notice",r=(e={},(0,a.default)(e,""+n,1),(0,a.default)(e,n+"-closable",t.closable),(0,a.default)(e,t.className,!!t.className),e);return v.default.createElement("div",{className:(0,g.default)(r),style:t.style,onMouseEnter:this.clearCloseTimer,onMouseLeave:this.startCloseTimer},v.default.createElement("div",{className:n+"-content"},t.children),t.closable?v.default.createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},v.default.createElement("span",{className:n+"-close-x"})):null)}}]),t}(h.Component);_.propTypes={duration:b.default.number,onClose:b.default.func,children:b.default.any},_.defaultProps={onEnd:function(){},onClose:function(){},duration:1.5,style:{right:"50%"}},t.default=_,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){return"rcNotification_"+L+"_"+D++}Object.defineProperty(t,"__esModule",{value:!0});var a=n(22),i=r(a),l=n(8),u=r(l),s=n(6),c=r(s),f=n(2),d=r(f),p=n(5),h=r(p),v=n(4),m=r(v),g=n(3),y=r(g),b=n(1),_=r(b),C=n(10),x=r(C),S=n(11),O=r(S),k=n(39),w=r(k),P=n(388),T=r(P),E=n(7),M=r(E),N=n(375),j=r(N),D=0,L=Date.now(),R=function(e){function t(){var e,n,r,a;(0,d.default)(this,t);for(var i=arguments.length,l=Array(i),u=0;u<i;u++)l[u]=arguments[u];return n=r=(0,m.default)(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(l))),r.state={notices:[]},r.add=function(e){var t=e.key=e.key||o();r.setState(function(n){var r=n.notices;if(!r.filter(function(e){return e.key===t}).length)return{notices:r.concat(e)}})},r.remove=function(e){r.setState(function(t){return{notices:t.notices.filter(function(t){return t.key!==e})}})},a=n,(0,m.default)(r,a)}return(0,y.default)(t,e),(0,h.default)(t,[{key:"getTransitionName",value:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t}},{key:"render",value:function(){var e,t=this,n=this.props,r=this.state.notices.map(function(e){var r=(0,T.default)(t.remove.bind(t,e.key),e.onClose);return _.default.createElement(j.default,(0,c.default)({prefixCls:n.prefixCls},e,{onClose:r}),e.content)}),o=(e={},(0,u.default)(e,n.prefixCls,1),(0,u.default)(e,n.className,!!n.className),e);return _.default.createElement("div",{className:(0,M.default)(o),style:n.style},_.default.createElement(w.default,{transitionName:this.getTransitionName()},r))}}]),t}(b.Component);R.propTypes={prefixCls:x.default.string,transitionName:x.default.string,animation:x.default.oneOfType([x.default.string,x.default.object]),style:x.default.object},R.defaultProps={prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}},R.newInstance=function(e){var t=e||{},n=t.getContainer,r=(0,i.default)(t,["getContainer"]),o=void 0;n?o=n():(o=document.createElement("div"),document.body.appendChild(o));var a=O.default.render(_.default.createElement(R,r),o);return{notice:function(e){a.add(e)},removeNotice:function(e){a.remove(e)},component:a,destroy:function(){O.default.unmountComponentAtNode(o),n||document.body.removeChild(o)}}},t.default=R,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(376),a=r(o);t.default=a.default,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{
value:!0});var o=n(6),a=r(o),i=n(22),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(10),b=r(y),_=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.vertical,r=e.offset,o=e.style,i=e.disabled,u=e.min,s=e.max,c=e.value,f=(0,l.default)(e,["className","vertical","offset","style","disabled","min","max","value"]),d=n?{bottom:r+"%"}:{left:r+"%"},p=(0,a.default)({},o,d),h={};return void 0!==c&&(h=(0,a.default)({},h,{"aria-valuemin":u,"aria-valuemax":s,"aria-valuenow":c,"aria-disabled":!!i})),g.default.createElement("div",(0,a.default)({role:"slider"},h,f,{className:t,style:p}))}}]),t}(g.default.Component);t.default=_,_.propTypes={className:b.default.string,vertical:b.default.bool,offset:b.default.number,style:b.default.object,disabled:b.default.bool,min:b.default.number,max:b.default.number,value:b.default.number},e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=o(a),l=n(35),u=o(l),s=n(6),c=o(s),f=n(2),d=o(f),p=n(5),h=o(p),v=n(4),m=o(v),g=n(3),y=o(g),b=n(1),_=o(b),C=n(10),x=o(C),S=n(7),O=o(S),k=n(383),w=o(k),P=n(114),T=o(P),E=n(115),M=o(E),N=n(72),j=r(N),D=function(e){function t(e){(0,d.default)(this,t);var n=(0,m.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onEnd=function(){n.setState({handle:null}),n.removeDocumentEvents(),n.props.onAfterChange(n.getValue())};var r=e.count,o=e.min,a=e.max,i=Array.apply(null,Array(r+1)).map(function(){return o}),l="defaultValue"in e?e.defaultValue:i,u=void 0!==e.value?e.value:l,s=u.map(function(e){return n.trimAlignValue(e)}),c=s[0]===a?0:s.length-1;return n.state={handle:null,recent:c,bounds:s},n}return(0,y.default)(t,e),(0,h.default)(t,[{key:"componentWillReceiveProps",value:function(e){var t=this;if(("value"in e||"min"in e||"max"in e)&&(this.props.min!==e.min||this.props.max!==e.max||!(0,w.default)(this.props.value,e.value))){var n=this.state.bounds,r=e.value||n,o=r.map(function(n){return t.trimAlignValue(n,e)});o.length===n.length&&o.every(function(e,t){return e===n[t]})||(this.setState({bounds:o}),n.some(function(t){return j.isValueOutOfRange(t,e)})&&this.props.onChange(o))}}},{key:"onChange",value:function(e){var t=this.props,n=!("value"in t);n?this.setState(e):void 0!==e.handle&&this.setState({handle:e.handle});var r=(0,c.default)({},this.state,e),o=r.bounds;t.onChange(o)}},{key:"onStart",value:function(e){var t=this.props,n=this.state,r=this.getValue();t.onBeforeChange(r);var o=this.calcValueByPos(e);this.startValue=o,this.startPosition=e;var a=this.getClosestBound(o),i=this.getBoundNeedMoving(o,a);this.setState({handle:i,recent:i});var l=r[i];if(o!==l){var s=[].concat((0,u.default)(n.bounds));s[i]=o,this.onChange({bounds:s})}}},{key:"onMove",value:function(e,t){j.pauseEvent(e);var n=this.props,r=this.state,o=this.calcValueByPos(t),a=r.bounds[r.handle];if(o!==a){var i=[].concat((0,u.default)(r.bounds));i[r.handle]=o;var l=r.handle;if(n.pushable!==!1){var s=r.bounds[l];this.pushSurroundingHandles(i,l,s)}else n.allowCross&&(i.sort(function(e,t){return e-t}),l=i.indexOf(o));this.onChange({handle:l,bounds:i})}}},{key:"getValue",value:function(){return this.state.bounds}},{key:"getClosestBound",value:function(e){for(var t=this.state.bounds,n=0,r=1;r<t.length-1;++r)e>t[r]&&(n=r);return Math.abs(t[n+1]-e)<Math.abs(t[n]-e)&&(n+=1),n}},{key:"getBoundNeedMoving",value:function(e,t){var n=this.state,r=n.bounds,o=n.recent,a=t,i=r[t+1]===r[t];return i&&(a=o),i&&e!==r[t+1]&&(a=e<r[t+1]?t:t+1),a}},{key:"getLowerBound",value:function(){return this.state.bounds[0]}},{key:"getUpperBound",value:function(){var e=this.state.bounds;return e[e.length-1]}},{key:"getPoints",value:function(){var e=this.props,t=e.marks,n=e.step,r=e.min,o=e.max,a=this._getPointsCache;if(!a||a.marks!==t||a.step!==n){var i=(0,c.default)({},t);if(null!==n)for(var l=r;l<=o;l+=n)i[l]=l;var u=Object.keys(i).map(parseFloat);u.sort(function(e,t){return e-t}),this._getPointsCache={marks:t,step:n,points:u}}return this._getPointsCache.points}},{key:"pushSurroundingHandles",value:function(e,t,n){var r=this.props.pushable,o=e[t],a=0;if(e[t+1]-o<r&&(a=1),o-e[t-1]<r&&(a=-1),0!==a){var i=t+a,l=a*(e[i]-o);this.pushHandle(e,i,a,r-l)||(e[t]=n)}}},{key:"pushHandle",value:function(e,t,n,r){for(var o=e[t],a=e[t];n*(a-o)<r;){if(!this.pushHandleOnePoint(e,t,n))return e[t]=o,!1;a=e[t]}return!0}},{key:"pushHandleOnePoint",value:function(e,t,n){var r=this.getPoints(),o=r.indexOf(e[t]),a=o+n;if(a>=r.length||a<0)return!1;var i=t+n,l=r[a],u=this.props.pushable,s=n*(e[i]-l);return!!this.pushHandle(e,i,n,u-s)&&(e[t]=l,!0)}},{key:"trimAlignValue",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(0,c.default)({},this.props,t),r=j.ensureValueInRange(e,n),o=this.ensureValueNotConflict(r,n);return j.ensureValuePrecision(o,n)}},{key:"ensureValueNotConflict",value:function(e,t){var n=t.allowCross,r=this.state||{},o=r.handle,a=r.bounds;if(!n&&null!=o){if(o>0&&e<=a[o-1])return a[o-1];if(o<a.length-1&&e>=a[o+1])return a[o+1]}return e}},{key:"render",value:function(){var e=this,t=this.state,n=t.handle,r=t.bounds,o=this.props,a=o.prefixCls,l=o.vertical,u=o.included,s=o.disabled,c=o.min,f=o.max,d=o.handle,p=o.trackStyle,h=o.handleStyle,v=r.map(function(t){return e.calcOffset(t)}),m=a+"-handle",g=r.map(function(t,r){var o;return d({className:(0,O.default)((o={},(0,i.default)(o,m,!0),(0,i.default)(o,m+"-"+(r+1),!0),o)),vertical:l,offset:v[r],value:t,dragging:n===r,index:r,min:c,max:f,disabled:s,style:h[r],ref:function(t){return e.saveHandle(r,t)}})}),y=r.slice(0,-1).map(function(e,t){var n,r=t+1,o=(0,O.default)((n={},(0,i.default)(n,a+"-track",!0),(0,i.default)(n,a+"-track-"+r,!0),n));return _.default.createElement(T.default,{className:o,vertical:l,included:u,offset:v[r-1],length:v[r]-v[r-1],style:p[t],key:r})});return{tracks:y,handles:g}}}]),t}(_.default.Component);D.displayName="Range",D.propTypes={defaultValue:x.default.arrayOf(x.default.number),value:x.default.arrayOf(x.default.number),count:x.default.number,pushable:x.default.oneOfType([x.default.bool,x.default.number]),allowCross:x.default.bool,disabled:x.default.bool},D.defaultProps={count:1,allowCross:!0,pushable:!1},t.default=(0,M.default)(D),e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=o(a),l=n(2),u=o(l),s=n(5),c=o(s),f=n(4),d=o(f),p=n(3),h=o(p),v=n(1),m=o(v),g=n(10),y=o(g),b=n(48),_=(o(b),n(114)),C=o(_),x=n(115),S=o(x),O=n(72),k=r(O),w=function(e){function t(e){(0,u.default)(this,t);var n=(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onEnd=function(){n.setState({dragging:!1}),n.removeDocumentEvents(),n.props.onAfterChange(n.getValue())};var r=void 0!==e.defaultValue?e.defaultValue:e.min,o=void 0!==e.value?e.value:r;return n.state={value:n.trimAlignValue(o),dragging:!1},n}return(0,h.default)(t,e),(0,c.default)(t,[{key:"componentWillReceiveProps",value:function(e){if("value"in e||"min"in e||"max"in e){var t=this.state.value,n=void 0!==e.value?e.value:t,r=this.trimAlignValue(n,e);r!==t&&(this.setState({value:r}),k.isValueOutOfRange(n,e)&&this.props.onChange(r))}}},{key:"onChange",value:function(e){var t=this.props,n=!("value"in t);n&&this.setState(e);var r=e.value;t.onChange(r)}},{key:"onStart",value:function(e){this.setState({dragging:!0});var t=this.props,n=this.getValue();t.onBeforeChange(n);var r=this.calcValueByPos(e);this.startValue=r,this.startPosition=e,r!==n&&this.onChange({value:r})}},{key:"onMove",value:function(e,t){k.pauseEvent(e);var n=this.state,r=this.calcValueByPos(t),o=n.value;r!==o&&this.onChange({value:r})}},{key:"getValue",value:function(){return this.state.value}},{key:"getLowerBound",value:function(){return this.props.min}},{key:"getUpperBound",value:function(){return this.state.value}},{key:"trimAlignValue",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(0,i.default)({},this.props,t),r=k.ensureValueInRange(e,n);return k.ensureValuePrecision(r,n)}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.vertical,o=t.included,a=t.disabled,l=t.minimumTrackStyle,u=t.trackStyle,s=t.handleStyle,c=t.min,f=t.max,d=t.handle,p=this.state,h=p.value,v=p.dragging,g=this.calcOffset(h),y=d({className:n+"-handle",vertical:r,offset:g,value:h,dragging:v,disabled:a,min:c,max:f,style:s[0]||s,ref:function(t){return e.saveHandle(0,t)}}),b=u[0]||u,_=m.default.createElement(C.default,{className:n+"-track",vertical:r,included:o,offset:0,length:g,style:(0,i.default)({},l,b)});return{tracks:_,handles:y}}}]),t}(m.default.Component);w.propTypes={defaultValue:y.default.number,value:y.default.number,disabled:y.default.bool},t.default=(0,S.default)(w),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(17),l=r(i),u=n(8),s=r(u),c=n(1),f=r(c),d=n(7),p=r(d),h=function(e){var t=e.className,n=e.vertical,r=e.marks,o=e.included,i=e.upperBound,u=e.lowerBound,c=e.max,d=e.min,h=Object.keys(r),v=h.length,m=v>1?100/(v-1):100,g=.9*m,y=c-d,b=h.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var c,h=!o&&e===i||o&&e<=i&&e>=u,v=(0,p.default)((c={},(0,s.default)(c,t+"-text",!0),(0,s.default)(c,t+"-text-active",h),c)),m={marginBottom:"-50%",bottom:(e-d)/y*100+"%"},b={width:g+"%",marginLeft:-g/2+"%",left:(e-d)/y*100+"%"},_=n?m:b,C=r[e],x="object"===("undefined"==typeof C?"undefined":(0,l.default)(C))&&!f.default.isValidElement(C),S=x?C.label:C,O=x?(0,a.default)({},_,C.style):_;return f.default.createElement("span",{className:v,style:O,key:e},S)});return f.default.createElement("div",{className:t},b)};t.default=h,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(6),l=r(i),u=n(1),s=r(u),c=n(7),f=r(c),d=n(48),p=r(d),h=function(e,t,n,r,o,a){(0,p.default)(!n||r>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var i=Object.keys(t).map(parseFloat);if(n)for(var l=o;l<=a;l+=r)i.indexOf(l)>=0||i.push(l);return i},v=function(e){var t=e.prefixCls,n=e.vertical,r=e.marks,o=e.dots,i=e.step,u=e.included,c=e.lowerBound,d=e.upperBound,p=e.max,v=e.min,m=e.dotStyle,g=e.activeDotStyle,y=p-v,b=h(n,r,o,i,v,p).map(function(e){var r,o=Math.abs(e-v)/y*100+"%",i=!u&&e===d||u&&e<=d&&e>=c,p=n?(0,l.default)({bottom:o},m):(0,l.default)({left:o},m);i&&(p=(0,l.default)({},p,g));var h=(0,f.default)((r={},(0,a.default)(r,t+"-dot",!0),(0,a.default)(r,t+"-dot-active",i),r));return s.default.createElement("span",{className:h,style:p,key:e})});return s.default.createElement("div",{className:t+"-step"},b)};t.default=v,e.exports=t.default},function(e,t){e.exports=function(e,t,n,r){var o=n?n.call(r,e,t):void 0;if(void 0!==o)return!!o;if(e===t)return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;var a=Object.keys(e),i=Object.keys(t);if(a.length!==i.length)return!1;for(var l=Object.prototype.hasOwnProperty.bind(t),u=0;u<a.length;u++){var s=a[u];if(!l(s))return!1;var c=e[s],f=t[s];if(o=n?n.call(r,c,f,s):void 0,o===!1||void 0===o&&c!==f)return!1}return!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){for(var n=e.matches||e.webkitMatchesSelector||e.mozMatchesSelector||e.msMatchesSelector;e;){if(n.call(e,t))return e;e=e.parentElement}return null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(8),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v),g=n(1),y=r(g),b=n(11),_=r(b),C=n(71),x=r(C),S=n(7),O=r(S),k=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},w=function(e){function t(e){(0,c.default)(this,t);var n=(0,h.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onCloseSwipe=function(e){if(n.openedLeft||n.openedRight){var t=o(e.target,"."+n.props.prefixCls+"-actions");t||(e.preventDefault(),n.close())}},n.onPanStart=function(e){var t=e.direction,r=e.moveStatus,o=r.x,a=2===t,i=4===t;if(a||i){var l=n.props,u=l.left,s=l.right;n.needShowRight=a&&s.length>0,n.needShowLeft=i&&u.length>0,n.left&&(n.left.style.visibility=n.needShowRight?"hidden":"visible"),n.right&&(n.right.style.visibility=n.needShowLeft?"hidden":"visible"),(n.needShowLeft||n.needShowRight)&&(n.swiping=!0,n.setState({swiping:n.swiping}),n._setStyle(o))}},n.onPanMove=function(e){var t=e.moveStatus,r=t.x;n.swiping&&n._setStyle(r)},n.onPanEnd=function(e){if(n.swiping){var t=e.moveStatus,r=t.x,o=n.needShowRight&&Math.abs(r)>n.btnsRightWidth/2,a=n.needShowLeft&&Math.abs(r)>n.btnsLeftWidth/2;o?n.doOpenRight():a?n.doOpenLeft():n.close(),n.swiping=!1,n.setState({swiping:n.swiping}),n.needShowLeft=!1,n.needShowRight=!1}},n.doOpenLeft=function(){n.open(n.btnsLeftWidth,!0,!1)},n.doOpenRight=function(){n.open(-n.btnsRightWidth,!0,!1)},n._setStyle=function(e){var t=e>0?n.btnsLeftWidth:-n.btnsRightWidth,r=n._getContentEasing(e,t),o="translate3d("+r+"px, 0px, 0px)";n.content.style.transform=o,n.cover&&(n.cover.style.display=Math.abs(e)>0?"block":"none",n.cover.style.transform=o)},n.open=function(e,t,r){n.openedLeft||n.openedRight||!n.props.onOpen||n.props.onOpen(),n.openedLeft=t,n.openedRight=r,n._setStyle(e)},n.close=function(){(n.openedLeft||n.openedRight)&&n.props.onClose&&n.props.onClose(),n._setStyle(0),n.openedLeft=!1,n.openedRight=!1},n.state={swiping:!1},n.openedLeft=!1,n.openedRight=!1,n}return(0,m.default)(t,e),(0,d.default)(t,[{key:"componentDidMount",value:function(){this.btnsLeftWidth=this.left?this.left.offsetWidth:0,this.btnsRightWidth=this.right?this.right.offsetWidth:0,document.body.addEventListener("touchstart",this.onCloseSwipe,!0)}},{key:"componentWillUnmount",value:function(){document.body.removeEventListener("touchstart",this.onCloseSwipe,!0)}},{key:"onBtnClick",value:function(e,t){var n=t.onPress;n&&n(e),this.props.autoClose&&this.close()}},{key:"_getContentEasing",value:function(e,t){var n=Math.abs(e)-Math.abs(t),r=n>0,o=t>0?1:-1;return r?(e=t+Math.pow(n,.85)*o,Math.abs(e)>Math.abs(t)?t:e):e}},{key:"renderButtons",value:function(e,t){var n=this,r=this.props.prefixCls;return e&&e.length?y.default.createElement("div",{className:r+"-actions "+r+"-actions-"+t,ref:function(e){return n[t]=e}},e.map(function(e,t){return y.default.createElement("div",{key:t,className:r+"-btn "+(e.hasOwnProperty("className")?e.className:""),style:e.style,role:"button",onClick:function(t){return n.onBtnClick(t,e)}},y.default.createElement("div",{className:r+"-btn-text"},e.text||"Click"))})):null}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.left,o=t.right,a=t.disabled,l=t.children,s=k(t,["prefixCls","left","right","disabled","children"]),c=(s.autoClose,s.onOpen,s.onClose,k(s,["autoClose","onOpen","onClose"])),f=(0,O.default)(n,(0,u.default)({},n+"-swiping",this.state.swiping)),d={ref:function(t){return e.content=_.default.findDOMNode(t)}};return!r.length&&!o.length||a?y.default.createElement("div",(0,i.default)({},d,c),l):y.default.createElement("div",(0,i.default)({className:f},c),y.default.createElement("div",{className:n+"-cover",ref:function(t){return e.cover=t}}),this.renderButtons(r,"left"),this.renderButtons(o,"right"),y.default.createElement(x.default,(0,i.default)({onPanStart:this.onPanStart,onPanMove:this.onPanMove,onPanEnd:this.onPanEnd,onSwipeLeft:this.doOpenRight,onSwipeRight:this.doOpenLeft,direction:"horizontal"},d),y.default.createElement("div",{className:n+"-content"},l)))}}]),t}(y.default.Component);t.default=w,w.defaultProps={prefixCls:"rc-swipeout",autoClose:!1,disabled:!1,left:[],right:[],onOpen:function(){},onClose:function(){}},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(384);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}}),e.exports=t.default},function(e,t){"use strict";function n(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(438),a={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=a},function(e,t){"use strict";function n(){var e=[].slice.call(arguments,0);return 1===e.length?e[0]:function(){for(var t=0;t<e.length;t++)e[t]&&e[t].apply&&e[t].apply(this,arguments)}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function l(e,t){function n(){o&&(clearTimeout(o),o=null)}function r(){n(),o=setTimeout(e,t)}var o=void 0;return r.clear=n,r}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=n(1),c=r(s),f=n(11),d=r(f),p=n(302),h=r(p),v=n(73),m=r(v),g=n(391),y=r(g),b=function(e){function t(){o(this,t);var e=a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.forceAlign=function(){var t=e.props;if(!t.disabled){var n=d.default.findDOMNode(e);t.onAlign(n,(0,h.default)(n,t.target(),t.align))}},e}return i(t,e),u(t,[{key:"componentDidMount",value:function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()}},{key:"componentDidUpdate",value:function(e){var t=!1,n=this.props;if(!n.disabled)if(e.disabled||e.align!==n.align)t=!0;else{var r=e.target(),o=n.target();(0,y.default)(r)&&(0,y.default)(o)?t=!1:r!==o&&(t=!0)}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()}},{key:"componentWillUnmount",value:function(){this.stopMonitorWindowResize()}},{key:"startMonitorWindowResize",value:function(){this.resizeHandler||(this.bufferMonitor=l(this.forceAlign,this.props.monitorBufferTime),this.resizeHandler=(0,m.default)(window,"resize",this.bufferMonitor))}},{key:"stopMonitorWindowResize",value:function(){this.resizeHandler&&(this.bufferMonitor.clear(),this.resizeHandler.remove(),this.resizeHandler=null)}},{key:"render",value:function(){var e=this.props,t=e.childrenProps,n=e.children,r=c.default.Children.only(n);if(t){var o={};for(var a in t)t.hasOwnProperty(a)&&(o[a]=this.props[t[a]]);return c.default.cloneElement(r,o)}return r}}]),t}(s.Component);b.defaultProps={target:function(){return window},onAlign:function(){},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1},t.default=b,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(389),a=r(o);t.default=a.default,e.exports=t.default},function(e,t){"use strict";function n(e){return null!=e&&e==e.window}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.StateType=void 0;var o=n(6),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(2),p=r(d),h=n(1),v=r(h),m=n(39),g=r(m),y=n(394),b=r(y),_=n(116),C=r(_),x=n(396),S=r(x),O=n(398),k=r(O),w=n(395),P=r(w),T=n(397),E=r(T),M=n(74),N=n(45),j=r(N),D=t.StateType=function e(){(0,p.default)(this,e),this.showTimePicker=!1,this.startDate=void 0,this.endDate=void 0,this.disConfirmBtn=!0,this.clientHight=0},L=function(e){function t(e){(0,p.default)(this,t);var n=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.selectDate=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=arguments[2],o=arguments[3];if(!e)return{};var i={},l=n.props,u=l.type,s=l.pickTime,c=l.defaultTimeValue,f=l.locale,d=void 0===f?{}:f,p=s&&!t?(0,M.mergeDateTime)(e,c):e;switch(u){case"one":i=(0,a.default)({},i,{startDate:p,disConfirmBtn:!1}),s&&(i=(0,a.default)({},i,{timePickerTitle:d.selectTime,showTimePicker:!0}));break;case"range":!r||o?(i=(0,a.default)({},i,{startDate:p,endDate:void 0,disConfirmBtn:!0}),s&&(i=(0,a.default)({},i,{timePickerTitle:d.selectStartTime,showTimePicker:!0}))):i=(0,a.default)({},i,{timePickerTitle:+p>=+r?d.selectEndTime:d.selectStartTime,disConfirmBtn:!1,endDate:s&&!t&&+p>=+r?new Date(+(0,M.mergeDateTime)(p,r)+36e5):p})}return i},n.onSelectedDate=function(e){var t=n.state,r=t.startDate,o=t.endDate;n.setState(n.selectDate(e,!1,r,o))},n.onSelectHasDisableDate=function(e){n.onClear(),n.props.onSelectHasDisableDate&&n.props.onSelectHasDisableDate(e)},n.onClose=function(){n.setState(new D)},n.onCancel=function(){n.onClose(),n.props.onCancel&&n.props.onCancel()},n.onConfirm=function(){n.onClose();var e=n.props.onConfirm,t=n.state,r=t.startDate,o=t.endDate;return r&&o&&+r>+o?e&&e(o,r):void(e&&e(r,o))},n.onTimeChange=function(e){var t=n.state,r=t.startDate,o=t.endDate;o?n.setState({endDate:e}):r&&n.setState({startDate:e})},n.onClear=function(){n.setState({startDate:void 0,endDate:void 0,showTimePicker:!1})},n.shortcutSelect=function(e,t){var r=n.selectDate(e,!0);n.setState((0,a.default)({},r,n.selectDate(t,!0,r.startDate),{showTimePicker:!1}))},n.setClientHeight=function(e){n.setState({clientHight:e})},n.state=new D,n}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.type,n=e.locale,r=void 0===n?{}:n,o=e.prefixCls,a=e.visible,i=e.pickTime,l=e.showShortcut,u=e.renderHeader,s=e.infiniteOpt,c=e.initalMonths,f=e.defaultDate,d=e.minDate,p=e.maxDate,h=e.getDateExtra,m=e.rowSize,y=e.defaultTimeValue,_=e.renderShortcut,x=e.enterDirection,O=e.timePickerPrefixCls,w=e.timePickerPickerPrefixCls,T=e.style,M=this.state,N=M.showTimePicker,j=M.timePickerTitle,D=M.startDate,L=M.endDate,R=M.disConfirmBtn,I=M.clientHight,A={locale:r,showClear:!!D,onCancel:this.onCancel,onClear:this.onClear};return v.default.createElement("div",{className:""+o,style:T},v.default.createElement(g.default,{showProp:"visible",transitionName:"fade"},v.default.createElement(P.default,{className:"mask",visible:!!a})),v.default.createElement(g.default,{showProp:"visible",transitionName:"horizontal"===x?"slideH":"slideV"},v.default.createElement(P.default,{className:"content",visible:!!a},u?u(A):v.default.createElement(E.default,A),v.default.createElement(C.default,{locale:r,type:t,prefixCls:o,infiniteOpt:s,initalMonths:c,defaultDate:f,minDate:d,maxDate:p,getDateExtra:h,onCellClick:this.onSelectedDate,onSelectHasDisableDate:this.onSelectHasDisableDate,onLayout:this.setClientHeight,startDate:D,endDate:L,rowSize:m}),N&&v.default.createElement(b.default,{prefixCls:O,pickerPrefixCls:w,locale:r,title:j,defaultValue:y,value:L?L:D,onValueChange:this.onTimeChange,minDate:d,maxDate:p,clientHeight:I}),l&&!N&&(_?_(this.shortcutSelect):v.default.createElement(k.default,{locale:r,onSelect:this.shortcutSelect})),D&&v.default.createElement(S.default,{type:t,locale:r,startDateTime:D,endDateTime:L,onConfirm:this.onConfirm,disableBtn:R,formatStr:i?r.dateTimeFormat:r.dateFormat}))))}}]),t}(v.default.PureComponent);t.default=L,L.DefaultHeader=E.default,L.DefaultShortcut=k.default,L.defaultProps={visible:!1,showHeader:!0,locale:j.default,pickTime:!1,showShortcut:!1,prefixCls:"rmc-calendar",type:"range",defaultTimeValue:new Date(2e3,0,1,8)}},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(35),i=o(a),l=n(2),u=o(l),s=n(5),c=o(s),f=n(4),d=o(f),p=n(3),h=o(p),v=n(1),m=r(v),g=n(117),y=n(74),b=n(45),_=o(b),C=function(e){function t(e){(0,u.default)(this,t);var n=(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.visibleMonth=[],n.getDateWithoutTime=function(e){return e?+new Date(e.getFullYear(),e.getMonth(),e.getDate()):0},n.genWeekData=function(e){var t=n.getDateWithoutTime(n.props.minDate),r=n.getDateWithoutTime(n.props.maxDate)||Number.POSITIVE_INFINITY,o=[],a=n.getMonthDate(e,1).firstDate,i=e,l=[];o.push(l);var u=i.getDay();if(u>0)for(var s=0;s<u;s++)l.push({});for(;i<a;){7===l.length&&(l=[],o.push(l));var c=i.getDate(),f=+i;l.push({tick:f,dayOfMonth:c,selected:g.Models.SelectType.None,isFirstOfMonth:1===c,isLastOfMonth:!1,outOfDate:f<t||f>r}),i=new Date(i.getTime()+864e5)}return l[l.length-1].isLastOfMonth=!0,o},n.selectDateRange=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o=n.props,a=o.getDateExtra,i=o.type,l=o.onSelectHasDisableDate;"one"===i&&(t=void 0);var u=n.getDateWithoutTime(e),s=n.getDateWithoutTime(t),c=!s||u<s?u:s,f=s&&u>s?u:s,d=n.getMonthDate(new Date(c)).firstDate,p=f?new Date(f):n.getMonthDate(new Date(c)).lastDate,h=[],v=!1;n.state.months.filter(function(e){return e.firstDate>=d&&e.firstDate<=p}).forEach(function(e){e.weeks.forEach(function(e){return e.filter(function(e){return f?e.tick&&e.tick>=c&&e.tick<=f:e.tick&&n.inDate(c,e.tick)}).forEach(function(e){var t=e.selected;if(r)e.selected=g.Models.SelectType.None;else{var o=a&&a(new Date(e.tick))||{};(e.outOfDate||o.disable)&&h.push(e.tick),n.inDate(c,e.tick)?"one"===i?e.selected=g.Models.SelectType.Single:f?c!==f?e.selected=g.Models.SelectType.Start:e.selected=g.Models.SelectType.All:e.selected=g.Models.SelectType.Only:n.inDate(f,e.tick)?e.selected=g.Models.SelectType.End:e.selected=g.Models.SelectType.Middle}v=v||e.selected!==t})}),v&&e.componentRef&&(e.componentRef.updateWeeks(),e.componentRef.forceUpdate())}),h.length>0&&(l?l(h.map(function(e){return new Date(e)})):console.warn("Unusable date. You can handle by onSelectHasDisableDate.",h))},n.computeVisible=function(e,t){var r=!1,o=2*e,a=e,i=function(n){return n.y&&n.height&&n.y+n.height>t-o&&n.y<t+e+o};if(n.props.infiniteOpt&&n.visibleMonth.length>12&&(n.visibleMonth=n.visibleMonth.filter(i).sort(function(e,t){return+e.firstDate-+t.firstDate})),n.visibleMonth.length>0){var l=n.visibleMonth[n.visibleMonth.length-1];if(void 0!==l.y&&l.height&&l.y+l.height<t+e+a){for(var u=n.state.months.indexOf(l),s=1;s<=2;s++){var c=u+s;c<n.state.months.length&&n.visibleMonth.indexOf(n.state.months[c])<0?n.visibleMonth.push(n.state.months[c]):n.canLoadNext()&&n.genMonthData(void 0,1)}r=!0}var f=n.visibleMonth[0];if(void 0!==f.y&&f.height&&f.y>t-a)for(var d=n.state.months.indexOf(f),p=1;p<=2;p++){var h=d-p;h>=0&&n.visibleMonth.indexOf(n.state.months[h])<0&&(n.visibleMonth.unshift(n.state.months[h]),r=!0)}}else n.state.months.length>0&&(n.visibleMonth=n.state.months.filter(i),r=!0);return r},n.createOnScroll=function(){var e=void 0,t=0,r=0;return function(o){var a=o.client,i=o.top;t=a,r=i,e||(e=setTimeout(function(){e=void 0,n.computeVisible(t,r)&&n.forceUpdate()},64))}},n.onCellClick=function(e){e.tick&&n.props.onCellClick&&n.props.onCellClick(new Date(e.tick))},n.state={months:[]},n}return(0,h.default)(t,e),(0,c.default)(t,[{key:"shouldComponentUpdate",value:function(e,t,n){return!(0,y.shallowEqual)(this.props,e,["startDate","endDate"])||!(0,y.shallowEqual)(this.state,t)||!(0,y.shallowEqual)(this.context,n)}},{key:"componentWillReceiveProps",value:function(e){var t=this.props,n=e;t.startDate===n.startDate&&t.endDate===n.endDate||(t.startDate&&this.selectDateRange(t.startDate,t.endDate,!0),n.startDate&&this.selectDateRange(n.startDate,n.endDate))}},{key:"componentWillMount",value:function(){for(var e=this.props,t=e.initalMonths,n=void 0===t?6:t,r=e.defaultDate,o=0;o<n;o++)this.canLoadNext()&&this.genMonthData(r,o);this.visibleMonth=[].concat((0,i.default)(this.state.months))}},{key:"getMonthDate",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=e.getFullYear(),r=e.getMonth();return{firstDate:new Date(n,r+t,1),lastDate:new Date(n,r+1+t,0)}}},{key:"canLoadPrev",value:function(){var e=this.props.minDate;return!e||this.state.months.length<=0||+this.getMonthDate(e).firstDate<+this.state.months[0].firstDate}},{key:"canLoadNext",value:function(){var e=this.props.maxDate;return!e||this.state.months.length<=0||+this.getMonthDate(e).firstDate>+this.state.months[this.state.months.length-1].firstDate}},{key:"genMonthData",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;e||(e=t>=0?this.state.months[this.state.months.length-1].firstDate:this.state.months[0].firstDate),e||(e=new Date);var n=this.props.locale,r=this.getMonthDate(e,t),o=r.firstDate,a=r.lastDate,i=this.genWeekData(o),l=(0,y.formatDate)(o,n?n.monthTitle:"yyyy/MM",this.props.locale),u={title:l,firstDate:o,lastDate:a,weeks:i};u.component=this.genMonthComponent(u),t>=0?this.state.months.push(u):this.state.months.unshift(u);var s=this.props,c=s.startDate,f=s.endDate;return c&&this.selectDateRange(c,f),u}},{key:"inDate",value:function(e,t){return e<=t&&t<e+864e5}}]),t}(m.Component);t.default=C,C.defaultProps={prefixCls:"rmc-calendar",infinite:!1,infiniteOpt:!1,defaultDate:new Date,initalMonths:6,locale:_.default},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(405),v=r(h),m=function(e){function t(){(0,a.default)(this,t);var e=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onDateChange=function(t){var n=e.props.onValueChange;n&&n(t)},e}return(0,f.default)(t,e),(0,l.default)(t,[{key:"getMinTime",value:function(e){var n=this.props.minDate;return!e||e.getFullYear()>n.getFullYear()||e.getMonth()>n.getMonth()||e.getDate()>n.getDate()?t.defaultProps.minDate:n}},{key:"getMaxTime",value:function(e){var n=this.props.maxDate;return!e||e.getFullYear()<n.getFullYear()||e.getMonth()<n.getMonth()||e.getDate()<n.getDate()?t.defaultProps.maxDate:n}},{key:"render",value:function(){var e=this.props,t=e.locale,n=e.title,r=e.value,o=e.defaultValue,a=e.prefixCls,i=e.pickerPrefixCls,l=e.clientHeight,u=r||o||void 0,s=l&&3*l/8-52||Number.POSITIVE_INFINITY;return p.default.createElement("div",{className:"time-picker"},p.default.createElement("div",{className:"title"},n),p.default.createElement(v.default,{prefixCls:a,pickerPrefixCls:i,style:{height:s>164||s<0?164:s,overflow:"hidden"},mode:"time",date:u,locale:t,minDate:this.getMinTime(u),maxDate:this.getMaxTime(u),onDateChange:this.onDateChange,use12Hours:!0}))}}]),t}(p.default.PureComponent);
t.default=m,m.defaultProps={minDate:new Date(0,0,0,0,0),maxDate:new Date(9999,11,31,23,59,59),defaultValue:new Date(2e3,1,1,8)},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.displayType,r=e.visible;return p.default.createElement("div",{className:t+" animate",style:{display:r?n:"none"}},r&&this.props.children)}}]),t}(p.default.PureComponent);t.default=h,h.defaultProps={className:"",displayType:"flex"},e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=o(a),l=n(5),u=o(l),s=n(4),c=o(s),f=n(3),d=o(f),p=n(1),h=r(p),v=n(74),m=function(e){function t(){(0,i.default)(this,t);var e=(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onConfirm=function(){var t=e.props,n=t.onConfirm,r=t.disableBtn;!r&&n()},e}return(0,d.default)(t,e),(0,u.default)(t,[{key:"formatDate",value:function(e){var t=this.props,n=t.formatStr,r=void 0===n?"":n,o=t.locale;return(0,v.formatDate)(e,r,o)}},{key:"render",value:function(){var e=this.props,t=e.type,n=e.locale,r=e.disableBtn,o=this.props,a=o.startDateTime,i=o.endDateTime;if(a&&i&&+a>+i){var l=a;a=i,i=l}var u=a?this.formatDate(a):n.noChoose,s=i?this.formatDate(i):n.noChoose,c=r?"button button-disable":"button";return"one"===t&&(c+=" button-full"),h.createElement("div",{className:"confirm-panel"},"range"===t&&h.createElement("div",{className:"info"},h.createElement("p",null,n.start,": ",h.createElement("span",{className:a?"":"grey"},u)),h.createElement("p",null,n.end,": ",h.createElement("span",{className:i?"":"grey"},s))),h.createElement("div",{className:c,onClick:this.onConfirm},n.confirm))}}]),t}(h.PureComponent);t.default=m,m.defaultProps={formatStr:"yyyy-MM-dd hh:mm"},e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=o(a),l=n(5),u=o(l),s=n(4),c=o(s),f=n(3),d=o(f),p=n(1),h=r(p),v=function(e){function t(){return(0,i.default)(this,t),(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,d.default)(t,e),(0,u.default)(t,[{key:"render",value:function(){var e=this.props,t=e.title,n=e.locale,r=void 0===n?{}:n,o=e.onCancel,a=e.onClear,i=e.showClear,l=e.closeIcon,u=e.clearIcon;return h.createElement("div",{className:"header"},h.createElement("span",{className:"left",onClick:function(){return o&&o()}},l),h.createElement("span",{className:"title"},t||r.title),i&&h.createElement("span",{className:"right",onClick:function(){return a&&a()}},u||r.clear))}}]),t}(h.PureComponent);t.default=v,v.defaultProps={closeIcon:"X"},e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=o(a),l=n(5),u=o(l),s=n(4),c=o(s),f=n(3),d=o(f),p=n(1),h=r(p),v=function(e){function t(){(0,i.default)(this,t);var e=(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onClick=function(t){var n=e.props.onSelect,r=new Date;switch(t){case"today":n(new Date(r.getFullYear(),r.getMonth(),r.getDate(),0),new Date(r.getFullYear(),r.getMonth(),r.getDate(),12));break;case"yesterday":n(new Date(r.getFullYear(),r.getMonth(),r.getDate()-1,0),new Date(r.getFullYear(),r.getMonth(),r.getDate()-1,12));break;case"lastweek":n(new Date(r.getFullYear(),r.getMonth(),r.getDate()-6,0),new Date(r.getFullYear(),r.getMonth(),r.getDate(),12));break;case"lastmonth":n(new Date(r.getFullYear(),r.getMonth(),r.getDate()-29,0),new Date(r.getFullYear(),r.getMonth(),r.getDate(),12))}},e}return(0,d.default)(t,e),(0,u.default)(t,[{key:"render",value:function(){var e=this,t=this.props.locale;return h.createElement("div",{className:"shortcut-panel"},h.createElement("div",{className:"item",onClick:function(){return e.onClick("today")}},t.today),h.createElement("div",{className:"item",onClick:function(){return e.onClick("yesterday")}},t.yesterday),h.createElement("div",{className:"item",onClick:function(){return e.onClick("lastweek")}},t.lastWeek),h.createElement("div",{className:"item",onClick:function(){return e.onClick("lastmonth")}},t.lastMonth))}}]),t}(h.PureComponent);t.default=v,e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=o(a),l=n(5),u=o(l),s=n(4),c=o(s),f=n(3),d=o(f),p=n(1),h=r(p),v=n(117),m=function(e){function t(e){(0,i.default)(this,t);var n=(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.genWeek=function(e,t){var r=n.props,o=r.getDateExtra,a=r.monthData,i=r.onCellClick,l=r.locale,u=r.rowSize,s="row";"xl"===u&&(s+=" row-xl"),n.state.weekComponents[t]=h.createElement("div",{key:t,className:s},e.map(function(e,t){var n=o&&o(new Date(e.tick))||{},r=n.info,u=n.disable||e.outOfDate,s="date",c="left",f="right",d="info";if(0!==t&&6!==t||(s+=" grey"),u?s+=" disable":r&&(s+=" important"),e.selected){s+=" date-selected";var p=e.selected;switch(p){case v.Models.SelectType.Only:r=l.begin,d+=" date-selected";break;case v.Models.SelectType.All:r=l.begin_over,d+=" date-selected";break;case v.Models.SelectType.Start:r=l.begin,d+=" date-selected",(6===t||e.isLastOfMonth)&&(p=v.Models.SelectType.All);break;case v.Models.SelectType.Middle:0===t||e.isFirstOfMonth?p=e.isLastOfMonth||6===t?v.Models.SelectType.All:v.Models.SelectType.Start:(6===t||e.isLastOfMonth)&&(p=v.Models.SelectType.End);break;case v.Models.SelectType.End:r=l.over,d+=" date-selected",(0===t||e.isFirstOfMonth)&&(p=v.Models.SelectType.All)}switch(p){case v.Models.SelectType.Single:case v.Models.SelectType.Only:case v.Models.SelectType.All:s+=" selected-single";break;case v.Models.SelectType.Start:s+=" selected-start",f+=" date-selected";break;case v.Models.SelectType.Middle:s+=" selected-middle",c+=" date-selected",f+=" date-selected";break;case v.Models.SelectType.End:s+=" selected-end",c+=" date-selected"}}var m=[h.createElement("div",{key:"wrapper",className:"date-wrapper"},h.createElement("span",{className:c}),h.createElement("div",{className:s},e.dayOfMonth),h.createElement("span",{className:f})),h.createElement("div",{key:"info",className:d},r)];return h.createElement("div",{key:t,className:"cell "+(n.cellCls||""),onClick:function(){!u&&i&&i(e,a)}},n.cellRender?n.cellRender(new Date(e.tick)):m)}))},n.updateWeeks=function(e){(e||n.props.monthData).weeks.forEach(function(e,t){n.genWeek(e,t)})},n.setWarpper=function(e){n.wrapperDivDOM=e},n.state={weekComponents:[]},n}return(0,d.default)(t,e),(0,u.default)(t,[{key:"componentWillMount",value:function(){var e=this;this.props.monthData.weeks.forEach(function(t,n){e.genWeek(t,n)})}},{key:"componentWillReceiveProps",value:function(e){this.props.monthData!==e.monthData&&this.updateWeeks(e.monthData)}},{key:"render",value:function(){var e=this.props.monthData.title,t=this.state.weekComponents;return h.createElement("div",{className:"single-month",ref:this.setWarpper},h.createElement("div",{className:"month-title"},e),h.createElement("div",{className:"date"},t))}}]),t}(h.PureComponent);t.default=m,m.defaultProps={rowSize:"normal"},e.exports=t.default},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(2),i=o(a),l=n(5),u=o(l),s=n(4),c=o(s),f=n(3),d=o(f),p=n(1),h=r(p),v=function(e){function t(){return(0,i.default)(this,t),(0,c.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,d.default)(t,e),(0,u.default)(t,[{key:"render",value:function(){return h.createElement("div",{className:"week-panel"},h.createElement("div",{className:"cell cell-grey"},"\u65e5"),h.createElement("div",{className:"cell"},"\u4e00"),h.createElement("div",{className:"cell"},"\u4e8c"),h.createElement("div",{className:"cell"},"\u4e09"),h.createElement("div",{className:"cell"},"\u56db"),h.createElement("div",{className:"cell"},"\u4e94"),h.createElement("div",{className:"cell cell-grey"},"\u516d"))}}]),t}(h.PureComponent);t.default=v,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Locale=t.DatePicker=t.Calendar=void 0;var o=n(392);Object.defineProperty(t,"Calendar",{enumerable:!0,get:function(){return r(o).default}});var a=n(116);Object.defineProperty(t,"DatePicker",{enumerable:!0,get:function(){return r(a).default}});var i=n(45),l=r(i),u=n(402),s=r(u),c={zhCN:l.default,enUS:s.default};t.Locale=c},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={title:"Calendar",today:"Today",month:"Month",year:"Year",am:"AM",pm:"PM",dateTimeFormat:"MM/dd/yyyy w hh:mm",dateFormat:"yyyy/MM/dd w",noChoose:"No Choose",week:["Sun","Mon","Tue","Wed","Thu","Fir","Sat"],clear:"Clear",selectTime:"Select Time",selectStartTime:"Select Start Time",selectEndTime:"Select End Time",start:"Start",end:"End",begin:"Start",over:"End",begin_over:"S/E",confirm:"Confirm",monthTitle:"yyyy/MM",loadPrevMonth:"Load Prev Month",yesterday:"Yesterday",lastWeek:"Last Week",lastMonth:"Last Month"};t.default=n,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(122),g=r(m),y=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onOk=function(t){var n=e.props,r=n.onChange,o=n.onOk;r&&r(t),o&&o(t)},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){return v.default.createElement(g.default,(0,a.default)({picker:this.props.cascader},this.props,{onOk:this.onOk}))}}]),t}(v.default.Component);y.defaultProps={pickerValueProp:"value",pickerValueChangeProp:"onChange"},t.default=y,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(122),g=r(m),y=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onOk=function(t){var n=e.props,r=n.onChange,o=n.onOk;r&&r(t),o&&o(t)},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){return v.default.createElement(g.default,(0,a.default)({picker:this.props.datePicker,value:this.props.date},this.props,{onOk:this.onOk}))}}]),t}(v.default.Component);y.defaultProps={pickerValueProp:"date",pickerValueChangeProp:"onDateChange"},t.default=y,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(75);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}}),e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={year:"",month:"",day:"",hour:"",minute:"",am:"AM",pm:"PM"},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(2),u=r(l),s=n(5),c=r(s),f=n(4),d=r(f),p=n(3),h=r(p),v=n(1),m=r(v),g=n(39),y=r(g),b=n(408),_=r(b),C=function(e){function t(){(0,u.default)(this,t);var e=(0,d.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getDialogElement=function(){var t=e.props,n=t.closable,r=t.prefixCls,o=void 0;t.footer&&(o=m.default.createElement("div",{className:r+"-footer",ref:function(t){return e.footerRef=t}},t.footer));var a=void 0;t.title&&(a=m.default.createElement("div",{className:r+"-header",ref:function(t){return e.headerRef=t}},m.default.createElement("div",{className:r+"-title"},t.title)));var i=void 0;n&&(i=m.default.createElement("button",{onClick:e.close,"aria-label":"Close",className:r+"-close"},m.default.createElement("span",{className:r+"-close-x"})));var l=e.getTransitionName(),u=m.default.createElement(_.default,{key:"dialog-element",role:"document",ref:function(t){return e.dialogRef=t},style:t.style||{},className:r+" "+(t.className||""),visible:t.visible},m.default.createElement("div",{className:r+"-content"},i,a,m.default.createElement("div",{className:r+"-body",style:t.bodyStyle,ref:function(t){return e.bodyRef=t}},t.children),o));return m.default.createElement(y.default,{key:"dialog",showProp:"visible",onAppear:e.onAnimateAppear,onLeave:e.onAnimateLeave,transitionName:l,component:"",transitionAppear:!0},u)},e.onAnimateAppear=function(){document.body.style.overflow="hidden"},e.onAnimateLeave=function(){document.body.style.overflow="",e.wrapRef&&(e.wrapRef.style.display="none"),e.props.onAnimateLeave&&e.props.onAnimateLeave(),e.props.afterClose&&e.props.afterClose()},e.close=function(t){e.props.onClose&&e.props.onClose(t)},e.onMaskClick=function(t){t.target===t.currentTarget&&e.close(t)},e}return(0,h.default)(t,e),(0,c.default)(t,[{key:"getZIndexStyle",value:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e}},{key:"getWrapStyle",value:function(){var e=this.props.wrapStyle||{};return(0,i.default)({},this.getZIndexStyle(),e)}},{key:"getMaskStyle",value:function(){var e=this.props.maskStyle||{};return(0,i.default)({},this.getZIndexStyle(),e)}},{key:"getMaskTransitionName",value:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t}},{key:"getTransitionName",value:function(){var e=this.props,t=e.transitionName,n=e.animation;return!t&&n&&(t=e.prefixCls+"-"+n),t}},{key:"getMaskElement",value:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=m.default.createElement(_.default,{style:this.getMaskStyle(),key:"mask-element",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=m.default.createElement(y.default,{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t}},{key:"render",value:function(){var e=this,t=this.props,n=t.prefixCls,r=t.maskClosable,o=this.getWrapStyle();return t.visible&&(o.display=null),m.default.createElement("div",null,this.getMaskElement(),m.default.createElement("div",(0,i.default)({className:n+"-wrap "+(t.wrapClassName||""),ref:function(t){return e.wrapRef=t},onClick:r?this.onMaskClick:void 0,role:"dialog","aria-labelledby":t.title,style:o},t.wrapProps),this.getDialogElement()))}}]),t}(m.default.Component);t.default=C,C.defaultProps={afterClose:o,className:"",mask:!0,visible:!1,closable:!0,maskClosable:!0,prefixCls:"rmc-dialog",onClose:o},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=function(e){function t(){return(0,l.default)(this,t),(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,p.default)(t,e),(0,s.default)(t,[{key:"shouldComponentUpdate",value:function(e){return!!e.hiddenClassName||!!e.visible}},{key:"render",value:function(){var e=this.props.className;this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName);var t=(0,a.default)({},this.props);return delete t.hiddenClassName,delete t.visible,t.className=e,v.default.createElement("div",(0,a.default)({},t))}}]),t}(v.default.Component);t.default=m,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(6),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=("undefined"!=typeof window&&"ontouchstart"in window,function(e){function t(){(0,s.default)(this,t);var e=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.state={active:!1},e.onTouchStart=function(t){e.triggerEvent("TouchStart",!0,t)},e.onTouchEnd=function(t){e.triggerEvent("TouchEnd",!1,t)},e.onTouchCancel=function(t){e.triggerEvent("TouchCancel",!1,t)},e.onMouseDown=function(t){e.props.onTouchStart&&e.triggerEvent("TouchStart",!0,t),e.triggerEvent("MouseDown",!0,t)},e.onMouseUp=function(t){e.props.onTouchEnd&&e.triggerEvent("TouchEnd",!1,t),e.triggerEvent("MouseUp",!1,t)},e.onMouseLeave=function(t){e.triggerEvent("MouseLeave",!1,t)},e}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentDidUpdate",value:function(){this.props.disabled&&this.state.active&&this.setState({active:!1})}},{key:"triggerEvent",value:function(e,t,n){var r="on"+e;this.props[r]&&this.props[r](n),this.setState({active:t})}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.disabled,r=e.activeClassName,o=e.activeStyle,i=n?void 0:{onTouchStart:this.onTouchStart,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchCancel,onMouseDown:this.onMouseDown,onMouseUp:this.onMouseUp,onMouseLeave:this.onMouseLeave},u=g.default.Children.only(t);if(!n&&this.state.active){var s,c=u.props,f=c.style,d=c.className;o&&(f=(0,l.default)({},f,o));var p=(0,b.default)((s={},(0,a.default)(s,d,!!d),(0,a.default)(s,r,!!r),s));return g.default.cloneElement(u,(0,l.default)({className:p,style:f},i))}return g.default.cloneElement(u,i)}}]),t}(g.default.Component));t.default=_,_.defaultProps={disabled:!1},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(12),v=r(h),m=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},g=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.disabled,r=e.onTouchStart,o=e.onTouchEnd,a=m(e,["prefixCls","disabled","onTouchStart","onTouchEnd"]);return p.default.createElement(v.default,{disabled:n,onTouchStart:r,onTouchEnd:o,activeClassName:t+"-handler-active"},p.default.createElement("span",a))}}]),t}(d.Component);t.default=g,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(e){return e.replace(/[^\w\.-]+/g,"")}Object.defineProperty(t,"__esModule",{value:!0});var i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=200,g=600,y=Number.MAX_SAFE_INTEGER||Math.pow(2,53)-1,b=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onFocus=function(){n.setState({focused:!0});var e=n.props.onFocus;e&&e.apply(void 0,arguments)},n.onBlur=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),o=1;o<t;o++)r[o-1]=arguments[o];n.setState({focused:!1});var a=n.getCurrentValidValue(n.state.inputValue);e.persist(),n.setValue(a,function(){var t=n.props.onBlur;t&&t.apply(void 0,[e].concat(r))})},n.getCurrentValidValue=function(e){var t=e;return t=""===t?"":n.isNotCompleteNumber(t)?n.state.value:n.getValidValue(t),n.toNumber(t)},n.getValidValue=function(e){var t=parseFloat(e);return isNaN(t)?e:(t<n.props.min&&(t=n.props.min),t>n.props.max&&(t=n.props.max),t)},n.setValue=function(e,t){var r=n.isNotCompleteNumber(parseFloat(e))?void 0:parseFloat(e),o=r!==n.state.value||""+r!=""+n.state.inputValue;if("value"in n.props?n.setState({inputValue:n.toPrecisionAsStep(n.state.value)},t):n.setState({value:r,inputValue:n.toPrecisionAsStep(e)},t),o){var a=n.props.onChange;a&&a(r)}},n.getPrecision=function(e){if("precision"in n.props)return n.props.precision;var t=e.toString();if(t.indexOf("e-")>=0)return parseInt(t.slice(t.indexOf("e-")+2),10);var r=0;return t.indexOf(".")>=0&&(r=t.length-t.indexOf(".")-1),r},n.getMaxPrecision=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;if("precision"in n.props)return n.props.precision;var r=n.props.step,o=n.getPrecision(t),a=n.getPrecision(r),i=n.getPrecision(e);return e?Math.max(i,o+a):o+a},n.getPrecisionFactor=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=n.getMaxPrecision(e,t);return Math.pow(10,r)},n.toPrecisionAsStep=function(e){if(n.isNotCompleteNumber(e)||""===e)return e;var t=Math.abs(n.getMaxPrecision(e));return isNaN(t)?e.toString():Number(e).toFixed(t)},n.isNotCompleteNumber=function(e){return isNaN(e)||""===e||null===e||e&&e.toString().indexOf(".")===e.toString().length-1},n.toNumber=function(e){return n.isNotCompleteNumber(e)?e:"precision"in n.props?Number(Number(e).toFixed(n.props.precision)):Number(e)},n.toNumberWhenUserInput=function(e){return(/\.\d*0$/.test(e)||e.length>16)&&n.state.focused?e:n.toNumber(e)},n.stepCompute=function(e,t,r){var o=n.props,a=o.step,i=o.min,l=n.getPrecisionFactor(t,r),u=Math.abs(n.getMaxPrecision(t,r)),s=void 0,c="up"===e?1:-1;return s="number"==typeof t?((l*t+c*l*+a*r)/l).toFixed(u):i===-(1/0)?c*+a:i,n.toNumber(s)},n.step=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1;t&&t.preventDefault();var o=n.props;if(!o.disabled){var a=n.getCurrentValidValue(n.state.inputValue)||0;if(!n.isNotCompleteNumber(a)){var i=n.stepCompute(e,a,r);i>o.max?i=o.max:i<o.min&&(i=o.min),n.setValue(i),n.setState({focused:!0})}}},n.stop=function(){n.autoStepTimer&&clearTimeout(n.autoStepTimer)},n.action=function(e,t,r,o){t.persist&&t.persist(),n.stop(),n.step(e,t,r),n.autoStepTimer=setTimeout(function(){n.action(e,t,r,!0)},o?m:g)},n.down=function(e,t,r){n.action("down",e,t,r)},n.up=function(e,t,r){n.action("up",e,t,r)};var r=void 0;return r="value"in e?e.value:e.defaultValue,r=n.toNumber(r),n.state={inputValue:n.toPrecisionAsStep(r),value:r,focused:e.autoFocus},n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillReceiveProps",value:function(e){if("value"in e){var t=this.state.focused?e.value:this.getValidValue(e.value);this.setState({value:t,inputValue:t})}}},{key:"componentWillUnmount",value:function(){this.stop()}},{key:"onChange",value:function e(t){var n=this.props,r=n.parser,e=n.onChange,o=r&&r(this.getValueFromEvent(t).trim());this.setState({inputValue:o}),e&&e(this.toNumberWhenUserInput(o))}}]),t}(v.default.Component);t.default=b,b.defaultProps={max:y,min:-y,step:1,style:{},onChange:o,onFocus:o,onBlur:o,parser:a},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(e){e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var i=n(8),l=r(i),u=n(6),s=r(u),c=n(2),f=r(c),d=n(5),p=r(d),h=n(4),v=r(h),m=n(3),g=r(m),y=n(1),b=r(y),_=n(7),C=r(_),x=n(411),S=r(x),O=n(410),k=r(O),w=function(e){function t(){(0,f.default)(this,t);var e=(0,v.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.setInput=function(t){e.input=t},e}return(0,g.default)(t,e),(0,p.default)(t,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentWillUpdate",value:function(){try{this.start=this.input.selectionStart,this.end=this.input.selectionEnd}catch(e){}}},{key:"componentDidUpdate",value:function(){if(this.props.focusOnUpDown&&this.state.focused){var e=this.input.setSelectionRange;e&&"function"==typeof e&&void 0!==this.start&&void 0!==this.end&&this.start!==this.end?this.input.setSelectionRange(this.start,this.end):this.focus()}}},{key:"getRatio",value:function(e){var t=1;return e.metaKey||e.ctrlKey?t=.1:e.shiftKey&&(t=10),t}},{key:"getValueFromEvent",value:function(e){return e.target.value}},{key:"focus",value:function(){this.input.focus()}},{key:"formatWrapper",value:function(e){return this.props.formatter?this.props.formatter(e):e}},{key:"render",value:function(){var e,t=(0,s.default)({},this.props),n=t.prefixCls,r=void 0===n?"":n,i=t.disabled,u=t.readOnly,c=t.max,f=t.min,d=(0,C.default)((e={},(0,l.default)(e,r,!0),(0,l.default)(e,t.className,!!t.className),(0,l.default)(e,r+"-disabled",i),(0,l.default)(e,r+"-focused",this.state.focused),e)),p="",h="",v=this.state.value;if(v)if(isNaN(v))p=r+"-handler-up-disabled",h=r+"-handler-down-disabled";else{var m=Number(v);m>=c&&(p=r+"-handler-up-disabled"),m<=f&&(h=r+"-handler-down-disabled")}var g=!t.readOnly&&!t.disabled,y=void 0;y=this.state.focused?this.state.inputValue:this.toPrecisionAsStep(this.state.value),void 0!==y&&null!==y||(y="");var _=void 0,x=void 0;_={onTouchStart:g&&!p?this.up:o,onTouchEnd:this.stop},x={onTouchStart:g&&!h?this.down:o,onTouchEnd:this.stop};var S=this.formatWrapper(y),O=!!p||i||u,w=!!h||i||u;return b.default.createElement("div",{className:d,style:t.style},b.default.createElement("div",{className:r+"-handler-wrap"},b.default.createElement(k.default,(0,s.default)({disabled:O,prefixCls:r,unselectable:!0},_,{role:"button","aria-label":"Increase Value","aria-disabled":!!O,className:r+"-handler "+r+"-handler-up "+p}),this.props.upHandler||b.default.createElement("span",{unselectable:!0,className:r+"-handler-up-inner",onClick:a})),b.default.createElement(k.default,(0,s.default)({disabled:w,prefixCls:r,unselectable:!0},x,{role:"button","aria-label":"Decrease Value","aria-disabled":!!w,className:r+"-handler "+r+"-handler-down "+h}),this.props.downHandler||b.default.createElement("span",{unselectable:!0,className:r+"-handler-down-inner",onClick:a}))),b.default.createElement("div",{className:r+"-input-wrap",role:"spinbutton","aria-valuemin":t.min,"aria-valuemax":t.max,"aria-valuenow":v},b.default.createElement("input",{className:r+"-input",tabIndex:t.tabIndex,autoComplete:"off",onFocus:this.onFocus,onBlur:this.onBlur,autoFocus:t.autoFocus,readOnly:t.readOnly,disabled:t.disabled,max:t.max,min:t.min,step:t.step,onChange:this.onChange,ref:this.setInput,value:S})))}}]),t}(S.default);t.default=w,w.defaultProps=(0,s.default)({},S.default.defaultProps,{focusOnUpDown:!1,useTouch:!1,prefixCls:"rmc-input-number"}),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){window.document.body.scrollTop=e,window.document.documentElement.scrollTop=e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(8),i=r(a),l=n(6),u=r(l),s=n(22),c=r(s),f=n(2),d=r(f),p=n(5),h=r(p),v=n(4),m=r(v),g=n(3),y=r(g),b=n(1),_=r(b),C=n(10),x=r(C),S=n(11),O=r(S),k=n(7),w=r(k),P=n(120),T=r(P),E=n(121),M=function(e){function t(e){(0,d.default)(this,t);var n=(0,m.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return N.call(n),n.state={pageSize:e.pageSize,_delay:!1},n}return(0,y.default)(t,e),(0,h.default)(t,[{key:"componentDidMount",value:function(){this.dataChange(this.props),this.getQsInfo()}},{key:"componentWillReceiveProps",value:function(e){this.props.dataSource!==e.dataSource&&this.dataChange(e)}},{key:"componentDidUpdate",value:function(){this.getQsInfo()}},{key:"componentWillUnmount",value:function(){this._timer&&clearTimeout(this._timer),this._hCache=null}},{key:"renderQuickSearchBar",value:function(e,t){var n=this,r=this.props,o=r.dataSource,a=r.prefixCls,i=o.sectionIdentities.map(function(e){return{value:e,label:o._getSectionHeaderData(o._dataBlob,e)}});return _.default.createElement("ul",{ref:function(e){return n.quickSearchBarRef=e},className:a+"-quick-search-bar",style:t,onTouchStart:this.onTouchStart,onTouchMove:this.onTouchMove,onTouchEnd:this.onTouchEnd,onTouchCancel:this.onTouchEnd},_.default.createElement("li",{"data-qf-target":e.value,onClick:function(){return n.onQuickSearchTop(void 0,e.value)}},e.label),i.map(function(e){return _.default.createElement("li",{key:e.value,"data-qf-target":e.value,onClick:function(){return n.onQuickSearch(e.value)}},e.label)}))}},{key:"render",value:function(){var e,t=this,n=this.state,r=n._delay,o=n.pageSize,a=this.props,l=a.className,s=a.prefixCls,f=a.children,d=a.quickSearchBarTop,p=a.quickSearchBarStyle,h=a.initialListSize,v=void 0===h?Math.min(20,this.props.dataSource.getRowCount()):h,m=a.showQuickSearchIndicator,g=a.renderSectionHeader,y=a.sectionHeaderClassName,b=(0,c.default)(a,["className","prefixCls","children","quickSearchBarTop","quickSearchBarStyle","initialListSize","showQuickSearchIndicator","renderSectionHeader","sectionHeaderClassName"]);return _.default.createElement("div",{className:s+"-container"},r&&this.props.delayActivityIndicator,_.default.createElement(T.default,(0,u.default)({},b,{ref:function(e){return t.indexedListViewRef=e},className:(0,w.default)(s,l),initialListSize:v,pageSize:o,renderSectionHeader:function(e,n){return _.default.cloneElement(g(e,n),{ref:function(e){return t.sectionComponents[n]=e},className:y||s+"-section-header"})}}),f),this.renderQuickSearchBar(d,p),m?_.default.createElement("div",{className:(0,w.default)((e={},(0,i.default)(e,s+"-qsindicator",!0),(0,i.default)(e,s+"-qsindicator-hide",!m||!this.state.showQuickSearchIndicator),e)),ref:function(e){return t.qsIndicatorRef=e}}):null)}}]),t}(_.default.Component);M.propTypes=(0,u.default)({},T.default.propTypes,{children:x.default.any,prefixCls:x.default.string,className:x.default.string,sectionHeaderClassName:x.default.string,quickSearchBarTop:x.default.object,quickSearchBarStyle:x.default.object,onQuickSearch:x.default.func,showQuickSearchIndicator:x.default.bool}),M.defaultProps={prefixCls:"rmc-indexed-list",quickSearchBarTop:{value:"#",label:"#"},onQuickSearch:function(){},showQuickSearchIndicator:!1,delayTime:100,delayActivityIndicator:""};var N=function(){var e=this;this.onQuickSearchTop=function(t,n){e.props.useBodyScroll?o(0):O.default.findDOMNode(e.indexedListViewRef.ListViewRef).scrollTop=0,e.props.onQuickSearch(t,n)},this.onQuickSearch=function(t){var n=O.default.findDOMNode(e.indexedListViewRef.ListViewRef),r=O.default.findDOMNode(e.sectionComponents[t]);e.props.useBodyScroll?o(r.getBoundingClientRect().top-n.getBoundingClientRect().top+(0,E.getOffsetTop)(n)):n.scrollTop+=r.getBoundingClientRect().top-n.getBoundingClientRect().top,e.props.onQuickSearch(t)},this.onTouchStart=function(t){e._target=t.target,e._basePos=e.quickSearchBarRef.getBoundingClientRect(),document.addEventListener("touchmove",e._disableParent,!1),document.body.className=document.body.className+" "+e.props.prefixCls+"-qsb-moving",e.updateIndicator(e._target)},this.onTouchMove=function(t){if(t.preventDefault(),e._target){var n=(0,E._event)(t),r=e._basePos,o=void 0;if(n.clientY>=r.top&&n.clientY<=r.top+e._qsHeight){o=Math.floor((n.clientY-r.top)/e._avgH);var a=void 0;if(o in e._hCache&&(a=e._hCache[o][0]),
a){var i=a.getAttribute("data-qf-target");e._target!==a&&(e.props.quickSearchBarTop.value===i?e.onQuickSearchTop(void 0,i):e.onQuickSearch(i),e.updateIndicator(a)),e._target=a}}}},this.onTouchEnd=function(){e._target&&(document.removeEventListener("touchmove",e._disableParent,!1),document.body.className=document.body.className.replace(new RegExp("\\s*"+e.props.prefixCls+"-qsb-moving","g"),""),e.updateIndicator(e._target,!0),e._target=null)},this.getQsInfo=function(){var t=e.quickSearchBarRef,n=t.offsetHeight,r=[];[].slice.call(t.querySelectorAll("[data-qf-target]")).forEach(function(e){r.push([e])});for(var o=n/r.length,a=0,i=0,l=r.length;i<l;i++)a=i*o,r[i][1]=[a,a+o];e._qsHeight=n,e._avgH=o,e._hCache=r},this.sectionComponents={},this.dataChange=function(t){var n=t.dataSource.getRowCount();n&&(e.setState({_delay:!0}),e._timer&&clearTimeout(e._timer),e._timer=setTimeout(function(){e.setState({pageSize:n,_delay:!1},function(){return e.indexedListViewRef._pageInNewRows()})},t.delayTime))},this.updateIndicator=function(t,n){var r=t;r.getAttribute("data-qf-target")||(r=r.parentNode),e.props.showQuickSearchIndicator&&(e.qsIndicatorRef.innerText=r.innerText.trim(),e.setState({showQuickSearchIndicator:!0}),e._indicatorTimer&&clearTimeout(e._indicatorTimer),e._indicatorTimer=setTimeout(function(){e.setState({showQuickSearchIndicator:!1})},1e3));var o=e.props.prefixCls+"-quick-search-bar-over";e._hCache.forEach(function(e){e[0].className=e[0].className.replace(o,"")}),n||(r.className=r.className+" "+o)},this._disableParent=function(e){e.preventDefault(),e.stopPropagation()}};t.default=M,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n){return e[t][n]}function a(e,t){return e[t]}function i(e){for(var t=0,n=0;n<e.length;n++){var r=e[n];t+=r.length}return t}function l(e){if((0,v.default)(e))return{};for(var t={},n=0;n<e.length;n++){var r=e[n];(0,g.default)(!t[r],"Value appears more than once in array: "+r),t[r]=!0}return t}Object.defineProperty(t,"__esModule",{value:!0});var u=n(2),s=r(u),c=n(5),f=r(c),d=n(70),p=r(d),h=n(354),v=r(h),m=n(48),g=r(m),y=function(){function e(t){(0,s.default)(this,e),(0,p.default)(t&&"function"==typeof t.rowHasChanged,"Must provide a rowHasChanged function."),this._rowHasChanged=t.rowHasChanged,this._getRowData=t.getRowData||o,this._sectionHeaderHasChanged=t.sectionHeaderHasChanged,this._getSectionHeaderData=t.getSectionHeaderData||a,this._dataBlob=null,this._dirtyRows=[],this._dirtySections=[],this._cachedRowCount=0,this.rowIdentities=[],this.sectionIdentities=[]}return(0,f.default)(e,[{key:"cloneWithRows",value:function(e,t){var n=t?[t]:null;return this._sectionHeaderHasChanged||(this._sectionHeaderHasChanged=function(){return!1}),this.cloneWithRowsAndSections({s1:e},["s1"],n)}},{key:"cloneWithRowsAndSections",value:function(t,n,r){(0,p.default)("function"==typeof this._sectionHeaderHasChanged,"Must provide a sectionHeaderHasChanged function with section data."),(0,p.default)(!n||!r||n.length===r.length,"row and section ids lengths must be the same");var o=new e({getRowData:this._getRowData,getSectionHeaderData:this._getSectionHeaderData,rowHasChanged:this._rowHasChanged,sectionHeaderHasChanged:this._sectionHeaderHasChanged});return o._dataBlob=t,n?o.sectionIdentities=n:o.sectionIdentities=Object.keys(t),r?o.rowIdentities=r:(o.rowIdentities=[],o.sectionIdentities.forEach(function(e){o.rowIdentities.push(Object.keys(t[e]))})),o._cachedRowCount=i(o.rowIdentities),o._calculateDirtyArrays(this._dataBlob,this.sectionIdentities,this.rowIdentities),o}},{key:"getRowCount",value:function(){return this._cachedRowCount}},{key:"getRowAndSectionCount",value:function(){return this._cachedRowCount+this.sectionIdentities.length}},{key:"rowShouldUpdate",value:function(e,t){var n=this._dirtyRows[e][t];return(0,g.default)(void 0!==n,"missing dirtyBit for section, row: "+e+", "+t),n}},{key:"getRowData",value:function(e,t){var n=this.sectionIdentities[e],r=this.rowIdentities[e][t];return(0,g.default)(void 0!==n&&void 0!==r,"rendering invalid section, row: "+e+", "+t),this._getRowData(this._dataBlob,n,r)}},{key:"getRowIDForFlatIndex",value:function(e){for(var t=e,n=0;n<this.sectionIdentities.length;n++){if(!(t>=this.rowIdentities[n].length))return this.rowIdentities[n][t];t-=this.rowIdentities[n].length}return null}},{key:"getSectionIDForFlatIndex",value:function(e){for(var t=e,n=0;n<this.sectionIdentities.length;n++){if(!(t>=this.rowIdentities[n].length))return this.sectionIdentities[n];t-=this.rowIdentities[n].length}return null}},{key:"getSectionLengths",value:function(){for(var e=[],t=0;t<this.sectionIdentities.length;t++)e.push(this.rowIdentities[t].length);return e}},{key:"sectionHeaderShouldUpdate",value:function(e){var t=this._dirtySections[e];return(0,g.default)(void 0!==t,"missing dirtyBit for section: "+e),t}},{key:"getSectionHeaderData",value:function(e){if(!this._getSectionHeaderData)return null;var t=this.sectionIdentities[e];return(0,g.default)(void 0!==t,"renderSection called on invalid section: "+e),this._getSectionHeaderData(this._dataBlob,t)}},{key:"_calculateDirtyArrays",value:function(e,t,n){for(var r=l(t),o={},a=0;a<n.length;a++){var i=t[a];(0,g.default)(!o[i],"SectionID appears more than once: "+i),o[i]=l(n[a])}this._dirtySections=[],this._dirtyRows=[];for(var u,s=0;s<this.sectionIdentities.length;s++){var i=this.sectionIdentities[s];u=!r[i];var c=this._sectionHeaderHasChanged;!u&&c&&(u=c(this._getSectionHeaderData(e,i),this._getSectionHeaderData(this._dataBlob,i))),this._dirtySections.push(!!u),this._dirtyRows[s]=[];for(var f=0;f<this.rowIdentities[s].length;f++){var d=this.rowIdentities[s][f];u=!r[i]||!o[i][d]||this._rowHasChanged(this._getRowData(e,i,d),this._getRowData(this._dataBlob,i,d)),this._dirtyRows[s].push(!!u)}}}}]),e}();t.default=y,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(8),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(10),g=r(m),y=n(7),b=r(y),_={prefixCls:g.default.string,className:g.default.string,style:g.default.object,icon:g.default.any,loading:g.default.any,distanceToRefresh:g.default.number,refreshing:g.default.bool,onRefresh:g.default.func.isRequired},C=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.state={active:!1,deactive:!1,loadingState:!1},n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.className,i=n.style,l=n.icon,u=n.loading,s=n.refreshing,c=this.state,f=c.active,d=c.deactive,p=c.loadingState,h=(0,b.default)(o,(e={},(0,a.default)(e,r+"-indicator",!0),(0,a.default)(e,r+"-active",f),(0,a.default)(e,r+"-deactive",d),(0,a.default)(e,r+"-loading",p||s),e));return v.default.createElement("div",{ref:function(e){return t.ptrRef=e},className:h,style:i},v.default.createElement("div",{className:r+"-indicator-icon-wrapper"},l),v.default.createElement("div",{className:r+"-indicator-loading-wrapper"},u))}}]),t}(v.default.Component);C.propTypes=_,C.defaultProps={prefixCls:"list-view-refresh-control",distanceToRefresh:50,refreshing:!1,icon:[v.default.createElement("div",{key:"0",className:"list-view-refresh-control-pull"},"\u2193 \u4e0b\u62c9"),v.default.createElement("div",{key:"1",className:"list-view-refresh-control-release"},"\u2191 \u91ca\u653e")],loading:v.default.createElement("div",null,"loading...")},t.default=C,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(22),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(10),b=r(y),_=n(11),C=r(_),x=n(126),S=r(x),O=n(7),k=r(O),w=n(121),P={children:b.default.any,className:b.default.string,prefixCls:b.default.string,listPrefixCls:b.default.string,listViewPrefixCls:b.default.string,style:b.default.object,contentContainerStyle:b.default.object,onScroll:b.default.func,scrollEventThrottle:b.default.number,refreshControl:b.default.element},T={base:{position:"relative",overflow:"auto",WebkitOverflowScrolling:"touch",flex:1},zScroller:{position:"relative",overflow:"hidden",flex:1}},E=function(e){function t(){var e,n,r,o;(0,s.default)(this,t);for(var a=arguments.length,i=Array(a),l=0;l<a;l++)i[l]=arguments[l];return n=r=(0,p.default)(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(i))),M.call(r),o=n,(0,p.default)(r,o)}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentWillUpdate",value:function(e){this.props.dataSource===e.dataSource&&this.props.initialListSize===e.initialListSize||!this.tsExec||(this.props.useBodyScroll?window.removeEventListener("scroll",this.tsExec):this.props.useZscroller||C.default.findDOMNode(this.ScrollViewRef).removeEventListener("scroll",this.tsExec))}},{key:"componentDidUpdate",value:function(e){var t=this;if(e.refreshControl&&this.props.refreshControl){var n=e.refreshControl.props.refreshing,r=this.props.refreshControl.props.refreshing;!n||r||this._refreshControlTimer?this.manuallyRefresh||n||!r||this.domScroller.scroller.triggerPullToRefresh():this.domScroller.scroller.finishPullToRefresh()}if(this.props.dataSource===e.dataSource&&this.props.initialListSize===e.initialListSize||!this.tsExec||setTimeout(function(){t.props.useBodyScroll?window.addEventListener("scroll",t.tsExec):t.props.useZscroller||C.default.findDOMNode(t.ScrollViewRef).addEventListener("scroll",t.tsExec)},0),this.props.pullUpEnabled){var o=e.pullUpRefreshing,a=this.props.pullUpRefreshing;!o||a||this._pullUpTimer||this.pullUpFinish()}}},{key:"componentDidMount",value:function(){var e=this;if(this.tsExec=this.throttleScroll(),this.onLayout=function(){return e.props.onLayout({nativeEvent:{layout:{width:window.innerWidth,height:window.innerHeight}}})},this.props.useBodyScroll)window.addEventListener("scroll",this.tsExec),window.addEventListener("resize",this.onLayout),this.initPullUp(document.body);else if(this.props.useZscroller)this.renderZscroller();else{var t=C.default.findDOMNode(this.ScrollViewRef);t.addEventListener("scroll",this.tsExec),this.initPullUp(t)}}},{key:"componentWillUnmount",value:function(){if(this.props.useBodyScroll)window.removeEventListener("scroll",this.tsExec),window.removeEventListener("resize",this.onLayout),this.destroyPullUp(document.body);else if(this.props.useZscroller)this.domScroller.destroy();else{var e=C.default.findDOMNode(this.ScrollViewRef);e.removeEventListener("scroll",this.tsExec),this.destroyPullUp(e)}}},{key:"renderZscroller",value:function(){var e=this,t=this.props,n=t.scrollerOptions,r=t.refreshControl,o=n.scrollingComplete,i=n.onScroll,u=(0,l.default)(n,["scrollingComplete","onScroll"]);if(this.domScroller=new S.default(this.getInnerViewNode(),(0,a.default)({scrollingX:!1,onScroll:function(){e.tsExec(),i&&i()},scrollingComplete:function(){e.scrollingComplete(),o&&o()}},u)),r){var s=this.domScroller.scroller,c=r.props,f=c.distanceToRefresh,d=c.onRefresh;s.activatePullToRefresh(f,function(){e.manuallyRefresh=!0,e.overDistanceThenRelease=!1,e.RefreshControlRef&&e.RefreshControlRef.setState({active:!0})},function(){e.manuallyRefresh=!1,e.RefreshControlRef&&e.RefreshControlRef.setState({deactive:e.overDistanceThenRelease,active:!1,loadingState:!1})},function(){e.overDistanceThenRelease=!0,e.RefreshControlRef&&e.RefreshControlRef.setState({deactive:!1,loadingState:!0}),e._refreshControlTimer=setTimeout(function(){e.props.refreshControl.props.refreshing||s.finishPullToRefresh(),e._refreshControlTimer=void 0},1e3),d()}),r.props.refreshing&&s.triggerPullToRefresh()}}},{key:"render",value:function(){var e=this,t=this.props,n=t.children,r=t.className,o=t.prefixCls,i=t.listPrefixCls,l=t.listViewPrefixCls,u=t.style,s=void 0===u?{}:u,c=t.contentContainerStyle,f=void 0===c?{}:c,d=t.useZscroller,p=t.refreshControl,h=t.useBodyScroll,v=t.pullUpEnabled,m=t.pullUpRenderer,y=T.base;h?y={}:d&&(y=T.zScroller);var b=o||l||"",_={ref:function(t){return e.ScrollViewRef=t},style:(0,a.default)({},y,s),className:(0,k.default)(r,b+"-scrollview")},C={ref:function(t){return e.InnerScrollViewRef=t},style:(0,a.default)({position:"absolute",minWidth:"100%"},f),className:(0,k.default)(b+"-scrollview-content",i)};if(p)return g.default.createElement("div",_,g.default.createElement("div",C,g.default.cloneElement(p,{ref:function(t){return e.RefreshControlRef=t}}),n));var x=function(){var t=(0,k.default)(b+"-pull-up-content",!e.state.isTouching&&b+"-pull-up-dropped"),r=e.pullUpDisplay.deactivate;switch(e.state.pullUp){case"activate":case"deactivate":case"release":case"finish":default:r=e.pullUpDisplay[e.state.pullUp]}return g.default.createElement("div",{className:t,ref:function(t){return e.pullUpContentRef=t}},n,g.default.createElement("div",{ref:function(t){return e.pullUpIndicatorRef=t},className:b+"-pull-up-indicator"},m?m(e.state.pullUp):r))};return h?v?(_.style.overflow="hidden",g.default.createElement("div",_,x())):g.default.createElement("div",_,n):v?(C.style.overflow="hidden",g.default.createElement("div",_,g.default.createElement("div",C,x()))):g.default.createElement("div",_,g.default.createElement("div",C,n))}}]),t}(g.default.Component);E.propTypes=P;var M=function(){var e=this;this.getInnerViewNode=function(){return C.default.findDOMNode(e.InnerScrollViewRef)},this.scrollTo=function(){if(e.props.useBodyScroll){var t;(t=window).scrollTo.apply(t,arguments)}else if(e.props.useZscroller){var n;e.domScroller.reflow(),(n=e.domScroller.scroller).scrollTo.apply(n,arguments)}else{var r=C.default.findDOMNode(e.ScrollViewRef);r.scrollLeft=arguments.length<=0?void 0:arguments[0],r.scrollTop=arguments.length<=1?void 0:arguments[1]}},this.throttleScroll=function(){var t=function(){};return e.props.scrollEventThrottle&&e.props.onScroll&&(t=(0,w.throttle)(function(t){e.props.onScroll&&e.props.onScroll(t)},e.props.scrollEventThrottle)),t},this.scrollingComplete=function(){e.props.refreshControl&&e.RefreshControlRef&&e.RefreshControlRef.state.deactive&&e.RefreshControlRef.setState({deactive:!1})},this.state={pullUp:!1,isTouching:!1},this.pullUpStats={activate:"activate",deactivate:"deactivate",release:"release",finish:"finish"},this.pullUpDisplay={activate:"\u91ca\u653e\u5237\u65b0",deactivate:"\u4e0a\u62c9 \u2191",release:"\u52a0\u8f7d\u4e2d...",finish:"\u5b8c\u6210\u5237\u65b0"},this.genEvtHandler=function(t){return{touchstart:e.onTouchStart.bind(e,t),touchmove:e.onTouchMove.bind(e,t),touchend:e.onTouchEnd.bind(e,t),touchcancel:e.onTouchEnd.bind(e,t)}},this.initPullUp=function(t){e.pullUpContentRef&&(0,w.setTransformOrigin)(e.pullUpContentRef.style,"left top"),e._to=e.genEvtHandler(t),Object.keys(e._to).forEach(function(n){t.addEventListener(n,e._to[n])})},this.destroyPullUp=function(t){Object.keys(e._to).forEach(function(n){t.removeEventListener(n,e._to[n])})},this.onTouchStart=function(t,n){e._pullUpScreenY=e._pullUpStartScreenY=n.touches[0].screenY,e._pullUpLastScreenY=0,e.props.pullUpEnabled&&e.setState({isTouching:!0})},this.onTouchMove=function(t,n){if(e.props.pullUpEnabled){var r=n.touches[0].screenY;if(e._pullUpStartScreenY-r>0){var o=void 0;if(e.props.useBodyScroll){var a=document.scrollingElement?document.scrollingElement:t;o=t.scrollHeight-a.scrollTop<=window.innerHeight}else o=t.scrollHeight-t.scrollTop===t.clientHeight;if(o){var i=Math.round(r-e._pullUpScreenY);e._pullUpScreenY=r,e._pullUpLastScreenY+=i,(0,w.setTransform)(e.pullUpContentRef.style,"translate3d(0px,"+e._pullUpLastScreenY+"px,0)"),Math.abs(e._pullUpLastScreenY)<e.props.pullUpDistanceToRefresh?e.state.pullUp!==e.pullUpStats.deactivate&&e.setState({pullUp:e.pullUpStats.deactivate}):e.state.pullUp===e.pullUpStats.deactivate&&e.setState({pullUp:e.pullUpStats.activate})}}}},this.onTouchEnd=function(){e.props.pullUpEnabled&&e.setState({isTouching:!1}),e.state.pullUp===e.pullUpStats.deactivate?e.pullUpFinish():e.state.pullUp===e.pullUpStats.activate&&(e.setState({pullUp:e.pullUpStats.release}),e._pullUpTimer=setTimeout(function(){e.props.pullUpRefreshing||e.pullUpFinish(),e._pullUpTimer=void 0},1e3),e.props.pullUpOnRefresh())},this.pullUpFinish=function(){e._pullUpLastScreenY=0,(0,w.setTransform)(e.pullUpContentRef.style,"translate3d(0px,0px,0)"),e.state.pullUp===e.pullUpStats.release&&e.setState({pullUp:e.pullUpStats.finish})}};t.default=E,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t,n,r){var o=n-t;return o*Math.sqrt(1-(e=e/r-1)*e)+t}function a(e,t,n,r){var o=n-t;return o*e/r+t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(6),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(418),b=r(y),_=n(305),C=r(_),x=n(110),S=r(x),O="ADDITIVE",k=300,w=0,P={ADDITIVE:"ADDITIVE",DESTRUCTIVE:"DESTRUCTIVE"},T=function(e,t,n){null!==e&&"undefined"!=typeof e&&(e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):e["on"+t]=n)},E=function(e,t,n){null!==e&&"undefined"!=typeof e&&(e.removeEventListener?e.removeEventListener(t,n,!1):e.detachEvent?e.detachEvent("on"+t,n):e["on"+t]=null)},M=function(e){function t(e){(0,s.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n._rafCb=function(){var e=n.state;if(0!==e.tweenQueue.length){for(var t=Date.now(),r=[],o=0;o<e.tweenQueue.length;o++){var a=e.tweenQueue[o],i=a.initTime,l=a.config;t-i<l.duration?r.push(a):l.onEnd&&l.onEnd()}n._rafID!==-1&&(n.setState({tweenQueue:r}),n._rafID=(0,S.default)(n._rafCb))}},n.handleClick=function(e){n.clickSafe===!0&&(e.preventDefault(),e.stopPropagation(),e.nativeEvent&&e.nativeEvent.stopPropagation())},n.autoplayIterator=function(){return n.props.wrapAround?n.nextSlide():void(n.state.currentSlide!==n.state.slideCount-n.state.slidesToShow?n.nextSlide():n.stopAutoplay())},n.goToSlide=function(e){var t=n.props,r=t.beforeSlide,o=t.afterSlide;if(e>=g.default.Children.count(n.props.children)||e<0){if(!n.props.wrapAround)return;if(e>=g.default.Children.count(n.props.children))return r(n.state.currentSlide,0),n.setState({currentSlide:0},function(){n.animateSlide(null,null,n.getTargetLeft(null,e),function(){n.animateSlide(null,.01),o(0),n.resetAutoplay(),n.setExternalData()})});var a=g.default.Children.count(n.props.children)-n.state.slidesToScroll;return r(n.state.currentSlide,a),n.setState({currentSlide:a},function(){n.animateSlide(null,null,n.getTargetLeft(null,e),function(){n.animateSlide(null,.01),o(a),n.resetAutoplay(),n.setExternalData()})})}r(n.state.currentSlide,e),n.setState({currentSlide:e},function(){n.animateSlide(),n.props.afterSlide(e),n.resetAutoplay(),n.setExternalData()})},n.nextSlide=function(){var e=g.default.Children.count(n.props.children),t=n.props.slidesToShow;if("auto"===n.props.slidesToScroll&&(t=n.state.slidesToScroll),!(n.state.currentSlide>=e-t)||n.props.wrapAround)if(n.props.wrapAround)n.goToSlide(n.state.currentSlide+n.state.slidesToScroll);else{if(1!==n.props.slideWidth)return n.goToSlide(n.state.currentSlide+n.state.slidesToScroll);n.goToSlide(Math.min(n.state.currentSlide+n.state.slidesToScroll,e-t))}},n.previousSlide=function(){n.state.currentSlide<=0&&!n.props.wrapAround||(n.props.wrapAround?n.goToSlide(n.state.currentSlide-n.state.slidesToScroll):n.goToSlide(Math.max(0,n.state.currentSlide-n.state.slidesToScroll)))},n.onResize=function(){n.setDimensions()},n.onReadyStateChange=function(){n.setDimensions()},n.state={currentSlide:n.props.slideIndex,dragging:!1,frameWidth:0,left:0,slideCount:0,slidesToScroll:n.props.slidesToScroll,slideWidth:0,top:0,tweenQueue:[]},n.touchObject={},n.clickSafe=!0,n}return(0,v.default)(t,e),(0,f.default)(t,[{key:"componentWillMount",value:function(){this.setInitialDimensions()}},{key:"componentDidMount",value:function(){this.setDimensions(),this.bindEvents(),this.setExternalData(),this.props.autoplay&&this.startAutoplay()}},{key:"componentWillReceiveProps",value:function(e){this.setState({slideCount:e.children.length}),this.setDimensions(e),this.props.slideIndex!==e.slideIndex&&e.slideIndex!==this.state.currentSlide&&this.goToSlide(e.slideIndex),this.props.autoplay!==e.autoplay&&(e.autoplay?this.startAutoplay():this.stopAutoplay())}},{key:"componentWillUnmount",value:function(){this.unbindEvents(),this.stopAutoplay(),S.default.cancel(this._rafID),this._rafID=-1}},{key:"tweenState",value:function(e,t){var n=this,r=t.easing,o=t.duration,a=t.delay,i=t.beginValue,l=t.endValue,u=t.onEnd,s=t.stackBehavior;this.setState(function(t){var c=t,f=void 0,d=void 0;if("string"==typeof e)f=e,d=e;else{for(var p=0;p<e.length-1;p++)c=c[e[p]];f=e[e.length-1],d=e.join("|")}var h={easing:r,duration:null==o?k:o,delay:null==a?w:a,beginValue:null==i?c[f]:i,endValue:l,onEnd:u,stackBehavior:s||O},v=t.tweenQueue;return h.stackBehavior===P.DESTRUCTIVE&&(v=t.tweenQueue.filter(function(e){return e.pathHash!==d})),v.push({pathHash:d,config:h,initTime:Date.now()+h.delay}),c[f]=h.endValue,1===v.length&&(n._rafID=(0,S.default)(n._rafCb)),{tweenQueue:v}})}},{key:"getTweeningValue",value:function(e){var t=this.state,n=void 0,r=void 0;if("string"==typeof e)n=t[e],r=e;else{n=t;for(var o=0;o<e.length;o++)n=n[e[o]];r=e.join("|")}for(var a=Date.now(),i=0;i<t.tweenQueue.length;i++){var l=t.tweenQueue[i],u=l.pathHash,s=l.initTime,c=l.config;if(u===r){var f=a-s>c.duration?c.duration:Math.max(0,a-s),d=0===c.duration?c.endValue:c.easing(f,c.beginValue,c.endValue,c.duration),p=d-c.endValue;n+=p}}return n}},{key:"render",value:function(){var e=this,t=g.default.Children.count(this.props.children)>1?this.formatChildren(this.props.children):this.props.children;return g.default.createElement("div",{className:["slider",this.props.className||""].join(" "),ref:"slider",style:(0,l.default)({},this.getSliderStyles(),this.props.style)},g.default.createElement("div",(0,l.default)({className:"slider-frame",ref:"frame",style:this.getFrameStyles()},this.getTouchEvents(),this.getMouseEvents(),{onClick:this.handleClick}),g.default.createElement("ul",{className:"slider-list",ref:"list",style:this.getListStyles()},t)),this.props.decorators?this.props.decorators.map(function(t,n){return g.default.createElement("div",{style:(0,l.default)({},e.getDecoratorStyles(t.position),t.style||{}),className:"slider-decorator-"+n,key:n},g.default.createElement(t.component,{currentSlide:e.state.currentSlide,slideCount:e.state.slideCount,frameWidth:e.state.frameWidth,slideWidth:e.state.slideWidth,slidesToScroll:e.state.slidesToScroll,cellSpacing:e.props.cellSpacing,slidesToShow:e.props.slidesToShow,wrapAround:e.props.wrapAround,nextSlide:e.nextSlide,previousSlide:e.previousSlide,goToSlide:e.goToSlide}))}):null,g.default.createElement("style",{type:"text/css",dangerouslySetInnerHTML:{__html:this.getStyleTagStyles()}}))}},{key:"getTouchEvents",value:function(){var e=this;return this.props.swiping===!1?null:{onTouchStart:function(t){e.touchObject={startX:t.touches[0].pageX,startY:t.touches[0].pageY},e.handleMouseOver()},onTouchMove:function(t){var n=e.swipeDirection(e.touchObject.startX,t.touches[0].pageX,e.touchObject.startY,t.touches[0].pageY);0!==n&&t.preventDefault();var r=e.props.vertical?Math.round(Math.sqrt(Math.pow(t.touches[0].pageY-e.touchObject.startY,2))):Math.round(Math.sqrt(Math.pow(t.touches[0].pageX-e.touchObject.startX,2)));e.touchObject={startX:e.touchObject.startX,startY:e.touchObject.startY,endX:t.touches[0].pageX,endY:t.touches[0].pageY,length:r,direction:n},e.setState({left:e.props.vertical?0:e.getTargetLeft(e.touchObject.length*e.touchObject.direction),top:e.props.vertical?e.getTargetLeft(e.touchObject.length*e.touchObject.direction):0})},onTouchEnd:function(t){e.handleSwipe(t),e.handleMouseOut()},onTouchCancel:function(t){e.handleSwipe(t)}}}},{key:"getMouseEvents",value:function(){var e=this;return this.props.dragging===!1?null:{onMouseOver:function(){e.handleMouseOver()},onMouseOut:function(){e.handleMouseOut()},onMouseDown:function(t){e.touchObject={startX:t.clientX,startY:t.clientY},e.setState({dragging:!0})},onMouseMove:function(t){if(e.state.dragging){var n=e.swipeDirection(e.touchObject.startX,t.clientX,e.touchObject.startY,t.clientY);0!==n&&t.preventDefault();var r=e.props.vertical?Math.round(Math.sqrt(Math.pow(t.clientY-e.touchObject.startY,2))):Math.round(Math.sqrt(Math.pow(t.clientX-e.touchObject.startX,2)));e.touchObject={startX:e.touchObject.startX,startY:e.touchObject.startY,endX:t.clientX,endY:t.clientY,length:r,direction:n},e.setState({left:e.props.vertical?0:e.getTargetLeft(e.touchObject.length*e.touchObject.direction),top:e.props.vertical?e.getTargetLeft(e.touchObject.length*e.touchObject.direction):0})}},onMouseUp:function(t){e.state.dragging&&e.handleSwipe(t)},onMouseLeave:function(t){e.state.dragging&&e.handleSwipe(t)}}}},{key:"handleMouseOver",value:function(){this.props.autoplay&&(this.autoplayPaused=!0,this.stopAutoplay())}},{key:"handleMouseOut",value:function(){this.props.autoplay&&this.autoplayPaused&&(this.startAutoplay(),this.autoplayPaused=null)}},{key:"handleSwipe",value:function(e){"undefined"!=typeof this.touchObject.length&&this.touchObject.length>44?this.clickSafe=!0:this.clickSafe=!1;var t=this.props,n=t.slidesToShow,r=t.slidesToScroll,o=t.swipeSpeed;"auto"===r&&(n=this.state.slidesToScroll),this.touchObject.length>this.state.slideWidth/n/o?1===this.touchObject.direction?this.state.currentSlide>=g.default.Children.count(this.props.children)-n&&!this.props.wrapAround?this.animateSlide(this.props.edgeEasing):this.nextSlide():this.touchObject.direction===-1&&(this.state.currentSlide<=0&&!this.props.wrapAround?this.animateSlide(this.props.edgeEasing):this.previousSlide()):this.goToSlide(this.state.currentSlide),this.touchObject={},this.setState({dragging:!1})}},{key:"swipeDirection",value:function(e,t,n,r){var o=e-t,a=n-r,i=Math.atan2(a,o),l=Math.round(180*i/Math.PI);return l<0&&(l=360-Math.abs(l)),l<=45&&l>=0?1:l<=360&&l>=315?1:l>=135&&l<=225?-1:this.props.vertical===!0?l>=35&&l<=135?1:-1:0}},{key:"startAutoplay",value:function(){this.autoplayID=setInterval(this.autoplayIterator,this.props.autoplayInterval)}},{key:"resetAutoplay",value:function(){this.props.resetAutoplay&&this.props.autoplay&&!this.autoplayPaused&&(this.stopAutoplay(),this.startAutoplay())}},{key:"stopAutoplay",value:function(){this.autoplayID&&clearInterval(this.autoplayID)}},{key:"animateSlide",value:function(e,t,n,r){this.tweenState(this.props.vertical?"top":"left",{easing:e||this.props.easing,duration:t||this.props.speed,endValue:n||this.getTargetLeft(),delay:null,beginValue:null,onEnd:r||null,stackBehavior:P})}},{key:"getTargetLeft",value:function(e,t){var n=void 0,r=t||this.state.currentSlide,o=this.props.cellSpacing;switch(this.props.cellAlign){case"left":n=0,n-=o*r;break;case"center":n=(this.state.frameWidth-this.state.slideWidth)/2,n-=o*r;break;case"right":n=this.state.frameWidth-this.state.slideWidth,n-=o*r}var a=this.state.slideWidth*r,i=this.state.currentSlide>0&&r+this.state.slidesToScroll>=this.state.slideCount;return i&&1!==this.props.slideWidth&&!this.props.wrapAround&&"auto"===this.props.slidesToScroll&&(a=this.state.slideWidth*this.state.slideCount-this.state.frameWidth,n=0,n-=o*(this.state.slideCount-1)),n-=e||0,(a-n)*-1}},{key:"bindEvents",value:function(){C.default.canUseDOM&&(T(window,"resize",this.onResize),T(document,"readystatechange",this.onReadyStateChange))}},{key:"unbindEvents",value:function(){C.default.canUseDOM&&(E(window,"resize",this.onResize),E(document,"readystatechange",this.onReadyStateChange))}},{key:"formatChildren",value:function(e){var t=this,n=this.props.vertical?this.getTweeningValue("top"):this.getTweeningValue("left");return g.default.Children.map(e,function(e,r){return g.default.createElement("li",{className:"slider-slide",style:t.getSlideStyles(r,n),key:r},e)})}},{key:"setInitialDimensions",value:function(){var e=this,t=this.props,n=t.vertical,r=t.initialSlideHeight,o=t.initialSlideWidth,a=t.slidesToShow,i=t.cellSpacing,l=t.children,u=n?r||0:o||0,s=r?r*a:0,c=s+i*(a-1);this.setState({slideHeight:s,frameWidth:n?c:"100%",slideCount:g.default.Children.count(l),slideWidth:u},function(){e.setLeft(),e.setExternalData()})}},{key:"setDimensions",value:function(e){var t=this;e=e||this.props;var n=void 0,r=void 0,o=void 0,a=void 0,i=e.slidesToScroll,l=this.refs.frame,u=l.childNodes[0].childNodes[0];u?(u.style.height="auto",o=this.props.vertical?u.offsetHeight*e.slidesToShow:u.offsetHeight):o=100,a="number"!=typeof e.slideWidth?parseInt(e.slideWidth,10):e.vertical?o/e.slidesToShow*e.slideWidth:l.offsetWidth/e.slidesToShow*e.slideWidth,e.vertical||(a-=e.cellSpacing*((100-100/e.slidesToShow)/100)),r=o+e.cellSpacing*(e.slidesToShow-1),n=e.vertical?r:l.offsetWidth,"auto"===e.slidesToScroll&&(i=Math.floor(n/(a+e.cellSpacing))),this.setState({slideHeight:o,frameWidth:n,slideWidth:a,slidesToScroll:i,left:e.vertical?0:this.getTargetLeft(),top:e.vertical?this.getTargetLeft():0},function(){t.setLeft()})}},{key:"setLeft",value:function(){this.setState({left:this.props.vertical?0:this.getTargetLeft(),top:this.props.vertical?this.getTargetLeft():0})}},{key:"setExternalData",value:function(){this.props.data&&this.props.data()}},{key:"getListStyles",value:function(){var e=this.state.slideWidth*g.default.Children.count(this.props.children),t=this.props.cellSpacing,n=t*g.default.Children.count(this.props.children),r="translate3d("+this.getTweeningValue("left")+"px, "+this.getTweeningValue("top")+"px, 0)";return{transform:r,WebkitTransform:r,msTransform:"translate("+this.getTweeningValue("left")+"px, "+this.getTweeningValue("top")+"px)",position:"relative",display:"block",margin:this.props.vertical?t/2*-1+"px 0px":"0px "+t/2*-1+"px",padding:0,height:this.props.vertical?e+n:this.state.slideHeight,width:this.props.vertical?"auto":e+n,cursor:this.state.dragging===!0?"pointer":"inherit",boxSizing:"border-box",MozBoxSizing:"border-box"}}},{key:"getFrameStyles",value:function(){return{position:"relative",display:"block",overflow:this.props.frameOverflow,height:this.props.vertical?this.state.frameWidth||"initial":"auto",margin:this.props.framePadding,padding:0,transform:"translate3d(0, 0, 0)",WebkitTransform:"translate3d(0, 0, 0)",msTransform:"translate(0, 0)",boxSizing:"border-box",MozBoxSizing:"border-box"}}},{key:"getSlideStyles",value:function(e,t){var n=this.getSlideTargetPosition(e,t),r=this.props.cellSpacing;return{position:"absolute",left:this.props.vertical?0:n,top:this.props.vertical?n:0,display:this.props.vertical?"block":"inline-block",listStyleType:"none",verticalAlign:"top",width:this.props.vertical?"100%":this.state.slideWidth,height:"auto",boxSizing:"border-box",MozBoxSizing:"border-box",marginLeft:this.props.vertical?"auto":r/2,marginRight:this.props.vertical?"auto":r/2,marginTop:this.props.vertical?r/2:"auto",marginBottom:this.props.vertical?r/2:"auto"}}},{key:"getSlideTargetPosition",value:function(e,t){var n=this.state.frameWidth/this.state.slideWidth,r=(this.state.slideWidth+this.props.cellSpacing)*e,o=(this.state.slideWidth+this.props.cellSpacing)*n*-1;if(this.props.wrapAround){var a=Math.ceil(t/this.state.slideWidth);if(this.state.slideCount-a<=e)return(this.state.slideWidth+this.props.cellSpacing)*(this.state.slideCount-e)*-1;var i=Math.ceil((Math.abs(t)-Math.abs(o))/this.state.slideWidth);if(1!==this.state.slideWidth&&(i=Math.ceil((Math.abs(t)-this.state.slideWidth)/this.state.slideWidth)),e<=i-1)return(this.state.slideWidth+this.props.cellSpacing)*(this.state.slideCount+e)}return r}},{key:"getSliderStyles",value:function(){return{position:"relative",display:"block",width:this.props.width,height:"auto",boxSizing:"border-box",MozBoxSizing:"border-box",visibility:this.state.slideWidth?"visible":"hidden"}}},{key:"getStyleTagStyles",value:function(){return".slider-slide > img {width: 100%; display: block;}"}},{key:"getDecoratorStyles",value:function(e){switch(e){case"TopLeft":return{position:"absolute",top:0,left:0};case"TopCenter":
return{position:"absolute",top:0,left:"50%",transform:"translateX(-50%)",WebkitTransform:"translateX(-50%)",msTransform:"translateX(-50%)"};case"TopRight":return{position:"absolute",top:0,right:0};case"CenterLeft":return{position:"absolute",top:"50%",left:0,transform:"translateY(-50%)",WebkitTransform:"translateY(-50%)",msTransform:"translateY(-50%)"};case"CenterCenter":return{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%,-50%)",WebkitTransform:"translate(-50%, -50%)",msTransform:"translate(-50%, -50%)"};case"CenterRight":return{position:"absolute",top:"50%",right:0,transform:"translateY(-50%)",WebkitTransform:"translateY(-50%)",msTransform:"translateY(-50%)"};case"BottomLeft":return{position:"absolute",bottom:0,left:0};case"BottomCenter":return{position:"absolute",bottom:0,width:"100%",textAlign:"center"};case"BottomRight":return{position:"absolute",bottom:0,right:0};default:return{position:"absolute",top:0,left:0}}}}]),t}(g.default.Component);M.defaultProps={afterSlide:function(){},autoplay:!1,resetAutoplay:!0,swipeSpeed:5,autoplayInterval:3e3,beforeSlide:function(){},cellAlign:"left",cellSpacing:0,data:function(){},decorators:b.default,dragging:!0,easing:o,edgeEasing:a,framePadding:"0px",frameOverflow:"hidden",slideIndex:0,slidesToScroll:1,slidesToShow:1,slideWidth:1,speed:500,swiping:!0,vertical:!1,width:"100%",wrapAround:!1,style:{}},t.default=M,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=[{component:function(e){function t(){(0,a.default)(this,t);var e=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleClick=function(t){t.preventDefault(),e.props.previousSlide()},e}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement("button",{style:this.getButtonStyles(0===this.props.currentSlide&&!this.props.wrapAround),onClick:this.handleClick},"PREV")}},{key:"getButtonStyles",value:function(e){return{border:0,background:"rgba(0,0,0,0.4)",color:"white",padding:10,outline:0,opacity:e?.3:1,cursor:"pointer"}}}]),t}(p.default.Component),position:"CenterLeft"},{component:function(e){function t(){(0,a.default)(this,t);var e=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.handleClick=function(t){t.preventDefault(),e.props.nextSlide&&e.props.nextSlide()},e}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){return p.default.createElement("button",{style:this.getButtonStyles(this.props.currentSlide+this.props.slidesToScroll>=this.props.slideCount&&!this.props.wrapAround),onClick:this.handleClick},"NEXT")}},{key:"getButtonStyles",value:function(e){return{border:0,background:"rgba(0,0,0,0.4)",color:"white",padding:10,outline:0,opacity:e?.3:1,cursor:"pointer"}}}]),t}(p.default.Component),position:"CenterRight"},{component:function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this,t=this.getIndexes(this.props.slideCount,this.props.slidesToScroll);return p.default.createElement("ul",{style:this.getListStyles()},t.map(function(t){return p.default.createElement("li",{style:e.getListItemStyles(),key:t},p.default.createElement("button",{style:e.getButtonStyles(e.props.currentSlide===t),onClick:e.props.goToSlide&&e.props.goToSlide.bind(null,t)},"\u2022"))}))}},{key:"getIndexes",value:function(e,t){for(var n=[],r=0;r<e;r+=t)n.push(r);return n}},{key:"getListStyles",value:function(){return{position:"relative",margin:0,top:-10,padding:0}}},{key:"getListItemStyles",value:function(){return{listStyleType:"none",display:"inline-block"}}},{key:"getButtonStyles",value:function(e){return{border:0,background:"transparent",color:"black",cursor:"pointer",padding:10,outline:0,fontSize:24,opacity:e?1:.5}}}]),t}(p.default.Component),position:"BottomCenter"}];t.default=h,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(417);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}}),e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d);t.default=function(e){return t=function(t){function n(){(0,l.default)(this,n);var e=(0,f.default)(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments));return e.getValue=function(){var t=e.props,n=t.children,r=t.selectedValue;return r&&r.length?r:n?v.default.Children.map(n,function(e){var t=v.default.Children.toArray(e.children||e.props.children);return t&&t[0]&&t[0].props.value}):[]},e.onChange=function(t,n,r){var o=e.getValue().concat();o[t]=n,r&&r(o,t)},e.onValueChange=function(t,n){e.onChange(t,n,e.props.onValueChange)},e.onScrollChange=function(t,n){e.onChange(t,n,e.props.onScrollChange)},e}return(0,p.default)(n,t),(0,s.default)(n,[{key:"render",value:function(){return v.default.createElement(e,(0,a.default)({},this.props,{getValue:this.getValue,onValueChange:this.onValueChange,onScrollChange:this.props.onScrollChange&&this.onScrollChange}))}}]),n}(v.default.Component),t.defaultProps={prefixCls:"rmc-multi-picker",onValueChange:function(){}},t;var t};var h=n(1),v=r(h);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d);t.default=function(e){return t=function(t){function n(){(0,l.default)(this,n);var e=(0,f.default)(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments));return e.select=function(t,n,r){for(var o=v.default.Children.toArray(e.props.children),a=0,i=o.length;a<i;a++)if(o[a].props.value===t)return void e.selectByIndex(a,n,r);e.selectByIndex(0,n,r)},e.doScrollingComplete=function(t,n,r){var o=v.default.Children.toArray(e.props.children),a=e.coumputeChildIndex(t,n,o.length),i=o[a];i?r(i.props.value):console.warn&&console.warn("child not found",o,a)},e}return(0,p.default)(n,t),(0,s.default)(n,[{key:"selectByIndex",value:function(e,t,n){e<0||e>=v.default.Children.count(this.props.children)||!t||n(e*t)}},{key:"coumputeChildIndex",value:function(e,t,n){var r=e/t,o=Math.floor(r);return r=r-o>.5?o+1:o,Math.min(r,n-1)}},{key:"render",value:function(){return v.default.createElement(e,(0,a.default)({},this.props,{doScrollingComplete:this.doScrollingComplete,coumputeChildIndex:this.coumputeChildIndex,select:this.select}))}}]),n}(v.default.Component),t.Item=m,t;var t};var h=n(1),v=r(h),m=function(e){return null};e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return n=function(t){function n(e){(0,c.default)(this,n);var t=(0,h.default)(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t.onPickerChange=function(e){if(t.state.pickerValue!==e){t.setState({pickerValue:e});var n=t.props,r=n.picker,o=n.pickerValueChangeProp;r&&r.props[o]&&r.props[o](e)}},t.saveRef=function(e){t.picker=e},t.onTriggerClick=function(e){var n=t.props.children,r=n.props||{};r[t.props.triggerType]&&r[t.props.triggerType](e),t.fireVisibleChange(!t.state.visible)},t.onOk=function(){t.props.onOk(t.picker&&t.picker.getValue()),t.fireVisibleChange(!1)},t.getContent=function(){if(t.props.picker){var e,n=t.state.pickerValue;return null===n&&(n=t.props.value),y.default.cloneElement(t.props.picker,(e={},(0,u.default)(e,t.props.pickerValueProp,n),(0,u.default)(e,t.props.pickerValueChangeProp,t.onPickerChange),(0,u.default)(e,"ref",t.saveRef),e))}return t.props.content},t.onDismiss=function(){t.props.onDismiss(),t.fireVisibleChange(!1)},t.hide=function(){t.fireVisibleChange(!1)},t.state={pickerValue:"value"in t.props?t.props.value:null,visible:t.props.visible||!1},t}return(0,m.default)(n,t),(0,d.default)(n,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({pickerValue:e.value}),"visible"in e&&this.setVisibleState(e.visible)}},{key:"setVisibleState",value:function(e){this.setState({visible:e}),e||this.setState({pickerValue:null})}},{key:"fireVisibleChange",value:function(e){this.state.visible!==e&&("visible"in this.props||this.setVisibleState(e),this.props.onVisibleChange(e))}},{key:"getRender",value:function(){var t=this.props,n=t.children;if(!n)return e(t,this.state.visible,{getContent:this.getContent,onOk:this.onOk,hide:this.hide,onDismiss:this.onDismiss});var r=this.props,o=r.WrapComponent,a=r.disabled,i=n,l={};return a||(l[t.triggerType]=this.onTriggerClick),y.default.createElement(o,{style:t.wrapStyle},y.default.cloneElement(i,l),e(t,this.state.visible,{getContent:this.getContent,onOk:this.onOk,hide:this.hide,onDismiss:this.onDismiss}))}},{key:"render",value:function(){return this.getRender()}}]),n}(y.default.Component),n.defaultProps=(0,i.default)({onVisibleChange:function(e){},okText:"Ok",dismissText:"Dismiss",title:"",onOk:function(e){},onDismiss:function(){}},t),n;var n}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(8),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v);t.default=o;var g=n(1),y=r(g);e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e){return"string"==typeof e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(6),i=r(a),l=n(8),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v),g=n(1),y=r(g),b=n(7),_=r(b),C=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},x=function(e){function t(){return(0,c.default)(this,t),(0,h.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,m.default)(t,e),(0,d.default)(t,[{key:"renderIconNode",value:function(){var e,t=this.props,n=t.prefixCls,r=t.progressDot,a=t.stepNumber,i=t.status,l=t.title,s=t.description,c=t.icon,f=t.iconPrefix,d=void 0,p=(0,_.default)(n+"-icon",f+"icon",(e={},(0,u.default)(e,f+"icon-"+c,c&&o(c)),(0,u.default)(e,f+"icon-check",!c&&"finish"===i),(0,u.default)(e,f+"icon-cross",!c&&"error"===i),e)),h=y.default.createElement("span",{className:n+"-icon-dot"});return d=r?"function"==typeof r?y.default.createElement("span",{className:n+"-icon"},r(h,{index:a-1,status:i,title:l,description:s})):y.default.createElement("span",{className:n+"-icon"},h):c&&!o(c)?y.default.createElement("span",{className:n+"-icon"},c):c||"finish"===i||"error"===i?y.default.createElement("span",{className:p}):y.default.createElement("span",{className:n+"-icon"},a)}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.prefixCls,r=e.style,o=e.itemWidth,a=e.status,l=void 0===a?"wait":a,s=(e.iconPrefix,e.icon),c=(e.wrapperStyle,e.adjustMarginRight),f=(e.stepNumber,e.description),d=e.title,p=(e.progressDot,C(e,["className","prefixCls","style","itemWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepNumber","description","title","progressDot"])),h=(0,_.default)(n+"-item",n+"-item-"+l,t,(0,u.default)({},n+"-item-custom",s)),v=(0,i.default)({},r);return o&&(v.width=o),c&&(v.marginRight=c),y.default.createElement("div",(0,i.default)({},p,{className:h,style:v}),y.default.createElement("div",{className:n+"-item-tail"}),y.default.createElement("div",{className:n+"-item-icon"},this.renderIconNode()),y.default.createElement("div",{className:n+"-item-content"},y.default.createElement("div",{className:n+"-item-title"},d),f&&y.default.createElement("div",{className:n+"-item-description"},f)))}}]),t}(y.default.Component);t.default=x,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(8),l=r(i),u=n(2),s=r(u),c=n(5),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(7),b=r(y),_=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},C=function(e){function t(){return(0,s.default)(this,t),(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,v.default)(t,e),(0,f.default)(t,[{key:"render",value:function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=void 0===r?{}:r,i=t.className,u=t.children,s=t.direction,c=t.labelPlacement,f=t.iconPrefix,d=t.status,p=t.size,h=t.current,v=t.progressDot,y=_(t,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size","current","progressDot"]),C=g.default.Children.toArray(u).filter(function(e){return!!e}),x=v?"vertical":c,S=(0,b.default)(n,n+"-"+s,i,(e={},(0,l.default)(e,n+"-"+p,p),(0,l.default)(e,n+"-label-"+x,"horizontal"===s),(0,l.default)(e,n+"-dot",!!v),e));return g.default.createElement("div",(0,a.default)({className:S,style:o},y),m.Children.map(C,function(e,t){if(!e)return null;var r=(0,a.default)({stepNumber:""+(t+1),prefixCls:n,iconPrefix:f,wrapperStyle:o,progressDot:v},e.props);return"error"===d&&t===h-1&&(r.className=n+"-next-error"),e.props.status||(t===h?r.status=d:t<h?r.status="finish":r.status="wait"),(0,m.cloneElement)(e,r)}))}}]),t}(m.Component);t.default=C,C.defaultProps={prefixCls:"rmc-steps",iconPrefix:"rmc",direction:"horizontal",labelPlacement:"horizontal",current:0,status:"process",size:"",progressDot:!1},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Step=void 0;var o=n(424),a=r(o),i=n(423),l=r(i);a.default.Step=l.default,t.Step=l.default,t.default=a.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.StaticContainer=void 0;var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=t.StaticContainer=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"shouldComponentUpdate",value:function(e){return!!e.shouldUpdate}},{key:"render",value:function(){var e=this.props.children;return e?p.default.Children.only(e):null}}]),t}(p.default.PureComponent);h.defaultProps={shouldUpdate:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.TabPane=void 0;var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(426),g=n(78),y=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},b=t.TabPane=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.offsetX=0,e.offsetY=0,e.emptyContent=!1,e.setLayout=function(t){e.layout=t},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentWillReceiveProps",value:function(e){this.props.active!==e.active&&(e.active?(this.offsetX=0,this.offsetY=0):(this.offsetX=this.layout.scrollLeft,this.offsetY=this.layout.scrollTop)),this.emptyContent=!(this.props.children&&e.children)}},{key:"render",value:function(){var e=this.props,t=e.shouldUpdate,n=(e.active,e.fixX),r=e.fixY,o=y(e,["shouldUpdate","active","fixX","fixY"]),i=(0,a.default)({},n&&this.offsetX?(0,g.getTransformPropValue)((0,g.getPxStyle)(-this.offsetX,"px",!1)):{},r&&this.offsetY?(0,g.getTransformPropValue)((0,g.getPxStyle)(-this.offsetY,"px",!0)):{});return v.default.createElement("div",(0,a.default)({},o,{style:i,ref:this.setLayout}),v.default.createElement(m.StaticContainer,{shouldUpdate:this.emptyContent||t},o.children))}}]),t}(v.default.PureComponent);b.defaultProps={fixX:!0,fixY:!0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Tabs=t.StateType=void 0;var o=n(6),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(2),p=r(d),h=n(1),v=r(h),m=(t.StateType=function e(){(0,p.default)(this,e)},t.Tabs=function(e){function t(e){(0,p.default)(this,t);var n=(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.getPrerenderRange=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,o=t||n.state,i=o.minRenderIndex,l=o.maxRenderIndex;return t=t||{},r===-1&&(r=void 0!==t.currentTab?t.currentTab:n.state.currentTab),(0,a.default)({},t,{minRenderIndex:Math.min(i,r-e),maxRenderIndex:Math.max(l,r+e)})},n.isTabVertical=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.props.tabDirection;return"vertical"===e},n.shouldRenderTab=function(e){var t=n.props,r=t.destroyInactiveTab,o=t.prerenderingSiblingsNumber,a=void 0===o?0:o,i=n.state,l=i.minRenderIndex,u=i.maxRenderIndex,s=i.currentTab,c=void 0===s?0:s;return r?c-a<=e&&e<=c+a:l<=e&&e<=u},n.shouldUpdateTab=function(e){var t=n.state.currentTab,r=void 0===t?0:t;return r===e},n.getOffsetIndex=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:n.props.distanceToChangeTab||0,o=Math.abs(e/t),a=o>n.state.currentTab?"<":">",i=Math.floor(o);switch(a){case"<":return o-i>r?i+1:i;case">":return 1-o+i>r?i:i+1;default:return Math.round(o)}},n.getSubElements=function(){var e=n.props.children,t={};return function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"$i$-",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"$ALL$";return Array.isArray(e)?e.forEach(function(e,r){e.key&&(t[e.key]=e),t[""+n+r]=e}):e&&(t[r]=e),t}},n.state=n.getPrerenderRange(e.prerenderingSiblingsNumber,{currentTab:n.getTabIndex(e),minRenderIndex:e.tabs.length-1,maxRenderIndex:0}),n.nextCurrentTab=n.state.currentTab,n}return(0,f.default)(t,e),(0,l.default)(t,[{key:"getTabIndex",value:function(e){var t=e.page,n=e.initialPage,r=e.tabs,o=(void 0!==t?t:n)||0,a=0;return"string"==typeof o?r.forEach(function(e,t){e.key===o&&(a=t)}):a=o||0,a<0?0:a}},{key:"componentWillReceiveProps",value:function(e){this.props.page!==e.page&&void 0!==e.page&&this.goToTab(this.getTabIndex(e),!0),this.props.prerenderingSiblingsNumber!==e.prerenderingSiblingsNumber&&this.setState(this.getPrerenderRange(e.prerenderingSiblingsNumber,{minRenderIndex:this.state.minRenderIndex,maxRenderIndex:this.state.maxRenderIndex},void 0!==e.page?this.getTabIndex(e):this.state.currentTab))}},{key:"componentDidMount",value:function(){this.prevCurrentTab=this.state.currentTab}},{key:"componentDidUpdate",value:function(){this.prevCurrentTab=this.state.currentTab}},{key:"goToTab",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t&&this.nextCurrentTab===e)return!1;this.nextCurrentTab=e;var r=this.props,o=r.tabs,i=r.onChange,l=r.prerenderingSiblingsNumber;if(e>=0&&e<o.length){if(!t&&(i&&i(o[e],e),void 0!==this.props.page))return!1;this.setState((0,a.default)({currentTab:e},this.getPrerenderRange(l,void 0,e),n))}return!0}},{key:"tabClickGoToTab",value:function(e){this.goToTab(e)}},{key:"getTabBarBaseProps",value:function(){var e=this.state.currentTab,t=this.props,n=t.animated,r=t.onTabClick,o=t.tabBarActiveTextColor,a=t.tabBarBackgroundColor,i=t.tabBarInactiveTextColor,l=t.tabBarPosition,u=t.tabBarTextStyle,s=t.tabBarUnderlineStyle,c=t.tabs;return{activeTab:e,animated:!!n,goToTab:this.tabClickGoToTab.bind(this),onTabClick:r,tabBarActiveTextColor:o,tabBarBackgroundColor:a,tabBarInactiveTextColor:i,tabBarPosition:l,tabBarTextStyle:u,tabBarUnderlineStyle:s,tabs:c}}},{key:"renderTabBar",value:function e(t,n){var e=this.props.renderTabBar;return e===!1?null:e?e(t):v.default.createElement(n,t)}},{key:"getSubElement",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"$i$-",o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"$ALL$",a=e.key||""+r+t,i=n(r,o),l=i[a]||i[o];return l instanceof Function&&(l=l(e,t)),l||null}}]),t}(v.default.PureComponent));m.defaultProps={tabBarPosition:"top",initialPage:0,swipeable:!0,animated:!0,prerenderingSiblingsNumber:1,tabs:[],destroyInactiveTab:!1,usePaged:!0,tabDirection:"horizontal",distanceToChangeTab:.3}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Tabs=t.StateType=void 0;var o=n(6),a=r(o),i=n(5),l=r(i),u=n(95),s=r(u),c=n(2),f=r(c),d=n(4),p=r(d),h=n(3),v=r(h),m=n(1),g=r(m),y=n(71),b=r(y),_=n(427),C=n(123),x=n(78),S=n(428),O=t.StateType=function(e){function t(){(0,f.default)(this,t);var e=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.transform="",e.isMoving=!1,e}return(0,v.default)(t,e),t}(S.StateType),k=t.Tabs=function(e){function t(e){(0,f.default)(this,t);var n=(0,p.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onPan=function(){var e=0,t=0,r=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:n.isTabVertical(),r=+(""+e).replace("%","");return(""+e).indexOf("%")>=0&&(r/=100,r*=t?n.layout.clientHeight:n.layout.clientWidth),r};return{onPanStart:function(){n.props.swipeable&&n.setState({isMoving:!0})},onPanMove:function(e){var o=n.props,a=o.swipeable,i=o.animated;if(e.moveStatus&&n.layout&&a&&i){var l=n.isTabVertical(),u=r()+(l?e.moveStatus.y:e.moveStatus.x),s=l?-n.layout.scrollHeight+n.layout.clientHeight:-n.layout.scrollWidth+n.layout.clientWidth;u=Math.min(u,0),u=Math.max(u,s),(0,x.setPxStyle)(n.layout,u,"px",l),t=u}},onPanEnd:function(){if(n.props.swipeable){e=t;var r=n.getOffsetIndex(t,n.layout.clientWidth);n.setState({isMoving:!1}),r===n.state.currentTab?n.props.usePaged&&(0,x.setTransform)(n.layout.style,n.getTransformByIndex(r,n.isTabVertical())):n.goToTab(r)}},setCurrentOffset:function(t){return e=t}}}(),n.onSwipe=function(e){var t=n.props,r=t.tabBarPosition,o=t.swipeable,a=t.usePaged;if(o&&a&&!n.isTabVertical())switch(r){case"top":case"bottom":switch(e.direction){case 2:case 8:n.goToTab(n.prevCurrentTab+1);break;case 4:case 16:n.goToTab(n.prevCurrentTab-1)}}},n.setContentLayout=function(e){n.layout=e},n.state=(0,a.default)({},n.state,new O,{transform:n.getTransformByIndex(n.getTabIndex(e),n.isTabVertical(e.tabDirection))}),n}return(0,v.default)(t,e),(0,l.default)(t,[{key:"goToTab",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.props.usePaged,o=this.props.tabDirection,a={};return r&&(a={transform:this.getTransformByIndex(e,this.isTabVertical(o))}),(0,s.default)(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"goToTab",this).call(this,e,n,a)}},{key:"tabClickGoToTab",value:function(e){this.goToTab(e,!1,!0)}},{key:"getTransformByIndex",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this.onPan.setCurrentOffset(100*-e+"%");var n=t?"0px, "+100*-e+"%":100*-e+"%, 0px";return"translate3d("+n+", 0px)"}},{key:"renderContent",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.getSubElements(),n=this.props,r=n.prefixCls,o=n.tabs,a=n.animated,i=this.state,l=i.currentTab,u=i.isMoving,s=i.transform,c=this.isTabVertical(),f=r+"-content-wrap";a&&!u&&(f+=" "+f+"-animated");var d=(0,x.getTransformPropValue)(s);return g.default.createElement("div",{className:f,style:d,ref:this.setContentLayout},o.map(function(n,o){var a=r+"-pane-wrap";a+=e.state.currentTab===o?" "+a+"-active":" "+a+"-inactive";var i=n.key||"tab_"+o;return g.default.createElement(_.TabPane,{key:i,className:a,shouldUpdate:e.shouldUpdateTab(o),active:l===o,fixX:c,fixY:!c},e.shouldRenderTab(o)&&e.getSubElement(n,o,t))}))}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.tabBarPosition,r=e.tabDirection,o=e.useOnPan,i=this.isTabVertical(r),l=(0,a.default)({},this.getTabBarBaseProps()),u=!i&&o?this.onPan:{},s=[g.default.createElement("div",{key:"tabBar",className:t+"-tab-bar-wrap"},this.renderTabBar(l,C.DefaultTabBar)),g.default.createElement(b.default,(0,a.default)({key:"$content",direction:i?"vertical":"horizontal",onSwipe:this.onSwipe},u),this.renderContent())];return g.default.createElement("div",{className:t+" "+t+"-"+r+" "+t+"-"+n},"top"===n||"left"===n?s:s.reverse())}}]),t}(S.Tabs);k.DefaultTabBar=C.DefaultTabBar,k.defaultProps=(0,a.default)({},S.Tabs.defaultProps,{prefixCls:"rmc-tabs",useOnPan:!0})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(429);Object.defineProperty(t,"Tabs",{enumerable:!0,get:function(){return r.Tabs}});var o=n(123);Object.defineProperty(t,"DefaultTabBar",{enumerable:!0,get:function(){return o.DefaultTabBar}})},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(437),g=r(m),y=n(433),b=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&(n[r[o]]=e[r[o]]);return n},_=function(e){function t(){(0,l.default)(this,t);var e=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.getPopupElement=function(){var t=e.props,n=t.arrowContent,r=t.overlay,o=t.prefixCls;return[v.default.createElement("div",{className:o+"-arrow",key:"arrow"},n),v.default.createElement("div",{className:o+"-inner",key:"content"},"function"==typeof r?r():r)]},e.saveTrigger=function(t){e.trigger=t},e}return(0,p.default)(t,e),(0,s.default)(t,[{key:"getPopupDomNode",value:function(){return this.trigger.triggerRef.getPopupDomNode()}},{key:"render",value:function(){var e=this.props,t=e.overlayClassName,n=(e.trigger,e.overlayStyle),r=e.prefixCls,o=e.children,i=e.onVisibleChange,l=e.afterVisibleChange,u=e.transitionName,s=e.animation,c=e.placement,f=e.align,d=e.destroyTooltipOnHide,p=e.defaultVisible,h=e.getTooltipContainer,m=b(e,["overlayClassName","trigger","overlayStyle","prefixCls","children","onVisibleChange","afterVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),_=(0,a.default)({},m);return"visible"in this.props&&(_.popupVisible=this.props.visible),v.default.createElement(g.default,(0,a.default)({popupClassName:t,ref:this.saveTrigger,prefixCls:r,popup:this.getPopupElement,builtinPlacements:y.placements,popupPlacement:c,popupAlign:f,getPopupContainer:h,onPopupVisibleChange:i,afterPopupVisibleChange:l,popupTransitionName:u,popupAnimation:s,defaultPopupVisible:p,destroyPopupOnHide:d,popupStyle:n},_),o)}}]),t}(h.Component);_.defaultProps={prefixCls:"rmc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null},t.default=_,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(431),a=r(o);t.default=a.default,e.exports=t.default},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o=t.placements={left:{points:["cr","cl"],overflow:n,offset:[-4,0],targetOffset:r},right:{points:["cl","cr"],overflow:n,offset:[4,0],targetOffset:r},top:{points:["bc","tc"],overflow:n,offset:[0,-4],targetOffset:r},bottom:{points:["tc","bc"],overflow:n,offset:[0,4],targetOffset:r},topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},leftTop:{points:["tr","tl"],overflow:n,offset:[-4,0],targetOffset:r},topRight:{points:["br","tr"],overflow:n,offset:[0,-4],targetOffset:r},rightTop:{points:["tl","tr"],overflow:n,offset:[4,0],targetOffset:r},bottomRight:{points:["tr","br"],overflow:n,offset:[0,4],targetOffset:r},rightBottom:{points:["bl","br"],overflow:n,offset:[4,0],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r},leftBottom:{points:["br","bl"],overflow:n,offset:[-4,0],targetOffset:r}};t.default=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(6),a=r(o),i=n(2),l=r(i),u=n(5),s=r(u),c=n(4),f=r(c),d=n(3),p=r(d),h=n(1),v=r(h),m=n(11),g=r(m),y=n(390),b=r(y),_=n(39),C=r(_),x=n(435),S=r(x),O=n(124),k=r(O),w=n(125),P=function(e){function t(e){(0,l.default)(this,t);var n=(0,f.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return n.onAlign=function(e,t){var r=n.props,o=r.getClassNameFromAlign(t);n.currentAlignClassName!==o&&(n.currentAlignClassName=o,e.className=n.getClassName(o)),r.onAlign(e,t)},n.getTarget=function(){return n.props.getRootDomNode()},n.savePopupRef=w.saveRef.bind(n,"popupInstance"),n.saveAlignRef=w.saveRef.bind(n,"alignInstance"),n}return(0,p.default)(t,e),(0,s.default)(t,[{key:"componentDidMount",value:function(){this.rootNode=this.getPopupDomNode()}},{key:"getPopupDomNode",value:function(){return g.default.findDOMNode(this.popupInstance)}},{key:"getMaskTransitionName",value:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t}},{key:"getTransitionName",value:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t}},{key:"getClassName",value:function(e){return this.props.prefixCls+" "+this.props.className+" "+e}},{key:"getPopupElement",value:function(){var e=this.savePopupRef,t=this.props,n=t.align,r=t.style,o=t.visible,i=t.prefixCls,l=t.destroyPopupOnHide,u=this.getClassName(this.currentAlignClassName||t.getClassNameFromAlign(n)),s=i+"-hidden";o||(this.currentAlignClassName=null);var c=(0,a.default)({},r,this.getZIndexStyle()),f={className:u,prefixCls:i,ref:e,style:c};if(l)return v.default.createElement(C.default,{component:"",exclusive:!0,transitionAppear:!0,onAnimateLeave:t.onAnimateLeave,transitionName:this.getTransitionName()},o?v.default.createElement(b.default,{target:this.getTarget,key:"popup",ref:this.saveAlignRef,monitorWindowResize:!0,align:n,onAlign:this.onAlign},v.default.createElement(S.default,(0,a.default)({visible:!0},f),t.children)):null);var d={xVisible:o};return v.default.createElement(C.default,{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),onAnimateLeave:t.onAnimateLeave,showProp:"xVisible"},v.default.createElement(b.default,(0,a.default)({target:this.getTarget,key:"popup",ref:this.saveAlignRef,monitorWindowResize:!0},d,{childrenProps:{visible:"xVisible"},disabled:!o,align:n,onAlign:this.onAlign}),v.default.createElement(S.default,(0,a.default)({hiddenClassName:s},f),t.children)))}},{key:"getZIndexStyle",value:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e}},{key:"getMaskElement",value:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=v.default.createElement(k.default,{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=v.default.createElement(C.default,{key:"mask",showProp:"visible",transitionAppear:!0,component:"",
transitionName:n},t))}return t}},{key:"render",value:function(){return v.default.createElement("div",null,this.getMaskElement(),this.getPopupElement())}}]),t}(h.Component);t.default=P,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(2),a=r(o),i=n(5),l=r(i),u=n(4),s=r(u),c=n(3),f=r(c),d=n(1),p=r(d),h=n(124),v=r(h),m=function(e){function t(){return(0,a.default)(this,t),(0,s.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return(0,f.default)(t,e),(0,l.default)(t,[{key:"render",value:function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),p.default.createElement("div",{className:t,style:e.style},p.default.createElement(v.default,{className:e.prefixCls+"-content",visible:e.visible},e.children))}}]),t}(d.Component);t.default=m,e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(){return""}function i(){return window.document}Object.defineProperty(t,"__esModule",{value:!0});var l=n(6),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v),g=n(1),y=r(g),b=n(11),_=r(b),C=n(386),x=r(C),S=n(73),O=r(S),k=n(434),w=r(k),P=n(125),T=function(e){function t(){(0,c.default)(this,t);var e=(0,h.default)(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments));return e.onDocumentClick=function(t){if(!e.props.mask||e.props.maskClosable){var n=t.target,r=(0,b.findDOMNode)(e),o=e.getPopupDomNode();(0,x.default)(r,n)||(0,x.default)(o,n)||e.close()}},e.getPopupAlign=function(){var t=e.props,n=t.popupPlacement,r=t.popupAlign,o=t.builtinPlacements;return n&&o?(0,P.getAlignFromPlacement)(o,n,r):r},e.getRootDomNode=function(){return(0,b.findDOMNode)(e)},e.getPopupClassNameFromAlign=function(t){var n=[],r=e.props,o=r.popupPlacement,a=r.builtinPlacements,i=r.prefixCls;return o&&a&&n.push((0,P.getPopupClassNameFromAlign)(a,i,t)),r.getPopupClassNameFromAlign&&n.push(r.getPopupClassNameFromAlign(t)),n.join(" ")},e.close=function(){e.props.onClose&&e.props.onClose()},e.onAnimateLeave=function(){if(e.props.destroyPopupOnHide){var t=e._container;t&&(_.default.unmountComponentAtNode(t),t.parentNode.removeChild(t))}},e.removeContainer=function(){var t=document.querySelector("#"+e.props.prefixCls+"-container");t&&(_.default.unmountComponentAtNode(t),t.parentNode.removeChild(t))},e}return(0,m.default)(t,e),(0,d.default)(t,[{key:"componentDidMount",value:function(){this.props.visible&&this.componentDidUpdate()}},{key:"shouldComponentUpdate",value:function(e){var t=e.visible;return!(!this.props.visible&&!t)}},{key:"componentWillUnmount",value:function(){this.renderDialog(!1)}},{key:"componentDidUpdate",value:function(){if(this.renderDialog(this.props.visible),this.props.visible){var e=void 0;return void(this.touchOutsideHandler||(e=e||this.props.getDocument(),this.touchOutsideHandler=(0,O.default)(e,"touchstart",this.onDocumentClick)))}this.clearOutsideHandler()}},{key:"clearOutsideHandler",value:function(){this.touchOutsideHandler&&(this.touchOutsideHandler.remove(),this.touchOutsideHandler=null)}},{key:"getPopupDomNode",value:function(){return this._component&&this._component.getPopupDomNode?this._component.getPopupDomNode():null}},{key:"saveRef",value:function(e,t){this._component=e,this.props.afterPopupVisibleChange(t)}},{key:"getComponent",value:function(e){var t=this,n=(0,u.default)({},this.props);return["visible","onAnimateLeave"].forEach(function(e){n.hasOwnProperty(e)&&delete n[e]}),y.default.createElement(w.default,{ref:function(n){return t.saveRef(n,e)},prefixCls:n.prefixCls,destroyPopupOnHide:n.destroyPopupOnHide,visible:e,className:n.popupClassName,align:this.getPopupAlign(),onAlign:n.onPopupAlign,animation:n.popupAnimation,getClassNameFromAlign:this.getPopupClassNameFromAlign,getRootDomNode:this.getRootDomNode,style:n.popupStyle,mask:n.mask,zIndex:n.zIndex,transitionName:n.popupTransitionName,maskAnimation:n.maskAnimation,maskTransitionName:n.maskTransitionName,onAnimateLeave:this.onAnimateLeave},"function"==typeof n.popup?n.popup():n.popup)}},{key:"renderDialog",value:function(e){var t=this.props;if(!this._container){var n=document.createElement("div");n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%";var r=t.getPopupContainer?t.getPopupContainer((0,b.findDOMNode)(this)):t.getDocument().body;r.appendChild(n),this._container=n}_.default.render(this.getComponent(e),this._container)}},{key:"render",value:function(){var e=this.props,t=e.children,n=y.default.Children.only(t),r={onClick:this.props.onTargetClick};return y.default.cloneElement(n,r)}}]),t}(y.default.Component);t.default=T,T.defaultProps={prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:a,getDocument:i,onPopupVisibleChange:o,afterPopupVisibleChange:o,onPopupAlign:o,popupClassName:"",popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0},e.exports=t.default},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(){}function a(){return""}function i(){return window.document}Object.defineProperty(t,"__esModule",{value:!0});var l=n(6),u=r(l),s=n(2),c=r(s),f=n(5),d=r(f),p=n(4),h=r(p),v=n(3),m=r(v),g=n(1),y=r(g),b=n(436),_=r(b),C=function(e){function t(e){(0,c.default)(this,t);var n=(0,h.default)(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));n.onTargetClick=function(){n.setPopupVisible(!n.state.popupVisible)},n.onClose=function(){n.setPopupVisible(!1)};var r=void 0;return r="popupVisible"in e?!!e.popupVisible:!!e.defaultPopupVisible,n.state={popupVisible:r},n}return(0,m.default)(t,e),(0,d.default)(t,[{key:"setPopupVisible",value:function(e){this.setState({popupVisible:e})}},{key:"render",value:function(){var e=this;return y.default.createElement(_.default,(0,u.default)({ref:function(t){return e.triggerRef=t}},this.props,{visible:this.state.popupVisible,onTargetClick:this.onTargetClick,onClose:this.onClose}))}}]),t}(y.default.Component);C.displayName="TriggerWrap",C.defaultProps={prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:a,getDocument:i,onPopupVisibleChange:o,afterPopupVisibleChange:o,onPopupAlign:o,popupClassName:"",popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,maskClosable:!0},t.default=C,e.exports=t.default},function(e,t,n){"use strict";var r=n(358);e.exports=function(e,t,n,o){var a=n?n.call(o,e,t):void 0;if(void 0!==a)return!!a;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var i=r(e),l=r(t),u=i.length;if(u!==l.length)return!1;o=o||null;for(var s=Object.prototype.hasOwnProperty.bind(t),c=0;c<u;c++){var f=i[c];if(!s(f))return!1;var d=e[f],p=t[f],h=n?n.call(o,d,p,f):void 0;if(h===!1||void 0===h&&d!==p)return!1}return!0}},function(e,t,n){(function(r){"use strict";function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(110),i=o(a),l=60,u=1e3,s={},c=1,f="undefined"!=typeof window?window:void 0;f||(f="undefined"!=typeof r?r:{});var d={stop:function(e){var t=null!=s[e];return t&&(s[e]=null),t},isRunning:function(e){return null!=s[e]},start:function e(t,n,r,o,a){var e=+new Date,f=e,d=0,p=0,h=c++;if(h%20===0){var v={};for(var m in s)v[m]=!0;s=v}var g=function c(v){var m=v!==!0,g=+new Date;if(!s[h]||n&&!n(h))return s[h]=null,void(r&&r(l-p/((g-e)/u),h,!1));if(m)for(var y=Math.round((g-f)/(u/l))-1,b=0;b<Math.min(y,4);b++)c(!0),p++;o&&(d=(g-e)/o,d>1&&(d=1));var _=a?a(d):d;t(_,g,m)!==!1&&1!==d||!m?m&&(f=g,(0,i.default)(c)):(s[h]=null,r&&r(l-p/((g-e)/u),h,1===d||null==o))};return s[h]=!0,(0,i.default)(g),h}};t.default=d,e.exports=t.default}).call(t,function(){return this}())},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o,a=n(439),i=r(a),l=function(){};o=function(e,t){this.__callback=e,this.options={scrollingX:!0,scrollingY:!0,animating:!0,animationDuration:250,bouncing:!0,locking:!0,paging:!1,snapping:!1,zooming:!1,minZoom:.5,maxZoom:3,speedMultiplier:1,scrollingComplete:l,penetrationDeceleration:.03,penetrationAcceleration:.08};for(var n in t)this.options[n]=t[n]};var u=function(e){return Math.pow(e-1,3)+1},s=function(e){return(e/=.5)<1?.5*Math.pow(e,3):.5*(Math.pow(e-2,3)+2)},c={__isSingleTouch:!1,__isTracking:!1,__didDecelerationComplete:!1,__isGesturing:!1,__isDragging:!1,__isDecelerating:!1,__isAnimating:!1,__clientLeft:0,__clientTop:0,__clientWidth:0,__clientHeight:0,__contentWidth:0,__contentHeight:0,__snapWidth:100,__snapHeight:100,__refreshHeight:null,__refreshActive:!1,__refreshActivate:null,__refreshDeactivate:null,__refreshStart:null,__zoomLevel:1,__scrollLeft:0,__scrollTop:0,__maxScrollLeft:0,__maxScrollTop:0,__scheduledLeft:0,__scheduledTop:0,__scheduledZoom:0,__lastTouchLeft:null,__lastTouchTop:null,__lastTouchMove:null,__positions:null,__minDecelerationScrollLeft:null,__minDecelerationScrollTop:null,__maxDecelerationScrollLeft:null,__maxDecelerationScrollTop:null,__decelerationVelocityX:null,__decelerationVelocityY:null,setDimensions:function(e,t,n,r){var o=this;e===+e&&(o.__clientWidth=e),t===+t&&(o.__clientHeight=t),n===+n&&(o.__contentWidth=n),r===+r&&(o.__contentHeight=r),o.__computeScrollMax(),o.scrollTo(o.__scrollLeft,o.__scrollTop,!0)},setPosition:function(e,t){var n=this;n.__clientLeft=e||0,n.__clientTop=t||0},setSnapSize:function(e,t){var n=this;n.__snapWidth=e,n.__snapHeight=t},activatePullToRefresh:function(e,t,n,r){var o=this;o.__refreshHeight=e,o.__refreshActivate=t,o.__refreshDeactivate=n,o.__refreshStart=r},triggerPullToRefresh:function(){this.__publish(this.__scrollLeft,-this.__refreshHeight,this.__zoomLevel,!0),this.__refreshStart&&this.__refreshStart()},finishPullToRefresh:function(){var e=this;e.__refreshActive=!1,e.__refreshDeactivate&&e.__refreshDeactivate(),e.scrollTo(e.__scrollLeft,e.__scrollTop,!0)},getValues:function(){var e=this;return{left:e.__scrollLeft,top:e.__scrollTop,zoom:e.__zoomLevel}},getScrollMax:function(){var e=this;return{left:e.__maxScrollLeft,top:e.__maxScrollTop}},zoomTo:function(e,t,n,r,o){var a=this;if(!a.options.zooming)throw new Error("Zooming is not enabled!");o&&(a.__zoomComplete=o),a.__isDecelerating&&(i.default.stop(a.__isDecelerating),a.__isDecelerating=!1);var l=a.__zoomLevel;null==n&&(n=a.__clientWidth/2),null==r&&(r=a.__clientHeight/2),e=Math.max(Math.min(e,a.options.maxZoom),a.options.minZoom),a.__computeScrollMax(e);var u=(n+a.__scrollLeft)*e/l-n,s=(r+a.__scrollTop)*e/l-r;u>a.__maxScrollLeft?u=a.__maxScrollLeft:u<0&&(u=0),s>a.__maxScrollTop?s=a.__maxScrollTop:s<0&&(s=0),a.__publish(u,s,e,t)},zoomBy:function(e,t,n,r,o){var a=this;a.zoomTo(a.__zoomLevel*e,t,n,r,o)},scrollTo:function(e,t,n,r,o){var a=this;if(a.__isDecelerating&&(i.default.stop(a.__isDecelerating),a.__isDecelerating=!1),null!=r&&r!==a.__zoomLevel){if(!a.options.zooming)throw new Error("Zooming is not enabled!");e*=r,t*=r,a.__computeScrollMax(r)}else r=a.__zoomLevel;a.options.scrollingX?a.options.paging?e=Math.round(e/a.__clientWidth)*a.__clientWidth:a.options.snapping&&(e=Math.round(e/a.__snapWidth)*a.__snapWidth):e=a.__scrollLeft,a.options.scrollingY?a.options.paging?t=Math.round(t/a.__clientHeight)*a.__clientHeight:a.options.snapping&&(t=Math.round(t/a.__snapHeight)*a.__snapHeight):t=a.__scrollTop,e=Math.max(Math.min(a.__maxScrollLeft,e),0),t=Math.max(Math.min(a.__maxScrollTop,t),0),e===a.__scrollLeft&&t===a.__scrollTop&&(n=!1,o&&o()),a.__isTracking||a.__publish(e,t,r,n)},scrollBy:function(e,t,n){var r=this,o=r.__isAnimating?r.__scheduledLeft:r.__scrollLeft,a=r.__isAnimating?r.__scheduledTop:r.__scrollTop;r.scrollTo(o+(e||0),a+(t||0),n)},doMouseZoom:function(e,t,n,r){var o=this,a=e>0?.97:1.03;return o.zoomTo(o.__zoomLevel*a,!1,n-o.__clientLeft,r-o.__clientTop)},doTouchStart:function(e,t){if(null==e.length)throw new Error("Invalid touch list: "+e);if(t instanceof Date&&(t=t.valueOf()),"number"!=typeof t)throw new Error("Invalid timestamp value: "+t);var n=this;n.__interruptedAnimation=!0,n.__isDecelerating&&(i.default.stop(n.__isDecelerating),n.__isDecelerating=!1,n.__interruptedAnimation=!0),n.__isAnimating&&(i.default.stop(n.__isAnimating),n.__isAnimating=!1,n.__interruptedAnimation=!0);var r,o,a=1===e.length;a?(r=e[0].pageX,o=e[0].pageY):(r=Math.abs(e[0].pageX+e[1].pageX)/2,o=Math.abs(e[0].pageY+e[1].pageY)/2),n.__initialTouchLeft=r,n.__initialTouchTop=o,n.__zoomLevelStart=n.__zoomLevel,n.__lastTouchLeft=r,n.__lastTouchTop=o,n.__lastTouchMove=t,n.__lastScale=1,n.__enableScrollX=!a&&n.options.scrollingX,n.__enableScrollY=!a&&n.options.scrollingY,n.__isTracking=!0,n.__didDecelerationComplete=!1,n.__isDragging=!a,n.__isSingleTouch=a,n.__positions=[]},doTouchMove:function(e,t,n){if(null==e.length)throw new Error("Invalid touch list: "+e);if(t instanceof Date&&(t=t.valueOf()),"number"!=typeof t)throw new Error("Invalid timestamp value: "+t);var r=this;if(r.__isTracking){var o,a;2===e.length?(o=Math.abs(e[0].pageX+e[1].pageX)/2,a=Math.abs(e[0].pageY+e[1].pageY)/2):(o=e[0].pageX,a=e[0].pageY);var i=r.__positions;if(r.__isDragging){var l=o-r.__lastTouchLeft,u=a-r.__lastTouchTop,s=r.__scrollLeft,c=r.__scrollTop,f=r.__zoomLevel;if(null!=n&&r.options.zooming){var d=f;if(f=f/r.__lastScale*n,f=Math.max(Math.min(f,r.options.maxZoom),r.options.minZoom),d!==f){var p=o-r.__clientLeft,h=a-r.__clientTop;s=(p+s)*f/d-p,c=(h+c)*f/d-h,r.__computeScrollMax(f)}}if(r.__enableScrollX){s-=l*this.options.speedMultiplier;var v=r.__maxScrollLeft;(s>v||s<0)&&(r.options.bouncing?s+=l/2*this.options.speedMultiplier:s=s>v?v:0)}if(r.__enableScrollY){c-=u*this.options.speedMultiplier;var m=r.__maxScrollTop;(c>m||c<0)&&(r.options.bouncing?(c+=u/2*this.options.speedMultiplier,r.__enableScrollX||null==r.__refreshHeight||(!r.__refreshActive&&c<=-r.__refreshHeight?(r.__refreshActive=!0,r.__refreshActivate&&r.__refreshActivate()):r.__refreshActive&&c>-r.__refreshHeight&&(r.__refreshActive=!1,r.__refreshDeactivate&&r.__refreshDeactivate()))):c=c>m?m:0)}i.length>60&&i.splice(0,30),i.push(s,c,t),r.__publish(s,c,f)}else{var g=3,y=5,b=Math.abs(o-r.__initialTouchLeft),_=Math.abs(a-r.__initialTouchTop);r.__enableScrollX=r.options.scrollingX&&b>=g,r.__enableScrollY=r.options.scrollingY&&_>=g;var C=void 0;r.options.locking&&r.__enableScrollY&&(C=C||Math.atan2(_,b),C<Math.PI/4&&(r.__enableScrollY=!1)),r.options.locking&&r.__enableScrollX&&(C=C||Math.atan2(_,b),C>Math.PI/4&&(r.__enableScrollX=!1)),i.push(r.__scrollLeft,r.__scrollTop,t),r.__isDragging=(r.__enableScrollX||r.__enableScrollY)&&(b>=y||_>=y),r.__isDragging&&(r.__interruptedAnimation=!1)}r.__lastTouchLeft=o,r.__lastTouchTop=a,r.__lastTouchMove=t,r.__lastScale=n}},doTouchEnd:function(e){if(e instanceof Date&&(e=e.valueOf()),"number"!=typeof e)throw new Error("Invalid timestamp value: "+e);var t=this;if(t.__isTracking){if(t.__isTracking=!1,t.__isDragging)if(t.__isDragging=!1,t.__isSingleTouch&&t.options.animating&&e-t.__lastTouchMove<=100){for(var n=t.__positions,r=n.length-1,o=r,a=r;a>0&&n[a]>t.__lastTouchMove-100;a-=3)o=a;if(o!==r){var i=n[r]-n[o],l=t.__scrollLeft-n[o-2],u=t.__scrollTop-n[o-1];t.__decelerationVelocityX=l/i*(1e3/60),t.__decelerationVelocityY=u/i*(1e3/60);var s=t.options.paging||t.options.snapping?4:1;Math.abs(t.__decelerationVelocityX)>s||Math.abs(t.__decelerationVelocityY)>s?t.__refreshActive||t.__startDeceleration(e):t.options.scrollingComplete()}else t.options.scrollingComplete()}else e-t.__lastTouchMove>100&&t.options.scrollingComplete();t.__isDecelerating||(t.__refreshActive&&t.__refreshStart?(t.__publish(t.__scrollLeft,-t.__refreshHeight,t.__zoomLevel,!0),t.__refreshStart&&t.__refreshStart()):((t.__interruptedAnimation||t.__isDragging)&&t.options.scrollingComplete(),t.scrollTo(t.__scrollLeft,t.__scrollTop,!0,t.__zoomLevel),t.__refreshActive&&(t.__refreshActive=!1,t.__refreshDeactivate&&t.__refreshDeactivate()))),t.__positions.length=0}},__publish:function(e,t,n,r){var o=this,a=o.__isAnimating;if(a&&(i.default.stop(a),o.__isAnimating=!1),r&&o.options.animating){o.__scheduledLeft=e,o.__scheduledTop=t,o.__scheduledZoom=n;var l=o.__scrollLeft,c=o.__scrollTop,f=o.__zoomLevel,d=e-l,p=t-c,h=n-f,v=function(e,t,n){n&&(o.__scrollLeft=l+d*e,o.__scrollTop=c+p*e,o.__zoomLevel=f+h*e,o.__callback&&o.__callback(o.__scrollLeft,o.__scrollTop,o.__zoomLevel))},m=function(e){return o.__isAnimating===e},g=function(e,t,n){t===o.__isAnimating&&(o.__isAnimating=!1),(o.__didDecelerationComplete||n)&&o.options.scrollingComplete(),o.options.zooming&&(o.__computeScrollMax(),o.__zoomComplete&&(o.__zoomComplete(),o.__zoomComplete=null))};o.__isAnimating=i.default.start(v,m,g,o.options.animationDuration,a?u:s)}else o.__scheduledLeft=o.__scrollLeft=e,o.__scheduledTop=o.__scrollTop=t,o.__scheduledZoom=o.__zoomLevel=n,o.__callback&&o.__callback(e,t,n),o.options.zooming&&(o.__computeScrollMax(),o.__zoomComplete&&(o.__zoomComplete(),o.__zoomComplete=null))},__computeScrollMax:function(e){var t=this;null==e&&(e=t.__zoomLevel),t.__maxScrollLeft=Math.max(t.__contentWidth*e-t.__clientWidth,0),t.__maxScrollTop=Math.max(t.__contentHeight*e-t.__clientHeight,0)},__startDeceleration:function(e){var t=this;if(t.options.paging){var n=Math.max(Math.min(t.__scrollLeft,t.__maxScrollLeft),0),r=Math.max(Math.min(t.__scrollTop,t.__maxScrollTop),0),o=t.__clientWidth,a=t.__clientHeight;t.__minDecelerationScrollLeft=Math.floor(n/o)*o,t.__minDecelerationScrollTop=Math.floor(r/a)*a,t.__maxDecelerationScrollLeft=Math.ceil(n/o)*o,t.__maxDecelerationScrollTop=Math.ceil(r/a)*a}else t.__minDecelerationScrollLeft=0,t.__minDecelerationScrollTop=0,t.__maxDecelerationScrollLeft=t.__maxScrollLeft,t.__maxDecelerationScrollTop=t.__maxScrollTop;var l=function(e,n,r){t.__stepThroughDeceleration(r)},u=t.options.minVelocityToKeepDecelerating;u||(u=t.options.snapping?4:.001);var s=function(){var e=Math.abs(t.__decelerationVelocityX)>=u||Math.abs(t.__decelerationVelocityY)>=u;return e||(t.__didDecelerationComplete=!0),e},c=function(e,n,r){t.__isDecelerating=!1,t.scrollTo(t.__scrollLeft,t.__scrollTop,t.options.snapping,null,t.__didDecelerationComplete&&t.options.scrollingComplete)};t.__isDecelerating=i.default.start(l,s,c)},__stepThroughDeceleration:function(e){var t=this,n=t.__scrollLeft+t.__decelerationVelocityX,r=t.__scrollTop+t.__decelerationVelocityY;if(!t.options.bouncing){var o=Math.max(Math.min(t.__maxDecelerationScrollLeft,n),t.__minDecelerationScrollLeft);o!==n&&(n=o,t.__decelerationVelocityX=0);var a=Math.max(Math.min(t.__maxDecelerationScrollTop,r),t.__minDecelerationScrollTop);a!==r&&(r=a,t.__decelerationVelocityY=0)}if(e?t.__publish(n,r,t.__zoomLevel):(t.__scrollLeft=n,t.__scrollTop=r),!t.options.paging){var i=.95;t.__decelerationVelocityX*=i,t.__decelerationVelocityY*=i}if(t.options.bouncing){var l=0,u=0,s=t.options.penetrationDeceleration,c=t.options.penetrationAcceleration;n<t.__minDecelerationScrollLeft?l=t.__minDecelerationScrollLeft-n:n>t.__maxDecelerationScrollLeft&&(l=t.__maxDecelerationScrollLeft-n),r<t.__minDecelerationScrollTop?u=t.__minDecelerationScrollTop-r:r>t.__maxDecelerationScrollTop&&(u=t.__maxDecelerationScrollTop-r),0!==l&&(l*t.__decelerationVelocityX<=0?t.__decelerationVelocityX+=l*s:t.__decelerationVelocityX=l*c),0!==u&&(u*t.__decelerationVelocityY<=0?t.__decelerationVelocityY+=u*s:t.__decelerationVelocityY=u*c)}}};for(var f in c)o.prototype[f]=c[f];t.default=o,e.exports=t.default},function(e,t,n,r){"use strict";n(9),n(r)},function(e,t,n,r){"use strict";n(9),n(15),n(r)},function(e,t,n,r){"use strict";n(9),n(21),n(r)},function(e,t,n,r){"use strict";n(r)}]))});
//# sourceMappingURL=antd-mobile.min.js.map |
src/client/redux/modules/user.js | eliasmeire/hz-pictionary | import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/concat';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/concatMap';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/mergeMapTo';
import Horizon from '@horizon/client';
import { goBack } from 'connected-react-router';
import {
actionTypes,
fetchUserAuthFulfilled,
fetchUserAuthRejected,
setRoomFormState,
showToast,
clearProfileForm,
} from '../actions';
import { hz, hzUsers } from '../../lib/horizon';
import { FORM_STATES, TOAST_STATES, DEFAULT_DRAWING_SETTINGS } from '../../constants';
const initialState = {
authPending: true,
isAuthorized: false,
id: '',
name: '',
drawingSettings: DEFAULT_DRAWING_SETTINGS,
error: null,
};
export const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.logout:
return Object.assign({}, initialState, { authPending: false });
case actionTypes.setDrawingSettings:
return Object.assign({}, state, { drawingSettings: action.settings });
case actionTypes.fetchUserAuthFulfilled:
return Object.assign({}, state, {
...action.user,
isAuthorized: true,
authPending: false,
});
case actionTypes.fetchUserAuthRejected:
return Object.assign({}, state, {
error: action.error,
isAuthorized: false,
authPending: false,
});
default:
return state;
}
};
export const fetchUserAuthEpic = action$ =>
action$.ofType(actionTypes.fetchUserAuth)
.mergeMapTo(
hz.hasAuthToken() ? (
hz.currentUser()
.watch()
.mergeMap((user) => {
if (!user.name) {
hzUsers.update(Object.assign({}, user, { name: user.id.substring(0, 6) }));
}
return Observable.concat(
Observable.of(fetchUserAuthFulfilled(user)),
Observable.of(setRoomFormState(FORM_STATES.PRISTINE))
);
})
) : (
Observable.concat(
Observable.of(fetchUserAuthRejected('No user logged in')),
Observable.of(setRoomFormState(FORM_STATES.LOCKED))
)
)
);
export const setUsernameEpic = action$ =>
action$.ofType(actionTypes.setUsername)
.mergeMap(action =>
hz.currentUser()
.fetch()
.do(user => hzUsers.update({ id: user.id, name: action.name }))
.mergeMap(() =>
Observable.concat(
Observable.of(showToast(TOAST_STATES.SUCCESS, 'Username successfully updated')),
Observable.of(clearProfileForm()),
Observable.of(goBack())
)
)
.catch(() => showToast(TOAST_STATES.ERROR, 'Username update failed, please try again'))
);
export const logoutEpic = action$ =>
action$.ofType(actionTypes.logout)
.do(() => Horizon.clearAuthTokens())
.mapTo(setRoomFormState(FORM_STATES.LOCKED));
|
index.ios.js | minifast/react-native-demo | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class ReactNativeDemo extends Component {
constructor(props) {
super(props)
this.state = {text: 'Waiting'}
}
componentDidMount() {
const that = this
fetch('http://localhost:3000/test.json').
then((response) => {
return response.json();
}).
then((json) => {
that.stateUpdater({ text: json.text});
}).
catch((error) => {
that.stateUpdater({ error: 'Error grabbing server data.' });
});
}
stateUpdater(new_state, callback) {
swizzled_callback = () => {
if(typeof(callback) === 'function' ) { callback(); }
if(typeof(this.props.afterSetState) === 'function' ) { this.props.afterSetState(); }
}
this.setState(new_state, swizzled_callback);
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
<Text>{this.state.text}</Text>
</Text>
<Text style={styles.instructions}>
<Text>Hello, Ministry of Velocity!</Text>
</Text>
<Text style={styles.instructions}>
<Text>{this.state.error}</Text>
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('ReactNativeDemo', () => ReactNativeDemo);
|
cheesecakes/plugins/content-manager/admin/src/components/Wysiwyg/index.js | strapi/strapi-examples | /**
*
* Wysiwyg
*
*/
import React from 'react';
import {
ContentState,
EditorState,
getDefaultKeyBinding,
genKey,
Modifier,
RichUtils,
SelectionState,
} from 'draft-js';
import PropTypes from 'prop-types';
import { isEmpty, isNaN, replace, words } from 'lodash';
import cn from 'classnames';
import Controls from 'components/WysiwygInlineControls';
import Drop from 'components/WysiwygDropUpload';
import WysiwygBottomControls from 'components/WysiwygBottomControls';
import WysiwygEditor from 'components/WysiwygEditor';
import request from 'utils/request';
import CustomSelect from './customSelect';
import PreviewControl from './previewControl';
import PreviewWysiwyg from './previewWysiwyg';
import ToggleMode from './toggleMode';
import { CONTROLS } from './constants';
import {
getBlockContent,
getBlockStyle,
getDefaultSelectionOffsets,
getKeyCommandData,
getOffSets,
} from './helpers';
import {
createNewBlock,
getNextBlocksList,
getSelectedBlocksList,
onTab,
updateSelection,
} from './utils';
import styles from './styles.scss';
/* eslint-disable react/jsx-handler-names */
/* eslint-disable react/sort-comp */
class Wysiwyg extends React.Component {
constructor(props) {
super(props);
this.state = {
editorState: EditorState.createEmpty(),
isDraging: false,
isFocused: false,
isFullscreen: false,
isPreviewMode: false,
headerValue: '',
};
this.focus = () => {
this.setState({ isFocused: true });
return this.domEditor.focus();
};
this.blur = () => {
this.setState({ isFocused: false });
return this.domEditor.blur();
};
}
getChildContext = () => ({
handleChangeSelect: this.handleChangeSelect,
headerValue: this.state.headerValue,
html: this.props.value,
isPreviewMode: this.state.isPreviewMode,
isFullscreen: this.state.isFullscreen,
placeholder: this.props.placeholder,
});
componentDidMount() {
if (this.props.autoFocus) {
this.focus();
}
if (!isEmpty(this.props.value)) {
this.setInitialValue(this.props);
}
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState.editorState !== this.state.editorState) {
return true;
}
if (nextProps.resetProps !== this.props.resetProps) {
return true;
}
if (nextState.isDraging !== this.state.isDraging) {
return true;
}
if (nextState.isFocused !== this.state.isFocused) {
return true;
}
if (nextState.isFullscreen !== this.state.isFullscreen) {
return true;
}
if (nextState.isPreviewMode !== this.state.isPreviewMode) {
return true;
}
if (nextState.headerValue !== this.state.headerValue) {
return true;
}
return false;
}
componentDidUpdate(prevProps) {
// Handle resetProps
if (prevProps.resetProps !== this.props.resetProps) {
this.setInitialValue(this.props);
}
}
/**
* Init the editor with data from
* @param {[type]} props [description]
*/
setInitialValue = props => {
const contentState = ContentState.createFromText(props.value);
const newEditorState = EditorState.createWithContent(contentState);
const editorState = this.state.isFocused
? EditorState.moveFocusToEnd(newEditorState)
: newEditorState;
return this.setState({ editorState });
};
/**
* Handler to add B, I, Strike, U, link
* @param {String} content usually something like **textToReplace**
* @param {String} style
*/
addContent = (content, style) => {
const selectedText = this.getSelectedText();
// Retrieve the associated data for the type to add
const { innerContent, endReplacer, startReplacer } = getBlockContent(style);
// Replace the selected text by the markdown command or insert default text
const defaultContent =
selectedText === ''
? replace(content, 'textToReplace', innerContent)
: replace(content, 'textToReplace', selectedText);
// Get the current cursor position
const cursorPosition = getOffSets(this.getSelection()).start;
const textWithEntity = this.modifyBlockContent(defaultContent);
// Highlight the text
const { anchorOffset, focusOffset } = getDefaultSelectionOffsets(
defaultContent,
startReplacer,
endReplacer,
cursorPosition,
);
// Merge the current selection with the new one
const updatedSelection = this.getSelection().merge({ anchorOffset, focusOffset });
const newEditorState = EditorState.push(
this.getEditorState(),
textWithEntity,
'insert-character',
);
// Update the parent reducer
this.sendData(newEditorState);
// Don't handle selection : the user has selected some text to be changed with the appropriate markdown
if (selectedText !== '') {
return this.setState(
{
editorState: newEditorState,
},
() => {
this.focus();
},
);
}
return this.setState({
// Highlight the text if the selection wad empty
editorState: EditorState.forceSelection(newEditorState, updatedSelection),
});
};
/**
* Create an ordered list block
* @return ContentBlock
*/
addOlBlock = () => {
// Get all the selected blocks
const selectedBlocksList = getSelectedBlocksList(this.getEditorState());
let newEditorState = this.getEditorState();
// Check if the cursor is NOT at the beginning of a new line
// So we need to move all the next blocks
if (getOffSets(this.getSelection()).start !== 0) {
// Retrieve all the blocks after the current position
const nextBlocks = getNextBlocksList(newEditorState, this.getSelection().getStartKey());
let liNumber = 1;
// Loop to update each block after the inserted li
nextBlocks.map((block, index) => {
const previousContent =
index === 0
? this.getEditorState()
.getCurrentContent()
.getBlockForKey(this.getCurrentAnchorKey())
: newEditorState.getCurrentContent().getBlockBefore(block.getKey());
// Check if there was an li before the position so we update the entire list bullets
const number = previousContent ? parseInt(previousContent.getText().split('.')[0], 10) : 0;
liNumber = isNaN(number) ? 1 : number + 1;
const nextBlockText = index === 0 ? `${liNumber}. ` : nextBlocks.get(index - 1).getText();
// Update the current block
const newBlock = createNewBlock(nextBlockText, 'block-list', block.getKey());
// Update the contentState
const newContentState = this.createNewContentStateFromBlock(
newBlock,
newEditorState.getCurrentContent(),
);
newEditorState = EditorState.push(newEditorState, newContentState);
});
// Move the cursor to the correct position and add a space after '.'
// 2 for the dot and the space after, we add the number length (10 = offset of 2)
const offset = 2 + liNumber.toString().length;
const updatedSelection = updateSelection(this.getSelection(), nextBlocks, offset);
return this.setState({
editorState: EditorState.acceptSelection(newEditorState, updatedSelection),
});
}
// If the cursor is at the beginning we need to move all the content after the cursor so we don't loose the data
selectedBlocksList.map((block, i) => {
const selectedText = block.getText();
const li = selectedText === '' ? `${i + 1}. ` : `${i + 1}. ${selectedText}`;
const newBlock = createNewBlock(li, 'block-list', block.getKey());
const newContentState = this.createNewContentStateFromBlock(
newBlock,
newEditorState.getCurrentContent(),
);
newEditorState = EditorState.push(newEditorState, newContentState);
});
// Update the parent reducer
this.sendData(newEditorState);
return this.setState({ editorState: EditorState.moveFocusToEnd(newEditorState) });
};
/**
* Create an unordered list
* @return ContentBlock
*/
// NOTE: it's pretty much the same dynamic as above
// We don't use the same handler because it needs less logic than a ordered list
// so it's easier to maintain the code
addUlBlock = () => {
const selectedBlocksList = getSelectedBlocksList(this.getEditorState());
let newEditorState = this.getEditorState();
if (getOffSets(this.getSelection()).start !== 0) {
const nextBlocks = getNextBlocksList(newEditorState, this.getSelection().getStartKey());
nextBlocks.map((block, index) => {
const nextBlockText = index === 0 ? '- ' : nextBlocks.get(index - 1).getText();
const newBlock = createNewBlock(nextBlockText, 'block-list', block.getKey());
const newContentState = this.createNewContentStateFromBlock(
newBlock,
newEditorState.getCurrentContent(),
);
newEditorState = EditorState.push(newEditorState, newContentState);
});
const updatedSelection = updateSelection(this.getSelection(), nextBlocks, 2);
return this.setState({
editorState: EditorState.acceptSelection(newEditorState, updatedSelection),
});
}
selectedBlocksList.map(block => {
const selectedText = block.getText();
const li = selectedText === '' ? '- ' : `- ${selectedText}`;
const newBlock = createNewBlock(li, 'block-list', block.getKey());
const newContentState = this.createNewContentStateFromBlock(
newBlock,
newEditorState.getCurrentContent(),
);
newEditorState = EditorState.push(newEditorState, newContentState);
});
this.sendData(newEditorState);
return this.setState({ editorState: EditorState.moveFocusToEnd(newEditorState) });
};
/**
* Handler to create header
* @param {String} text header content
*/
addBlock = text => {
const nextBlockKey = this.getNextBlockKey(this.getCurrentAnchorKey()) || genKey();
const newBlock = createNewBlock(text, 'header', nextBlockKey);
const newContentState = this.createNewContentStateFromBlock(newBlock);
const newEditorState = this.createNewEditorState(newContentState, text);
return this.setState(
{
editorState: newEditorState,
},
() => {
this.focus();
},
);
};
/**
* Handler used for code block and Img controls
* @param {String} content the text that will be added
* @param {String} style the type
*/
addSimpleBlockWithSelection = (content, style) => {
const selectedText = this.getSelectedText();
const { innerContent, endReplacer, startReplacer } = getBlockContent(style);
const defaultContent =
selectedText === ''
? replace(content, 'textToReplace', innerContent)
: replace(content, 'textToReplace', selectedText);
const newBlock = createNewBlock(defaultContent);
const newContentState = this.createNewContentStateFromBlock(newBlock);
const { anchorOffset, focusOffset } = getDefaultSelectionOffsets(
defaultContent,
startReplacer,
endReplacer,
);
let newEditorState = this.createNewEditorState(newContentState, defaultContent);
const updatedSelection =
getOffSets(this.getSelection()).start === 0
? this.getSelection().merge({ anchorOffset, focusOffset })
: new SelectionState({
anchorKey: newBlock.getKey(),
anchorOffset,
focusOffset,
focusKey: newBlock.getKey(),
isBackward: false,
});
newEditorState = EditorState.acceptSelection(newEditorState, updatedSelection);
return this.setState({
editorState: EditorState.forceSelection(newEditorState, newEditorState.getSelection()),
});
};
/**
* Update the current editorState
* @param {Map} newContentState
* @param {String} text The text to add
* @return {Map} EditorState
*/
createNewEditorState = (newContentState, text) => {
let newEditorState;
if (getOffSets(this.getSelection()).start !== 0) {
newEditorState = EditorState.push(this.getEditorState(), newContentState);
} else {
const textWithEntity = this.modifyBlockContent(text);
newEditorState = EditorState.push(this.getEditorState(), textWithEntity, 'insert-characters');
}
return newEditorState;
};
/**
* Update the content of a block
* @param {Map} newBlock The new block
* @param {Map} contentState The ContentState
* @return {Map} The updated block
*/
createNewBlockMap = (newBlock, contentState) =>
contentState.getBlockMap().set(newBlock.key, newBlock);
createNewContentStateFromBlock = (
newBlock,
contentState = this.getEditorState().getCurrentContent(),
) =>
ContentState.createFromBlockArray(this.createNewBlockMap(newBlock, contentState).toArray())
.set('selectionBefore', contentState.getSelectionBefore())
.set('selectionAfter', contentState.getSelectionAfter());
getCharactersNumber = (editorState = this.getEditorState()) => {
const plainText = editorState.getCurrentContent().getPlainText();
const spacesNumber = plainText.split(' ').length;
return words(plainText).join('').length + spacesNumber - 1;
};
getEditorState = () => this.state.editorState;
/**
* Retrieve the selected text
* @return {Map}
*/
getSelection = () => this.getEditorState().getSelection();
/**
* Retrieve the cursor anchor key
* @return {String}
*/
getCurrentAnchorKey = () => this.getSelection().getAnchorKey();
/**
* Retrieve the current content block
* @return {Map} ContentBlock
*/
getCurrentContentBlock = () =>
this.getEditorState()
.getCurrentContent()
.getBlockForKey(this.getSelection().getAnchorKey());
/**
* Retrieve the block key after a specific one
* @param {String} currentBlockKey
* @param {Map} [editorState=this.getEditorState()] The current EditorState or the updated one
* @return {String} The next block key
*/
getNextBlockKey = (currentBlockKey, editorState = this.getEditorState()) =>
editorState.getCurrentContent().getKeyAfter(currentBlockKey);
getSelectedText = ({ start, end } = getOffSets(this.getSelection())) =>
this.getCurrentContentBlock()
.getText()
.slice(start, end);
handleBlur = () => {
const target = {
name: this.props.name,
type: 'textarea',
value: this.getEditorState()
.getCurrentContent()
.getPlainText(),
};
this.props.onBlur({ target });
this.blur();
};
handleChangeSelect = ({ target }) => {
this.setState({ headerValue: target.value });
const selectedText = this.getSelectedText();
const title = selectedText === '' ? `${target.value} ` : `${target.value} ${selectedText}`;
this.addBlock(title);
return this.setState({ headerValue: '' });
};
handleClickPreview = () => this.setState({ isPreviewMode: !this.state.isPreviewMode });
handleDragEnter = e => {
e.preventDefault();
e.stopPropagation();
if (!this.state.isDraging) {
this.setState({ isDraging: true });
}
};
handleDragLeave = () => this.setState({ isDraging: false });
handleDragOver = e => {
e.preventDefault();
e.stopPropagation();
};
handleDrop = e => {
e.preventDefault();
if (this.state.isPreviewMode) {
return this.setState({ isDraging: false });
}
const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
return this.uploadFile(files);
};
/**
* Handler that listens for specific key commands
* @param {String} command
* @param {Map} editorState
* @return {Bool}
*/
handleKeyCommand = (command, editorState) => {
const newState = RichUtils.handleKeyCommand(editorState, command);
if (command === 'bold' || command === 'italic' || command === 'underline') {
const { content, style } = getKeyCommandData(command);
this.addContent(content, style);
return false;
}
if (newState && command !== 'backspace') {
this.onChange(newState);
return true;
}
return false;
};
/**
* Handler to upload files on paste
* @param {Array<Blob>} files [description]
* @return {} DraftHandleValue
*/
handlePastedFiles = files => this.uploadFile(files);
handleReturn = (e, editorState) => {
const selection = editorState.getSelection();
const currentBlock = editorState.getCurrentContent().getBlockForKey(selection.getStartKey());
if (currentBlock.getText().split('')[0] === '-') {
this.addUlBlock();
return true;
}
if (
currentBlock.getText().split('.').length > 1 &&
!isNaN(parseInt(currentBlock.getText().split('.')[0], 10))
) {
this.addOlBlock();
return true;
}
return false;
};
mapKeyToEditorCommand = e => {
if (e.keyCode === 9 /* TAB */) {
const newEditorState = RichUtils.onTab(e, this.state.editorState, 4 /* maxDepth */);
if (newEditorState !== this.state.editorState) {
this.onChange(newEditorState);
}
return;
}
return getDefaultKeyBinding(e);
};
/**
* Change the content of a block
* @param {String]} text
* @param {Map} [contentState=this.getEditorState().getCurrentContent()]
* @return {Map}
*/
modifyBlockContent = (text, contentState = this.getEditorState().getCurrentContent()) =>
Modifier.replaceText(contentState, this.getSelection(), text);
onChange = editorState => {
this.setState({ editorState });
this.sendData(editorState);
};
handleTab = e => {
e.preventDefault();
const newEditorState = onTab(this.getEditorState());
return this.onChange(newEditorState);
};
/**
* Update the parent reducer
* @param {Map} editorState [description]
*/
sendData = editorState => {
if (this.getEditorState().getCurrentContent() === editorState.getCurrentContent())
return;
this.props.onChange({
target: {
value: editorState.getCurrentContent().getPlainText(),
name: this.props.name,
type: 'textarea',
},
});
}
toggleFullScreen = e => {
e.preventDefault();
this.setState({
isFullscreen: !this.state.isFullscreen,
isPreviewMode: false,
});
};
uploadFile = files => {
const formData = new FormData();
formData.append('files', files[0]);
const headers = {
'X-Forwarded-Host': 'strapi',
};
let newEditorState = this.getEditorState();
const nextBlocks = getNextBlocksList(newEditorState, this.getSelection().getStartKey());
// Loop to update each block after the inserted li
nextBlocks.map((block, index) => {
// Update the current block
const nextBlockText = index === 0 ? `![Uploading ${files[0].name}]()` : nextBlocks.get(index - 1).getText();
const newBlock = createNewBlock(nextBlockText, 'unstyled', block.getKey());
// Update the contentState
const newContentState = this.createNewContentStateFromBlock(
newBlock,
newEditorState.getCurrentContent(),
);
newEditorState = EditorState.push(newEditorState, newContentState);
});
const offset = `![Uploading ${files[0].name}]()`.length;
const updatedSelection = updateSelection(this.getSelection(), nextBlocks, offset);
this.setState({ editorState: EditorState.acceptSelection(newEditorState, updatedSelection) });
return request('/upload', { method: 'POST', headers, body: formData }, false, false)
.then(response => {
const nextBlockKey = newEditorState
.getCurrentContent()
.getKeyAfter(newEditorState.getSelection().getStartKey());
const content = ``;
const newContentState = this.createNewContentStateFromBlock(
createNewBlock(content, 'unstyled', nextBlockKey),
);
newEditorState = EditorState.push(newEditorState, newContentState);
const updatedSelection = updateSelection(this.getSelection(), nextBlocks, 2);
this.sendData(newEditorState);
this.setState({ editorState: EditorState.acceptSelection(newEditorState, updatedSelection) });
})
.catch(() => {
this.setState({ editorState: EditorState.undo(this.getEditorState()) });
})
.finally(() => {
this.setState({ isDraging: false });
});
};
renderDrop = () => (
<Drop
onDrop={this.handleDrop}
onDragOver={this.handleDragOver}
onDragLeave={this.handleDragLeave}
/>
);
render() {
const { editorState, isPreviewMode, isFullscreen } = this.state;
const editorStyle = isFullscreen ? { marginTop: '0' } : this.props.style;
return (
<div className={cn(isFullscreen && styles.fullscreenOverlay)}>
{/* FIRST EDITOR WITH CONTROLS} */}
<div
className={cn(
styles.editorWrapper,
!this.props.deactivateErrorHighlight && this.props.error && styles.editorError,
!isEmpty(this.props.className) && this.props.className,
)}
onClick={e => {
if (isFullscreen) {
e.preventDefault();
e.stopPropagation();
}
}}
onDragEnter={this.handleDragEnter}
onDragOver={this.handleDragOver}
style={editorStyle}
>
{this.state.isDraging && this.renderDrop()}
<div className={styles.controlsContainer}>
<CustomSelect />
{CONTROLS.map((value, key) => (
<Controls
key={key}
buttons={value}
disabled={isPreviewMode}
editorState={editorState}
handlers={{
addContent: this.addContent,
addOlBlock: this.addOlBlock,
addSimpleBlockWithSelection: this.addSimpleBlockWithSelection,
addUlBlock: this.addUlBlock,
}}
onToggle={this.toggleInlineStyle}
onToggleBlock={this.toggleBlockType}
/>
))}
{!isFullscreen ? (
<ToggleMode isPreviewMode={isPreviewMode} onClick={this.handleClickPreview} />
) : (
<div style={{ marginRight: '10px' }} />
)}
</div>
{/* WYSIWYG PREVIEW NOT FULLSCREEN */}
{isPreviewMode ? (
<PreviewWysiwyg data={this.props.value} />
) : (
<div
className={cn(styles.editor, isFullscreen && styles.editorFullScreen)}
onClick={this.focus}
>
<WysiwygEditor
blockStyleFn={getBlockStyle}
editorState={editorState}
handleKeyCommand={this.handleKeyCommand}
handlePastedFiles={this.handlePastedFiles}
handleReturn={this.handleReturn}
keyBindingFn={this.mapKeyToEditorCommand}
onBlur={this.handleBlur}
onChange={this.onChange}
onTab={this.handleTab}
placeholder={this.props.placeholder}
setRef={editor => (this.domEditor = editor)}
stripPastedStyles
tabIndex={this.props.tabIndex}
/>
<input className={styles.editorInput} tabIndex="-1" />
</div>
)}
{!isFullscreen && (
<WysiwygBottomControls
isPreviewMode={isPreviewMode}
onClick={this.toggleFullScreen}
onChange={this.handleDrop}
/>
)}
</div>
{/* PREVIEW WYSIWYG FULLSCREEN */}
{isFullscreen && (
<div
className={cn(styles.editorWrapper)}
onClick={e => {
e.preventDefault();
e.stopPropagation();
}}
style={{ marginTop: '0' }}
>
<PreviewControl
onClick={this.toggleFullScreen}
characters={this.getCharactersNumber()}
/>
<PreviewWysiwyg data={this.props.value} />
</div>
)}
</div>
);
}
}
Wysiwyg.childContextTypes = {
handleChangeSelect: PropTypes.func,
headerValue: PropTypes.string,
html: PropTypes.string,
isFullscreen: PropTypes.bool,
isPreviewMode: PropTypes.bool,
placeholder: PropTypes.string,
previewHTML: PropTypes.func,
};
Wysiwyg.defaultProps = {
autoFocus: false,
className: '',
deactivateErrorHighlight: false,
error: false,
onBlur: () => {},
onChange: () => {},
placeholder: '',
resetProps: false,
style: {},
tabIndex: '0',
value: '',
};
Wysiwyg.propTypes = {
autoFocus: PropTypes.bool,
className: PropTypes.string,
deactivateErrorHighlight: PropTypes.bool,
error: PropTypes.bool,
name: PropTypes.string.isRequired,
onBlur: PropTypes.func,
onChange: PropTypes.func,
placeholder: PropTypes.string,
resetProps: PropTypes.bool,
style: PropTypes.object,
tabIndex: PropTypes.string,
value: PropTypes.string,
};
export default Wysiwyg;
|
spec/javascripts/components/story/expanded_story/expanded_story_title_spec.js | Codeminer42/cm42-central | import React from 'react';
import { shallow } from 'enzyme';
import ExpandedStoryTitle from 'components/story/ExpandedStory/ExpandedStoryTitle';
describe('<ExpandedStoryTitle />', () => {
const setup = propOverrides => {
const defaultProps = () => ({
story: { _editing: { title: 'foo' } },
onEdit: sinon.spy(),
disabled: false,
...propOverrides
});
const wrapper = shallow(<ExpandedStoryTitle {...defaultProps()} />);
const input = wrapper.find('input');
return { wrapper, input };
};
it('renders properly', () => {
const { wrapper } = setup();
expect(wrapper).toExist();
});
describe('input element', () => {
it('has value equals to story title', () => {
const story = { _editing: { title: 'bar' } }
const { input } = setup({ story });
expect(input.prop('value')).toBe(story._editing.title);
});
it('calls onEdit with the right params', () => {
const mockOnEdit = sinon.spy();
const eventValue = 'foobar';
const { input } = setup({ onEdit: mockOnEdit });
input.simulate('change', { target: { value: eventValue } })
expect(mockOnEdit).toHaveBeenCalledWith(eventValue);
});
describe('when the component is enabled', () => {
it('should not be read-only', () => {
const { input } = setup({disabled: false});
expect(input.prop('readOnly')).toBe(false);
});
});
describe('when component is disabled', () => {
it('should be read-only', () => {
const { input } = setup({disabled: true});
expect(input.prop('readOnly')).toBe(true);
});
});
});
});
|
client-react/src/components/Accounts/Value.js | diman84/Welthperk | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { ContentBlock } from 'components';
import { Row, Col } from 'react-bootstrap';
import { WithTooltip } from 'components/Elements';
import { portfolioValue } from 'constants/staticText';
import { ValueChart } from 'components/Charts';
import ContentLoader, { Rect } from 'react-content-loader';
@connect(
state => ({
...state.account.current
}))
export default class Value extends Component {
static propTypes = {
balance: PropTypes.string,
earnings: PropTypes.string,
feeSavings: PropTypes.string,
loading: PropTypes.bool.isRequired,
loaded: PropTypes.bool.isRequired,
loadError: PropTypes.string
};
static defaultProps = {
balance: '',
earnings: '',
feeSavings: '',
loadError: ''
};
render() {
const {
balance,
earnings,
feeSavings,
loaded,
loading,
loadError
} = this.props;
return (
<ContentBlock>
<div>
<div className="value__header">
<Row>
<Col md={4} className="value__header--box">
<div className="value__header--title">
ACCOUNT VALUE
<WithTooltip id="tt1" tooltip={portfolioValue} >
<span className="info-icon" />
</WithTooltip>
</div>
{loaded &&
<div className="value__header--value">
{balance}
</div>}
{loading &&
<div>
<ContentLoader height={50} speed={1}>
<Rect x={50} y={10} height={20} radius={5} width={200} />
<Rect x={50} y={40} height={10} radius={5} width={100} />
</ContentLoader>
</div>}
</Col>
<Col md={4} className="value__header--box">
<div className="value__header--title">
EARNINGS
<WithTooltip id="tt2" tooltip={portfolioValue} >
<span className="info-icon" />
</WithTooltip>
</div>
{loaded &&
<div className="value__header--value">
{earnings}
</div>}
{loading &&
<div>
<ContentLoader height={50} speed={1}>
<Rect x={80} y={10} height={20} radius={5} width={200} />
<Rect x={80} y={40} height={10} radius={5} width={100} />
</ContentLoader>
</div>}
</Col>
<Col md={4} className="value__header--box">
<div className="value__header--title">
SAVED ON FEES
<WithTooltip id="tt3" tooltip={portfolioValue} >
<span className="info-icon" />
</WithTooltip>
</div>
{loaded &&
<div className="value__header--value">
{feeSavings}
</div>}
{loading &&
<div>
<ContentLoader height={50} speed={1}>
<Rect x={100} y={10} height={20} radius={5} width={200} />
<Rect x={100} y={40} height={10} radius={5} width={100} />
</ContentLoader>
</div>}
</Col>
</Row>
</div>
{!loading && !loaded && loadError &&
<Row>
<Col md={12} className="value__header--value">
<div className="value__header--error">
{loadError}
</div>
</Col>
</Row>}
<div className="value__content pd-30">
<h2>Overall Chart</h2>
<ValueChart data={[1, 2, 3]} />
</div>
</div>
</ContentBlock>
);
}
}
|
packages/material-ui-icons/src/PhonelinkErase.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PhonelinkErase = props =>
<SvgIcon {...props}>
<path d="M13 8.2l-1-1-4 4-4-4-1 1 4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4zM19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2z" />
</SvgIcon>;
PhonelinkErase = pure(PhonelinkErase);
PhonelinkErase.muiName = 'SvgIcon';
export default PhonelinkErase;
|
index.js | react-rpm/react-rpm | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import App from '../../../app/containers/App';
console.log('In index!');
render(
<App/>,
document.getElementById('root')
);
|
stories/components/imageCard/index.js | hollomancer/operationcode_frontend | import React from 'react';
import { storiesOf } from '@storybook/react';
import ImageCard from 'shared/components/imageCard/imageCard';
import jamesBondJpg from '../../asset/james-bond.jpg';
storiesOf('shared/components/imageCard', module)
.add('Default', () => (
<ImageCard
image={jamesBondJpg}
title="James Bond"
cardText="Hello World"
buttonText="Link"
link="http://google.com"
/>
)); |
ajax/libs/cleave.js/0.7.21/cleave-angular.js | wout/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Cleave"] = factory();
else
root["Cleave"] = factory();
})(this, function() {
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__) {
/* WEBPACK VAR INJECTION */(function(global) {'use strict';
/**
* Construct a new Cleave instance by passing the configuration object
*
* @param {String / HTMLElement} element
* @param {Object} opts
*/
var Cleave = function (element, opts) {
var owner = this;
if (typeof element === 'string') {
owner.element = document.querySelector(element);
} else {
owner.element = ((typeof element.length !== 'undefined') && element.length > 0) ? element[0] : element;
}
if (!owner.element) {
throw new Error('[cleave.js] Please check the element');
}
opts.initValue = owner.element.value;
owner.properties = Cleave.DefaultProperties.assign({}, opts);
owner.init();
};
Cleave.prototype = {
init: function () {
var owner = this, pps = owner.properties;
// no need to use this lib
if (!pps.numeral && !pps.phone && !pps.creditCard && !pps.date && (pps.blocksLength === 0 && !pps.prefix)) {
return;
}
pps.maxLength = Cleave.Util.getMaxLength(pps.blocks);
owner.isAndroid = Cleave.Util.isAndroid();
owner.lastInputValue = '';
owner.onChangeListener = owner.onChange.bind(owner);
owner.onKeyDownListener = owner.onKeyDown.bind(owner);
owner.onCutListener = owner.onCut.bind(owner);
owner.onCopyListener = owner.onCopy.bind(owner);
owner.element.addEventListener('input', owner.onChangeListener);
owner.element.addEventListener('keydown', owner.onKeyDownListener);
owner.element.addEventListener('cut', owner.onCutListener);
owner.element.addEventListener('copy', owner.onCopyListener);
owner.initPhoneFormatter();
owner.initDateFormatter();
owner.initNumeralFormatter();
owner.onInput(pps.initValue);
},
initNumeralFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.numeral) {
return;
}
pps.numeralFormatter = new Cleave.NumeralFormatter(
pps.numeralDecimalMark,
pps.numeralIntegerScale,
pps.numeralDecimalScale,
pps.numeralThousandsGroupStyle,
pps.numeralPositiveOnly,
pps.delimiter
);
},
initDateFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.date) {
return;
}
pps.dateFormatter = new Cleave.DateFormatter(pps.datePattern);
pps.blocks = pps.dateFormatter.getBlocks();
pps.blocksLength = pps.blocks.length;
pps.maxLength = Cleave.Util.getMaxLength(pps.blocks);
},
initPhoneFormatter: function () {
var owner = this, pps = owner.properties;
if (!pps.phone) {
return;
}
// Cleave.AsYouTypeFormatter should be provided by
// external google closure lib
try {
pps.phoneFormatter = new Cleave.PhoneFormatter(
new pps.root.Cleave.AsYouTypeFormatter(pps.phoneRegionCode),
pps.delimiter
);
} catch (ex) {
throw new Error('[cleave.js] Please include phone-type-formatter.{country}.js lib');
}
},
onKeyDown: function (event) {
var owner = this, pps = owner.properties,
charCode = event.which || event.keyCode,
Util = Cleave.Util,
currentValue = owner.element.value;
if (Util.isAndroidBackspaceKeydown(owner.lastInputValue, currentValue)) {
charCode = 8;
}
owner.lastInputValue = currentValue;
// hit backspace when last character is delimiter
if (charCode === 8 && Util.isDelimiter(currentValue.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
pps.backspace = true;
return;
}
pps.backspace = false;
},
onChange: function () {
this.onInput(this.element.value);
},
onCut: function (e) {
this.copyClipboardData(e);
this.onInput('');
},
onCopy: function (e) {
this.copyClipboardData(e);
},
copyClipboardData: function (e) {
var owner = this,
pps = owner.properties,
Util = Cleave.Util,
inputValue = owner.element.value,
textToCopy = '';
if (!pps.copyDelimiter) {
textToCopy = Util.stripDelimiters(inputValue, pps.delimiter, pps.delimiters);
} else {
textToCopy = inputValue;
}
try {
if (e.clipboardData) {
e.clipboardData.setData('Text', textToCopy);
} else {
window.clipboardData.setData('Text', textToCopy);
}
e.preventDefault();
} catch (ex) {
// empty
}
},
onInput: function (value) {
var owner = this, pps = owner.properties,
prev = value,
Util = Cleave.Util;
// case 1: delete one more character "4"
// 1234*| -> hit backspace -> 123|
// case 2: last character is not delimiter which is:
// 12|34* -> hit backspace -> 1|34*
// note: no need to apply this for numeral mode
if (!pps.numeral && pps.backspace && !Util.isDelimiter(value.slice(-pps.delimiterLength), pps.delimiter, pps.delimiters)) {
value = Util.headStr(value, value.length - pps.delimiterLength);
}
// phone formatter
if (pps.phone) {
pps.result = pps.phoneFormatter.format(value);
owner.updateValueState();
return;
}
// numeral formatter
if (pps.numeral) {
pps.result = pps.prefix + pps.numeralFormatter.format(value);
owner.updateValueState();
return;
}
// date
if (pps.date) {
value = pps.dateFormatter.getValidatedDate(value);
}
// strip delimiters
value = Util.stripDelimiters(value, pps.delimiter, pps.delimiters);
// strip prefix
value = Util.getPrefixStrippedValue(value, pps.prefix, pps.prefixLength);
// strip non-numeric characters
value = pps.numericOnly ? Util.strip(value, /[^\d]/g) : value;
// convert case
value = pps.uppercase ? value.toUpperCase() : value;
value = pps.lowercase ? value.toLowerCase() : value;
// prefix
if (pps.prefix) {
value = pps.prefix + value;
// no blocks specified, no need to do formatting
if (pps.blocksLength === 0) {
pps.result = value;
owner.updateValueState();
return;
}
}
// update credit card props
if (pps.creditCard) {
owner.updateCreditCardPropsByValue(value);
}
// strip over length characters
value = Util.headStr(value, pps.maxLength);
// apply blocks
pps.result = Util.getFormattedValue(value, pps.blocks, pps.blocksLength, pps.delimiter, pps.delimiters);
// nothing changed
// prevent update value to avoid caret position change
if (prev === pps.result && prev !== pps.prefix) {
return;
}
owner.updateValueState();
},
updateCreditCardPropsByValue: function (value) {
var owner = this, pps = owner.properties,
Util = Cleave.Util,
creditCardInfo;
// At least one of the first 4 characters has changed
if (Util.headStr(pps.result, 4) === Util.headStr(value, 4)) {
return;
}
creditCardInfo = Cleave.CreditCardDetector.getInfo(value, pps.creditCardStrictMode);
pps.blocks = creditCardInfo.blocks;
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
// credit card type changed
if (pps.creditCardType !== creditCardInfo.type) {
pps.creditCardType = creditCardInfo.type;
pps.onCreditCardTypeChanged.call(owner, pps.creditCardType);
}
},
updateValueState: function () {
var owner = this;
// fix Android browser type="text" input field
// cursor not jumping issue
if (owner.isAndroid) {
window.setTimeout(function () {
owner.element.value = owner.properties.result;
}, 1);
return;
}
owner.element.value = owner.properties.result;
},
setPhoneRegionCode: function (phoneRegionCode) {
var owner = this, pps = owner.properties;
pps.phoneRegionCode = phoneRegionCode;
owner.initPhoneFormatter();
owner.onChange();
},
setRawValue: function (value) {
var owner = this, pps = owner.properties;
value = value !== undefined && value !== null ? value.toString() : '';
if (pps.numeral) {
value = value.replace('.', pps.numeralDecimalMark);
}
owner.element.value = value;
owner.onInput(value);
},
getRawValue: function () {
var owner = this,
pps = owner.properties,
Util = Cleave.Util,
rawValue = owner.element.value;
if (pps.rawValueTrimPrefix) {
rawValue = Util.getPrefixStrippedValue(rawValue, pps.prefix, pps.prefixLength);
}
if (pps.numeral) {
rawValue = pps.numeralFormatter.getRawValue(rawValue);
} else {
rawValue = Util.stripDelimiters(rawValue, pps.delimiter, pps.delimiters);
}
return rawValue;
},
getFormattedValue: function () {
return this.element.value;
},
destroy: function () {
var owner = this;
owner.element.removeEventListener('input', owner.onChangeListener);
owner.element.removeEventListener('keydown', owner.onKeyDownListener);
owner.element.removeEventListener('cut', owner.onCutListener);
owner.element.removeEventListener('copy', owner.onCopyListener);
},
toString: function () {
return '[Cleave Object]';
}
};
Cleave.NumeralFormatter = __webpack_require__(1);
Cleave.DateFormatter = __webpack_require__(2);
Cleave.PhoneFormatter = __webpack_require__(3);
Cleave.CreditCardDetector = __webpack_require__(4);
Cleave.Util = __webpack_require__(5);
Cleave.DefaultProperties = __webpack_require__(6);
// for angular directive
((typeof global === 'object' && global) ? global : window)['Cleave'] = Cleave;
// CommonJS
module.exports = Cleave;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 1 */
/***/ function(module, exports) {
'use strict';
var NumeralFormatter = function (numeralDecimalMark,
numeralIntegerScale,
numeralDecimalScale,
numeralThousandsGroupStyle,
numeralPositiveOnly,
delimiter) {
var owner = this;
owner.numeralDecimalMark = numeralDecimalMark || '.';
owner.numeralIntegerScale = numeralIntegerScale >= 0 ? numeralIntegerScale : 10;
owner.numeralDecimalScale = numeralDecimalScale >= 0 ? numeralDecimalScale : 2;
owner.numeralThousandsGroupStyle = numeralThousandsGroupStyle || NumeralFormatter.groupStyle.thousand;
owner.numeralPositiveOnly = !!numeralPositiveOnly;
owner.delimiter = (delimiter || delimiter === '') ? delimiter : ',';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
};
NumeralFormatter.groupStyle = {
thousand: 'thousand',
lakh: 'lakh',
wan: 'wan'
};
NumeralFormatter.prototype = {
getRawValue: function (value) {
return value.replace(this.delimiterRE, '').replace(this.numeralDecimalMark, '.');
},
format: function (value) {
var owner = this, parts, partInteger, partDecimal = '';
// strip alphabet letters
value = value.replace(/[A-Za-z]/g, '')
// replace the first decimal mark with reserved placeholder
.replace(owner.numeralDecimalMark, 'M')
// strip non numeric letters except minus and "M"
// this is to ensure prefix has been stripped
.replace(/[^\dM-]/g, '')
// replace the leading minus with reserved placeholder
.replace(/^\-/, 'N')
// strip the other minus sign (if present)
.replace(/\-/g, '')
// replace the minus sign (if present)
.replace('N', owner.numeralPositiveOnly ? '' : '-')
// replace decimal mark
.replace('M', owner.numeralDecimalMark)
// strip any leading zeros
.replace(/^(-)?0+(?=\d)/, '$1');
partInteger = value;
if (value.indexOf(owner.numeralDecimalMark) >= 0) {
parts = value.split(owner.numeralDecimalMark);
partInteger = parts[0];
partDecimal = owner.numeralDecimalMark + parts[1].slice(0, owner.numeralDecimalScale);
}
if (owner.numeralIntegerScale > 0) {
partInteger = partInteger.slice(0, owner.numeralIntegerScale + (value.slice(0, 1) === '-' ? 1 : 0));
}
switch (owner.numeralThousandsGroupStyle) {
case NumeralFormatter.groupStyle.lakh:
partInteger = partInteger.replace(/(\d)(?=(\d\d)+\d$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.wan:
partInteger = partInteger.replace(/(\d)(?=(\d{4})+$)/g, '$1' + owner.delimiter);
break;
default:
partInteger = partInteger.replace(/(\d)(?=(\d{3})+$)/g, '$1' + owner.delimiter);
}
return partInteger.toString() + (owner.numeralDecimalScale > 0 ? partDecimal.toString() : '');
}
};
module.exports = NumeralFormatter;
/***/ },
/* 2 */
/***/ function(module, exports) {
'use strict';
var DateFormatter = function (datePattern) {
var owner = this;
owner.blocks = [];
owner.datePattern = datePattern;
owner.initBlocks();
};
DateFormatter.prototype = {
initBlocks: function () {
var owner = this;
owner.datePattern.forEach(function (value) {
if (value === 'Y') {
owner.blocks.push(4);
} else {
owner.blocks.push(2);
}
});
},
getBlocks: function () {
return this.blocks;
},
getValidatedDate: function (value) {
var owner = this, result = '';
value = value.replace(/[^\d]/g, '');
owner.blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
sub0 = sub.slice(0, 1),
rest = value.slice(length);
switch (owner.datePattern[index]) {
case 'd':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 3) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 31) {
sub = '31';
}
break;
case 'm':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 1) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 12) {
sub = '12';
}
break;
}
result += sub;
// update remaining string
value = rest;
}
});
return result;
}
};
module.exports = DateFormatter;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
var PhoneFormatter = function (formatter, delimiter) {
var owner = this;
owner.delimiter = (delimiter || delimiter === '') ? delimiter : ' ';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
owner.formatter = formatter;
};
PhoneFormatter.prototype = {
setFormatter: function (formatter) {
this.formatter = formatter;
},
format: function (phoneNumber) {
var owner = this;
owner.formatter.clear();
// only keep number and +
phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
// strip delimiter
phoneNumber = phoneNumber.replace(owner.delimiterRE, '');
var result = '', current, validated = false;
for (var i = 0, iMax = phoneNumber.length; i < iMax; i++) {
current = owner.formatter.inputDigit(phoneNumber.charAt(i));
// has ()- or space inside
if (/[\s()-]/g.test(current)) {
result = current;
validated = true;
} else {
if (!validated) {
result = current;
}
// else: over length input
// it turns to invalid number again
}
}
// strip ()
// e.g. US: 7161234567 returns (716) 123-4567
result = result.replace(/[()]/g, '');
// replace library delimiter with user customized delimiter
result = result.replace(/[\s-]/g, owner.delimiter);
return result;
}
};
module.exports = PhoneFormatter;
/***/ },
/* 4 */
/***/ function(module, exports) {
'use strict';
var CreditCardDetector = {
blocks: {
uatp: [4, 5, 6],
amex: [4, 6, 5],
diners: [4, 6, 4],
discover: [4, 4, 4, 4],
mastercard: [4, 4, 4, 4],
dankort: [4, 4, 4, 4],
instapayment: [4, 4, 4, 4],
jcb: [4, 4, 4, 4],
maestro: [4, 4, 4, 4],
visa: [4, 4, 4, 4],
general: [4, 4, 4, 4],
generalStrict: [4, 4, 4, 7]
},
re: {
// starts with 1; 15 digits, not starts with 1800 (jcb card)
uatp: /^(?!1800)1\d{0,14}/,
// starts with 34/37; 15 digits
amex: /^3[47]\d{0,13}/,
// starts with 6011/65/644-649; 16 digits
discover: /^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/,
// starts with 300-305/309 or 36/38/39; 14 digits
diners: /^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,
// starts with 51-55/22-27; 16 digits
mastercard: /^(5[1-5]|2[2-7])\d{0,14}/,
// starts with 5019/4175/4571; 16 digits
dankort: /^(5019|4175|4571)\d{0,12}/,
// starts with 637-639; 16 digits
instapayment: /^63[7-9]\d{0,13}/,
// starts with 2131/1800/35; 16 digits
jcb: /^(?:2131|1800|35\d{0,2})\d{0,12}/,
// starts with 50/56-58/6304/67; 16 digits
maestro: /^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/,
// starts with 4; 16 digits
visa: /^4\d{0,15}/
},
getInfo: function (value, strictMode) {
var blocks = CreditCardDetector.blocks,
re = CreditCardDetector.re;
// In theory, visa credit card can have up to 19 digits number.
// Set strictMode to true will remove the 16 max-length restrain,
// however, I never found any website validate card number like
// this, hence probably you don't need to enable this option.
strictMode = !!strictMode;
if (re.amex.test(value)) {
return {
type: 'amex',
blocks: blocks.amex
};
} else if (re.uatp.test(value)) {
return {
type: 'uatp',
blocks: blocks.uatp
};
} else if (re.diners.test(value)) {
return {
type: 'diners',
blocks: blocks.diners
};
} else if (re.discover.test(value)) {
return {
type: 'discover',
blocks: strictMode ? blocks.generalStrict : blocks.discover
};
} else if (re.mastercard.test(value)) {
return {
type: 'mastercard',
blocks: blocks.mastercard
};
} else if (re.dankort.test(value)) {
return {
type: 'dankort',
blocks: blocks.dankort
};
} else if (re.instapayment.test(value)) {
return {
type: 'instapayment',
blocks: blocks.instapayment
};
} else if (re.jcb.test(value)) {
return {
type: 'jcb',
blocks: blocks.jcb
};
} else if (re.maestro.test(value)) {
return {
type: 'maestro',
blocks: strictMode ? blocks.generalStrict : blocks.maestro
};
} else if (re.visa.test(value)) {
return {
type: 'visa',
blocks: strictMode ? blocks.generalStrict : blocks.visa
};
} else {
return {
type: 'unknown',
blocks: strictMode ? blocks.generalStrict : blocks.general
};
}
}
};
module.exports = CreditCardDetector;
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
var Util = {
noop: function () {
},
strip: function (value, re) {
return value.replace(re, '');
},
isDelimiter: function (letter, delimiter, delimiters) {
// single delimiter
if (delimiters.length === 0) {
return letter === delimiter;
}
// multiple delimiters
return delimiters.some(function (current) {
if (letter === current) {
return true;
}
});
},
stripDelimiters: function (value, delimiter, delimiters) {
// single delimiter
if (delimiters.length === 0) {
var delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
return value.replace(delimiterRE, '');
}
// multiple delimiters
delimiters.forEach(function (current) {
value = value.replace(new RegExp('\\' + current, 'g'), '');
});
return value;
},
headStr: function (str, length) {
return str.slice(0, length);
},
getMaxLength: function (blocks) {
return blocks.reduce(function (previous, current) {
return previous + current;
}, 0);
},
// strip value by prefix length
// for prefix: PRE
// (PRE123, 3) -> 123
// (PR123, 3) -> 23 this happens when user hits backspace in front of "PRE"
getPrefixStrippedValue: function (value, prefix, prefixLength) {
if (value.slice(0, prefixLength) !== prefix) {
var diffIndex = this.getFirstDiffIndex(prefix, value.slice(0, prefixLength));
value = prefix + value.slice(diffIndex, diffIndex + 1) + value.slice(prefixLength + 1);
}
return value.slice(prefixLength);
},
getFirstDiffIndex: function (prev, current) {
var index = 0;
while (prev.charAt(index) === current.charAt(index))
if (prev.charAt(index++) === '')
return -1;
return index;
},
getFormattedValue: function (value, blocks, blocksLength, delimiter, delimiters) {
var result = '',
multipleDelimiters = delimiters.length > 0,
currentDelimiter;
// no options, normal input
if (blocksLength === 0) {
return value;
}
blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
result += sub;
currentDelimiter = multipleDelimiters ? (delimiters[index] || currentDelimiter) : delimiter;
if (sub.length === length && index < blocksLength - 1) {
result += currentDelimiter;
}
// update remaining string
value = rest;
}
});
return result;
},
isAndroid: function () {
if (navigator && /android/i.test(navigator.userAgent)) {
return true;
}
return false;
},
// On Android chrome, the keyup and keydown events
// always return key code 229 as a composition that
// buffers the user’s keystrokes
// see https://github.com/nosir/cleave.js/issues/147
isAndroidBackspaceKeydown: function (lastInputValue, currentInputValue) {
if (!this.isAndroid()) {
return false;
}
return currentInputValue === lastInputValue.slice(0, -1);
}
};
module.exports = Util;
/***/ },
/* 6 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(global) {'use strict';
/**
* Props Assignment
*
* Separate this, so react module can share the usage
*/
var DefaultProperties = {
// Maybe change to object-assign
// for now just keep it as simple
assign: function (target, opts) {
target = target || {};
opts = opts || {};
// credit card
target.creditCard = !!opts.creditCard;
target.creditCardStrictMode = !!opts.creditCardStrictMode;
target.creditCardType = '';
target.onCreditCardTypeChanged = opts.onCreditCardTypeChanged || (function () {});
// phone
target.phone = !!opts.phone;
target.phoneRegionCode = opts.phoneRegionCode || 'AU';
target.phoneFormatter = {};
// date
target.date = !!opts.date;
target.datePattern = opts.datePattern || ['d', 'm', 'Y'];
target.dateFormatter = {};
// numeral
target.numeral = !!opts.numeral;
target.numeralIntegerScale = opts.numeralIntegerScale >= 0 ? opts.numeralIntegerScale : 10;
target.numeralDecimalScale = opts.numeralDecimalScale >= 0 ? opts.numeralDecimalScale : 2;
target.numeralDecimalMark = opts.numeralDecimalMark || '.';
target.numeralThousandsGroupStyle = opts.numeralThousandsGroupStyle || 'thousand';
target.numeralPositiveOnly = !!opts.numeralPositiveOnly;
// others
target.numericOnly = target.creditCard || target.date || !!opts.numericOnly;
target.uppercase = !!opts.uppercase;
target.lowercase = !!opts.lowercase;
target.prefix = (target.creditCard || target.phone || target.date) ? '' : (opts.prefix || '');
target.prefixLength = target.prefix.length;
target.rawValueTrimPrefix = !!opts.rawValueTrimPrefix;
target.copyDelimiter = !!opts.copyDelimiter;
target.initValue = opts.initValue === undefined ? '' : opts.initValue.toString();
target.delimiter =
(opts.delimiter || opts.delimiter === '') ? opts.delimiter :
(opts.date ? '/' :
(opts.numeral ? ',' :
(opts.phone ? ' ' :
' ')));
target.delimiterLength = target.delimiter.length;
target.delimiters = opts.delimiters || [];
target.blocks = opts.blocks || [];
target.blocksLength = target.blocks.length;
target.root = (typeof global === 'object' && global) ? global : window;
target.maxLength = 0;
target.backspace = false;
target.result = '';
return target;
}
};
module.exports = DefaultProperties;
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }
/******/ ])
});
;
angular.module('cleave.js', [])
.directive('cleave', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
cleave: '&',
onValueChange: '&?'
},
compile: function () {
return {
pre: function ($scope, $element, attrs, ngModelCtrl) {
$scope.cleave = new window.Cleave($element[0], $scope.cleave());
ngModelCtrl.$formatters.push(function (val) {
$scope.cleave.setRawValue(val);
return $scope.cleave.getFormattedValue();
});
ngModelCtrl.$parsers.push(function (newFormattedValue) {
if ($scope.onValueChange) {
$scope.onValueChange()(newFormattedValue);
}
return $scope.cleave.getRawValue();
});
}
};
}
};
});
|
src/components/App/index.js | u-wave/web | import React from 'react';
import PropTypes from 'prop-types';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import FooterBar from '../FooterBar';
import HeaderBar from '../../containers/HeaderBar';
import Video from '../../containers/Video';
import ErrorArea from '../../containers/ErrorArea';
import Overlays from './Overlays';
import PlaylistManager from '../../containers/PlaylistManager';
import RoomHistory from '../../containers/RoomHistory';
import SettingsManager from '../../containers/SettingsManager';
import AdminProxy from '../AdminProxy';
import About from '../../containers/About';
import ConnectionIndicator from '../ConnectionIndicator';
import SidePanels from '../SidePanels';
import Dialogs from '../Dialogs';
import AddToPlaylistMenu from '../../containers/AddToPlaylistMenu';
import DragLayer from '../../containers/DragLayer';
function App({
activeOverlay,
isConnected,
settings,
onCloseOverlay,
}) {
const el = (
<div className="App">
<div className="AppColumn AppColumn--left">
<div className="AppRow AppRow--top">
<HeaderBar
className="App-header"
title="üWave"
/>
</div>
<div className="AppRow AppRow--middle App-media">
<Video
enabled={settings.videoEnabled}
size={settings.videoSize}
isMuted={settings.muted}
volume={settings.volume}
/>
<ErrorArea />
<ConnectionIndicator isConnected={isConnected} />
</div>
<Overlays transitionName="Overlay" active={activeOverlay}>
<About key="about" onCloseOverlay={onCloseOverlay} />
<AdminProxy key="admin" onCloseOverlay={onCloseOverlay} />
<PlaylistManager key="playlistManager" onCloseOverlay={onCloseOverlay} />
<RoomHistory key="roomHistory" onCloseOverlay={onCloseOverlay} />
<SettingsManager key="settings" onCloseOverlay={onCloseOverlay} />
</Overlays>
<FooterBar className="AppRow AppRow--bottom" />
</div>
<div className="AppColumn AppColumn--right">
<SidePanels />
</div>
<Dialogs />
<AddToPlaylistMenu />
<DragLayer />
</div>
);
return (
<DndProvider backend={HTML5Backend}>
{el}
</DndProvider>
);
}
App.propTypes = {
activeOverlay: PropTypes.string,
isConnected: PropTypes.bool.isRequired,
settings: PropTypes.object.isRequired,
onCloseOverlay: PropTypes.func.isRequired,
};
export default App;
|
app/containers/productListContainer.js | t0nin0s/react-product-list | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { selectProduct, fetchProducts } from '../actions/productActions'
import ProductList from '../components/productList'
export const PREV = 'PREV'
export const NEXT = 'NEXT'
class ProductListContainer extends Component {
constructor(props){
super(props)
this.getPage = this.getPage.bind(this)
}
componentWillMount() {
this.props.fetchProducts()
}
getPage(page) {
switch(page){
case NEXT:
this.props.fetchProducts(this.props.page + 1);
break;
case PREV:
if(this.props.page > 1)
this.props.fetchProducts(this.props.page - 1);
break;
default:
break;
}
}
render() {
return ( <ProductList {...this.props} getPage={this.getPage} /> );
}
}
function mapStateToProps(state) {
return {
products: state.products.list,
page: state.products.page,
isFetching: state.products.isFetching
};
}
function matchDispatchToProps(dispatch){
return bindActionCreators({selectProduct, fetchProducts}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(ProductListContainer);
|
app/javascript/mastodon/components/permalink.js | ikuradon/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class Permalink extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
className: PropTypes.string,
href: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
children: PropTypes.node,
onInterceptClick: PropTypes.func,
};
handleClick = e => {
if (this.props.onInterceptClick && this.props.onInterceptClick()) {
e.preventDefault();
return;
}
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(this.props.to);
}
}
render () {
const { href, children, className, onInterceptClick, ...other } = this.props;
return (
<a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}>
{children}
</a>
);
}
}
|
sites/default/files/js/js_Rd2YWjTgpPwZ1kmnM924o3cLMuVszPN8J51DKyDTRxI.js | suzi/fdug_demo_1115 | /*! jQuery v2.1.4 | (c) 2005, 2015 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=a.document,m="2.1.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,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=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.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},n.extend=n.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||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)+1>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},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=s(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(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;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=s(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&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b="length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=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)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(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||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(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 H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(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 pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(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 p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),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))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),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===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(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?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.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 ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.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},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.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=ga.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=ga.selectors={cacheLength:50,createPseudo:ia,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(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===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]||ga.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]&&ga.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(ca,da).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("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.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.replace(Q," ")+" ").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()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(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),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).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:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(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]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.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?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(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 ta(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 ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(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 wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(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?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(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 wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(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]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.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(ca,da),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(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(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&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.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?n.extend(a,d):d}},e={};return d.pipe=d.then,n.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&&n.isFunction(a.promise)?e:0,g=1===f?a:n.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]&&n.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;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(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};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){
return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.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.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.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 L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.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=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!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(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.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=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.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(g in a)this.on(g,b,c,a[g],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=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.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,n(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=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=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=ja(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=ja(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?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(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,n.cleanData(oa(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,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.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}function ya(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.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",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),f.removeChild(c),b}})}}(),n.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 za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(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+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",ta(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.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}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xa(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":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fa(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Ba.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.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))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wa(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Ja(this,!0)},hide:function(){return Ja(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,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||(n.cssNumber[c]?"":"px")},cur:function(){var a=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Ka.propHooks.scrollTop=Ka.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.exec(n.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,n.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 Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||ta(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Na.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?ta(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ua(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wa(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.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 Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),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:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:La||Sa(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.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(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.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)}n.Animation=n.extend(Xa,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xa(this,n.extend({},a),f);(e||L.get(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=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pa.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)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.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})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.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=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Ya,Za,$a=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Za:Ya)),
void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.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 n.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=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Za={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.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||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.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){return a.hasAttribute("tabindex")||_a.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ab=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ab," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.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(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(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(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.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&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.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){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.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 cb=n.now(),db=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function rb(a,b,c,d){var e={},f=a===mb;function g(h){var i;return e[h]=!0,n.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 sb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function tb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function ub(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}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,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":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=gb.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e: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 c&&c.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||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(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]?", "+nb+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=rb(mb,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=tb(k,v,f)),u=ub(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=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,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;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)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Cb[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.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,Fb.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Jb(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Jb(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.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?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n});
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])<u?i=a+1:o=a}return i},m.indexOf=r(1,m.findIndex,m.sortedIndex),m.lastIndexOf=r(-1,m.findLastIndex),m.range=function(n,t,r){null==t&&(t=n||0,n=0),r=r||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=Array(e),i=0;e>i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e<arguments.length;)i.push(arguments[e++]);return E(n,r,this,this,i)};return r},m.bindAll=function(n){var t,r,e=arguments.length;if(1>=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this);
(function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,n){e.Backbone=t(e,n,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(n){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var n=t.Backbone;var s=Array.prototype.slice;e.VERSION="1.2.3";e.$=r;e.noConflict=function(){t.Backbone=n;return this};e.emulateHTTP=false;e.emulateJSON=false;var a=function(t,e,r){switch(t){case 1:return function(){return i[e](this[r])};case 2:return function(t){return i[e](this[r],t)};case 3:return function(t,n){return i[e](this[r],h(t,this),n)};case 4:return function(t,n,s){return i[e](this[r],h(t,this),n,s)};default:return function(){var t=s.call(arguments);t.unshift(this[r]);return i[e].apply(i,t)}}};var o=function(t,e,r){i.each(e,function(e,n){if(i[n])t.prototype[n]=a(e,n,r)})};var h=function(t,e){if(i.isFunction(t))return t;if(i.isObject(t)&&!e._isModel(t))return u(t);if(i.isString(t))return function(e){return e.get(t)};return t};var u=function(t){var e=i.matches(t);return function(t){return e(t.attributes)}};var l=e.Events={};var c=/\s+/;var f=function(t,e,r,n,s){var a=0,o;if(r&&typeof r==="object"){if(n!==void 0&&"context"in s&&s.context===void 0)s.context=n;for(o=i.keys(r);a<o.length;a++){e=f(t,e,o[a],r[o[a]],s)}}else if(r&&c.test(r)){for(o=r.split(c);a<o.length;a++){e=t(e,o[a],n,s)}}else{e=t(e,r,n,s)}return e};l.on=function(t,e,i){return d(this,t,e,i)};var d=function(t,e,i,r,n){t._events=f(v,t._events||{},e,i,{context:r,ctx:t,listening:n});if(n){var s=t._listeners||(t._listeners={});s[n.id]=n}return t};l.listenTo=function(t,e,r){if(!t)return this;var n=t._listenId||(t._listenId=i.uniqueId("l"));var s=this._listeningTo||(this._listeningTo={});var a=s[n];if(!a){var o=this._listenId||(this._listenId=i.uniqueId("l"));a=s[n]={obj:t,objId:n,id:o,listeningTo:s,count:0}}d(t,e,r,this,a);return this};var v=function(t,e,i,r){if(i){var n=t[e]||(t[e]=[]);var s=r.context,a=r.ctx,o=r.listening;if(o)o.count++;n.push({callback:i,context:s,ctx:s||a,listening:o})}return t};l.off=function(t,e,i){if(!this._events)return this;this._events=f(g,this._events,t,e,{context:i,listeners:this._listeners});return this};l.stopListening=function(t,e,r){var n=this._listeningTo;if(!n)return this;var s=t?[t._listenId]:i.keys(n);for(var a=0;a<s.length;a++){var o=n[s[a]];if(!o)break;o.obj.off(e,r,this)}if(i.isEmpty(n))this._listeningTo=void 0;return this};var g=function(t,e,r,n){if(!t)return;var s=0,a;var o=n.context,h=n.listeners;if(!e&&!r&&!o){var u=i.keys(h);for(;s<u.length;s++){a=h[u[s]];delete h[a.id];delete a.listeningTo[a.objId]}return}var l=e?[e]:i.keys(t);for(;s<l.length;s++){e=l[s];var c=t[e];if(!c)break;var f=[];for(var d=0;d<c.length;d++){var v=c[d];if(r&&r!==v.callback&&r!==v.callback._callback||o&&o!==v.context){f.push(v)}else{a=v.listening;if(a&&--a.count===0){delete h[a.id];delete a.listeningTo[a.objId]}}}if(f.length){t[e]=f}else{delete t[e]}}if(i.size(t))return t};l.once=function(t,e,r){var n=f(p,{},t,e,i.bind(this.off,this));return this.on(n,void 0,r)};l.listenToOnce=function(t,e,r){var n=f(p,{},e,r,i.bind(this.stopListening,this,t));return this.listenTo(t,n)};var p=function(t,e,r,n){if(r){var s=t[e]=i.once(function(){n(e,s);r.apply(this,arguments)});s._callback=r}return t};l.trigger=function(t){if(!this._events)return this;var e=Math.max(0,arguments.length-1);var i=Array(e);for(var r=0;r<e;r++)i[r]=arguments[r+1];f(m,this._events,t,void 0,i);return this};var m=function(t,e,i,r){if(t){var n=t[e];var s=t.all;if(n&&s)s=s.slice();if(n)_(n,r);if(s)_(s,[e].concat(r))}return t};var _=function(t,e){var i,r=-1,n=t.length,s=e[0],a=e[1],o=e[2];switch(e.length){case 0:while(++r<n)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<n)(i=t[r]).callback.call(i.ctx,s);return;case 2:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a);return;case 3:while(++r<n)(i=t[r]).callback.call(i.ctx,s,a,o);return;default:while(++r<n)(i=t[r]).callback.apply(i.ctx,e);return}};l.bind=l.on;l.unbind=l.off;i.extend(e,l);var y=e.Model=function(t,e){var r=t||{};e||(e={});this.cid=i.uniqueId(this.cidPrefix);this.attributes={};if(e.collection)this.collection=e.collection;if(e.parse)r=this.parse(r,e)||{};r=i.defaults({},r,i.result(this,"defaults"));this.set(r,e);this.changed={};this.initialize.apply(this,arguments)};i.extend(y.prototype,l,{changed:null,validationError:null,idAttribute:"id",cidPrefix:"c",initialize:function(){},toJSON:function(t){return i.clone(this.attributes)},sync:function(){return e.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return i.escape(this.get(t))},has:function(t){return this.get(t)!=null},matches:function(t){return!!i.iteratee(t,this)(this.attributes)},set:function(t,e,r){if(t==null)return this;var n;if(typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r||(r={});if(!this._validate(n,r))return false;var s=r.unset;var a=r.silent;var o=[];var h=this._changing;this._changing=true;if(!h){this._previousAttributes=i.clone(this.attributes);this.changed={}}var u=this.attributes;var l=this.changed;var c=this._previousAttributes;for(var f in n){e=n[f];if(!i.isEqual(u[f],e))o.push(f);if(!i.isEqual(c[f],e)){l[f]=e}else{delete l[f]}s?delete u[f]:u[f]=e}this.id=this.get(this.idAttribute);if(!a){if(o.length)this._pending=r;for(var d=0;d<o.length;d++){this.trigger("change:"+o[d],this,u[o[d]],r)}}if(h)return this;if(!a){while(this._pending){r=this._pending;this._pending=false;this.trigger("change",this,r)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,i.extend({},e,{unset:true}))},clear:function(t){var e={};for(var r in this.attributes)e[r]=void 0;return this.set(e,i.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!i.isEmpty(this.changed);return i.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?i.clone(this.changed):false;var e=this._changing?this._previousAttributes:this.attributes;var r={};for(var n in t){var s=t[n];if(i.isEqual(e[n],s))continue;r[n]=s}return i.size(r)?r:false},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(t){t=i.extend({parse:true},t);var e=this;var r=t.success;t.success=function(i){var n=t.parse?e.parse(i,t):i;if(!e.set(n,t))return false;if(r)r.call(t.context,e,i,t);e.trigger("sync",e,i,t)};z(this,t);return this.sync("read",this,t)},save:function(t,e,r){var n;if(t==null||typeof t==="object"){n=t;r=e}else{(n={})[t]=e}r=i.extend({validate:true,parse:true},r);var s=r.wait;if(n&&!s){if(!this.set(n,r))return false}else{if(!this._validate(n,r))return false}var a=this;var o=r.success;var h=this.attributes;r.success=function(t){a.attributes=h;var e=r.parse?a.parse(t,r):t;if(s)e=i.extend({},n,e);if(e&&!a.set(e,r))return false;if(o)o.call(r.context,a,t,r);a.trigger("sync",a,t,r)};z(this,r);if(n&&s)this.attributes=i.extend({},h,n);var u=this.isNew()?"create":r.patch?"patch":"update";if(u==="patch"&&!r.attrs)r.attrs=n;var l=this.sync(u,this,r);this.attributes=h;return l},destroy:function(t){t=t?i.clone(t):{};var e=this;var r=t.success;var n=t.wait;var s=function(){e.stopListening();e.trigger("destroy",e,e.collection,t)};t.success=function(i){if(n)s();if(r)r.call(t.context,e,i,t);if(!e.isNew())e.trigger("sync",e,i,t)};var a=false;if(this.isNew()){i.defer(t.success)}else{z(this,t);a=this.sync("delete",this,t)}if(!n)s();return a},url:function(){var t=i.result(this,"urlRoot")||i.result(this.collection,"url")||F();if(this.isNew())return t;var e=this.get(this.idAttribute);return t.replace(/[^\/]$/,"$&/")+encodeURIComponent(e)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(t){return this._validate({},i.defaults({validate:true},t))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=i.extend({},this.attributes,t);var r=this.validationError=this.validate(t,e)||null;if(!r)return true;this.trigger("invalid",this,r,i.extend(e,{validationError:r}));return false}});var b={keys:1,values:1,pairs:1,invert:1,pick:0,omit:0,chain:1,isEmpty:1};o(y,b,"attributes");var x=e.Collection=function(t,e){e||(e={});if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,i.extend({silent:true},e))};var w={add:true,remove:true,merge:true};var E={add:true,remove:false};var k=function(t,e,i){i=Math.min(Math.max(i,0),t.length);var r=Array(t.length-i);var n=e.length;for(var s=0;s<r.length;s++)r[s]=t[s+i];for(s=0;s<n;s++)t[s+i]=e[s];for(s=0;s<r.length;s++)t[s+n+i]=r[s]};i.extend(x.prototype,l,{model:y,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return e.sync.apply(this,arguments)},add:function(t,e){return this.set(t,i.extend({merge:false},e,E))},remove:function(t,e){e=i.extend({},e);var r=!i.isArray(t);t=r?[t]:i.clone(t);var n=this._removeModels(t,e);if(!e.silent&&n)this.trigger("update",this,e);return r?n[0]:n},set:function(t,e){if(t==null)return;e=i.defaults({},e,w);if(e.parse&&!this._isModel(t))t=this.parse(t,e);var r=!i.isArray(t);t=r?[t]:t.slice();var n=e.at;if(n!=null)n=+n;if(n<0)n+=this.length+1;var s=[];var a=[];var o=[];var h={};var u=e.add;var l=e.merge;var c=e.remove;var f=false;var d=this.comparator&&n==null&&e.sort!==false;var v=i.isString(this.comparator)?this.comparator:null;var g;for(var p=0;p<t.length;p++){g=t[p];var m=this.get(g);if(m){if(l&&g!==m){var _=this._isModel(g)?g.attributes:g;if(e.parse)_=m.parse(_,e);m.set(_,e);if(d&&!f)f=m.hasChanged(v)}if(!h[m.cid]){h[m.cid]=true;s.push(m)}t[p]=m}else if(u){g=t[p]=this._prepareModel(g,e);if(g){a.push(g);this._addReference(g,e);h[g.cid]=true;s.push(g)}}}if(c){for(p=0;p<this.length;p++){g=this.models[p];if(!h[g.cid])o.push(g)}if(o.length)this._removeModels(o,e)}var y=false;var b=!d&&u&&c;if(s.length&&b){y=this.length!=s.length||i.some(this.models,function(t,e){return t!==s[e]});this.models.length=0;k(this.models,s,0);this.length=this.models.length}else if(a.length){if(d)f=true;k(this.models,a,n==null?this.length:n);this.length=this.models.length}if(f)this.sort({silent:true});if(!e.silent){for(p=0;p<a.length;p++){if(n!=null)e.index=n+p;g=a[p];g.trigger("add",g,this,e)}if(f||y)this.trigger("sort",this,e);if(a.length||o.length)this.trigger("update",this,e)}return r?t[0]:t},reset:function(t,e){e=e?i.clone(e):{};for(var r=0;r<this.models.length;r++){this._removeReference(this.models[r],e)}e.previousModels=this.models;this._reset();t=this.add(t,i.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return t},push:function(t,e){return this.add(t,i.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);return this.remove(e,t)},unshift:function(t,e){return this.add(t,i.extend({at:0},e))},shift:function(t){var e=this.at(0);return this.remove(e,t)},slice:function(){return s.apply(this.models,arguments)},get:function(t){if(t==null)return void 0;var e=this.modelId(this._isModel(t)?t.attributes:t);return this._byId[t]||this._byId[e]||this._byId[t.cid]},at:function(t){if(t<0)t+=this.length;return this.models[t]},where:function(t,e){return this[e?"find":"filter"](t)},findWhere:function(t){return this.where(t,true)},sort:function(t){var e=this.comparator;if(!e)throw new Error("Cannot sort a set without a comparator");t||(t={});var r=e.length;if(i.isFunction(e))e=i.bind(e,this);if(r===1||i.isString(e)){this.models=this.sortBy(e)}else{this.models.sort(e)}if(!t.silent)this.trigger("sort",this,t);return this},pluck:function(t){return i.invoke(this.models,"get",t)},fetch:function(t){t=i.extend({parse:true},t);var e=t.success;var r=this;t.success=function(i){var n=t.reset?"reset":"set";r[n](i,t);if(e)e.call(t.context,r,i,t);r.trigger("sync",r,i,t)};z(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?i.clone(e):{};var r=e.wait;t=this._prepareModel(t,e);if(!t)return false;if(!r)this.add(t,e);var n=this;var s=e.success;e.success=function(t,e,i){if(r)n.add(t,i);if(s)s.call(i.context,t,e,i)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models,{model:this.model,comparator:this.comparator})},modelId:function(t){return t[this.model.prototype.idAttribute||"id"]},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(this._isModel(t)){if(!t.collection)t.collection=this;return t}e=e?i.clone(e):{};e.collection=this;var r=new this.model(t,e);if(!r.validationError)return r;this.trigger("invalid",this,r.validationError,e);return false},_removeModels:function(t,e){var i=[];for(var r=0;r<t.length;r++){var n=this.get(t[r]);if(!n)continue;var s=this.indexOf(n);this.models.splice(s,1);this.length--;if(!e.silent){e.index=s;n.trigger("remove",n,this,e)}i.push(n);this._removeReference(n,e)}return i.length?i:false},_isModel:function(t){return t instanceof y},_addReference:function(t,e){this._byId[t.cid]=t;var i=this.modelId(t.attributes);if(i!=null)this._byId[i]=t;t.on("all",this._onModelEvent,this)},_removeReference:function(t,e){delete this._byId[t.cid];var i=this.modelId(t.attributes);if(i!=null)delete this._byId[i];if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(t==="change"){var n=this.modelId(e.previousAttributes());var s=this.modelId(e.attributes);if(n!==s){if(n!=null)delete this._byId[n];if(s!=null)this._byId[s]=e}}this.trigger.apply(this,arguments)}});var S={forEach:3,each:3,map:3,collect:3,reduce:4,foldl:4,inject:4,reduceRight:4,foldr:4,find:3,detect:3,filter:3,select:3,reject:3,every:3,all:3,some:3,any:3,include:3,includes:3,contains:3,invoke:0,max:3,min:3,toArray:1,size:1,first:3,head:3,take:3,initial:3,rest:3,tail:3,drop:3,last:3,without:0,difference:0,indexOf:3,shuffle:1,lastIndexOf:3,isEmpty:1,chain:1,sample:3,partition:3,groupBy:3,countBy:3,sortBy:3,indexBy:3};o(x,S,"models");var I=e.View=function(t){this.cid=i.uniqueId("view");i.extend(this,i.pick(t,P));this._ensureElement();this.initialize.apply(this,arguments)};var T=/^(\S+)\s*(.*)$/;var P=["model","collection","el","id","attributes","className","tagName","events"];i.extend(I.prototype,l,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this._removeElement();this.stopListening();return this},_removeElement:function(){this.$el.remove()},setElement:function(t){this.undelegateEvents();this._setElement(t);this.delegateEvents();return this},_setElement:function(t){this.$el=t instanceof e.$?t:e.$(t);this.el=this.$el[0]},delegateEvents:function(t){t||(t=i.result(this,"events"));if(!t)return this;this.undelegateEvents();for(var e in t){var r=t[e];if(!i.isFunction(r))r=this[r];if(!r)continue;var n=e.match(T);this.delegate(n[1],n[2],i.bind(r,this))}return this},delegate:function(t,e,i){this.$el.on(t+".delegateEvents"+this.cid,e,i);return this},undelegateEvents:function(){if(this.$el)this.$el.off(".delegateEvents"+this.cid);return this},undelegate:function(t,e,i){this.$el.off(t+".delegateEvents"+this.cid,e,i);return this},_createElement:function(t){return document.createElement(t)},_ensureElement:function(){if(!this.el){var t=i.extend({},i.result(this,"attributes"));if(this.id)t.id=i.result(this,"id");if(this.className)t["class"]=i.result(this,"className");this.setElement(this._createElement(i.result(this,"tagName")));this._setAttributes(t)}else{this.setElement(i.result(this,"el"))}},_setAttributes:function(t){this.$el.attr(t)}});e.sync=function(t,r,n){var s=H[t];i.defaults(n||(n={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:s,dataType:"json"};if(!n.url){a.url=i.result(r,"url")||F()}if(n.data==null&&r&&(t==="create"||t==="update"||t==="patch")){a.contentType="application/json";a.data=JSON.stringify(n.attrs||r.toJSON(n))}if(n.emulateJSON){a.contentType="application/x-www-form-urlencoded";a.data=a.data?{model:a.data}:{}}if(n.emulateHTTP&&(s==="PUT"||s==="DELETE"||s==="PATCH")){a.type="POST";if(n.emulateJSON)a.data._method=s;var o=n.beforeSend;n.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",s);if(o)return o.apply(this,arguments)}}if(a.type!=="GET"&&!n.emulateJSON){a.processData=false}var h=n.error;n.error=function(t,e,i){n.textStatus=e;n.errorThrown=i;if(h)h.call(n.context,t,e,i)};var u=n.xhr=e.ajax(i.extend(a,n));r.trigger("request",r,u,n);return u};var H={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var $=e.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var A=/\((.*?)\)/g;var C=/(\(\?)?:\w+/g;var R=/\*\w+/g;var j=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend($.prototype,l,{initialize:function(){},route:function(t,r,n){if(!i.isRegExp(t))t=this._routeToRegExp(t);if(i.isFunction(r)){n=r;r=""}if(!n)n=this[r];var s=this;e.history.route(t,function(i){var a=s._extractParameters(t,i);if(s.execute(n,a,r)!==false){s.trigger.apply(s,["route:"+r].concat(a));s.trigger("route",r,a);e.history.trigger("route",s,r,a)}});return this},execute:function(t,e,i){if(t)t.apply(this,e)},navigate:function(t,i){e.history.navigate(t,i);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=i.result(this,"routes");var t,e=i.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(j,"\\$&").replace(A,"(?:$1)?").replace(C,function(t,e){return e?t:"([^/?]+)"}).replace(R,"([^?]*?)");return new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var r=t.exec(e).slice(1);return i.map(r,function(t,e){if(e===r.length-1)return t||null;return t?decodeURIComponent(t):null})}});var M=e.History=function(){this.handlers=[];this.checkUrl=i.bind(this.checkUrl,this);if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var N=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var U=/#.*$/;M.started=false;i.extend(M.prototype,l,{interval:50,atRoot:function(){var t=this.location.pathname.replace(/[^\/]$/,"$&/");return t===this.root&&!this.getSearch()},matchRoot:function(){var t=this.decodeFragment(this.location.pathname);var e=t.slice(0,this.root.length-1)+"/";return e===this.root},decodeFragment:function(t){return decodeURI(t.replace(/%25/g,"%2525"))},getSearch:function(){var t=this.location.href.replace(/#.*/,"").match(/\?.+/);return t?t[0]:""},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getPath:function(){var t=this.decodeFragment(this.location.pathname+this.getSearch()).slice(this.root.length-1);return t.charAt(0)==="/"?t.slice(1):t},getFragment:function(t){if(t==null){if(this._usePushState||!this._wantsHashChange){t=this.getPath()}else{t=this.getHash()}}return t.replace(N,"")},start:function(t){if(M.started)throw new Error("Backbone.history has already been started");M.started=true;this.options=i.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._hasHashChange="onhashchange"in window&&(document.documentMode===void 0||document.documentMode>7);this._useHashChange=this._wantsHashChange&&this._hasHashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.history&&this.history.pushState);this._usePushState=this._wantsPushState&&this._hasPushState;this.fragment=this.getFragment();this.root=("/"+this.root+"/").replace(O,"/");if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||"/";this.location.replace(e+"#"+this.getPath());return true}else if(this._hasPushState&&this.atRoot()){this.navigate(this.getHash(),{replace:true})}}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe");this.iframe.src="javascript:0";this.iframe.style.display="none";this.iframe.tabIndex=-1;var r=document.body;var n=r.insertBefore(this.iframe,r.firstChild).contentWindow;n.document.open();n.document.close();n.location.hash="#"+this.fragment}var s=window.addEventListener||function(t,e){return attachEvent("on"+t,e)};if(this._usePushState){s("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){s("hashchange",this.checkUrl,false)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}if(!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent("on"+t,e)};if(this._usePushState){t("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){t("hashchange",this.checkUrl,false)}if(this.iframe){document.body.removeChild(this.iframe);this.iframe=null}if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);M.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getHash(this.iframe.contentWindow)}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){if(!this.matchRoot())return false;t=this.fragment=this.getFragment(t);return i.some(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!M.started)return false;if(!e||e===true)e={trigger:!!e};t=this.getFragment(t||"");var i=this.root;if(t===""||t.charAt(0)==="?"){i=i.slice(0,-1)||"/"}var r=i+t;t=this.decodeFragment(t.replace(U,""));if(this.fragment===t)return;this.fragment=t;if(this._usePushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,r)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;if(!e.replace){n.document.open();n.document.close()}this._updateHash(n.location,t,e.replace)}}else{return this.location.assign(r)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new M;var q=function(t,e){var r=this;var n;if(t&&i.has(t,"constructor")){n=t.constructor}else{n=function(){return r.apply(this,arguments)}}i.extend(n,r,e);var s=function(){this.constructor=n};s.prototype=r.prototype;n.prototype=new s;if(t)i.extend(n.prototype,t);n.__super__=r.prototype;return n};y.extend=x.extend=$.extend=I.extend=M.extend=q;var F=function(){throw new Error('A "url" property or function must be specified')};var z=function(t,e){var i=e.error;e.error=function(r){if(i)i.call(e.context,t,r,e);t.trigger("error",t,r,e)}};return e});
/*!
* jQuery Once v2.1.1 - http://github.com/robloach/jquery-once
* @license MIT, GPL-2.0
* http://opensource.org/licenses/MIT
* http://opensource.org/licenses/GPL-2.0
*/
(function(e){"use strict";if(typeof exports==="object"){e(require("jquery"))}else if(typeof define==="function"&&define.amd){define(["jquery"],e)}else{e(jQuery)}})(function(e){"use strict";var n=function(e){e=e||"once";if(typeof e!=="string"){throw new Error("The jQuery Once id parameter must be a string")}return e};e.fn.once=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)!==true}).data(r,true)};e.fn.removeOnce=function(e){return this.findOnce(e).removeData("jquery-once-"+n(e))};e.fn.findOnce=function(t){var r="jquery-once-"+n(t);return this.filter(function(){return e(this).data(r)===true})}});
/**
* @file
* Parse inline JSON and initialize the drupalSettings global object.
*/
(function () {
'use strict';
var settingsElement = document.querySelector('script[type="application/json"][data-drupal-selector="drupal-settings-json"]');
/**
* Variable generated by Drupal with all the configuration created from PHP.
*
* @global
*
* @type {object}
*/
window.drupalSettings = {};
if (settingsElement !== null) {
window.drupalSettings = JSON.parse(settingsElement.textContent);
}
})();
;
/**
* @file
* Defines the Drupal JavaScript API.
*/
/**
* A jQuery object, typically the return value from a `$(selector)` call.
*
* Holds an HTMLElement or a collection of HTMLElements.
*
* @typedef {object} jQuery
*
* @prop {number} length=0
* Number of elements contained in the jQuery object.
*/
/**
* Variable generated by Drupal that holds all translated strings from PHP.
*
* Content of this variable is automatically created by Drupal when using the
* Interface Translation module. It holds the translation of strings used on
* the page.
*
* This variable is used to pass data from the backend to the frontend. Data
* contained in `drupalSettings` is used during behavior initialization.
*
* @global
*
* @var {object} drupalTranslations
*/
/**
* Global Drupal object.
*
* All Drupal JavaScript APIs are contained in this namespace.
*
* @global
*
* @namespace
*/
window.Drupal = {behaviors: {}, locale: {}};
// Class indicating that JavaScript is enabled; used for styling purpose.
document.documentElement.className += ' js';
// Allow other JavaScript libraries to use $.
if (window.jQuery) {
jQuery.noConflict();
}
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it in an anonymous closure.
(function (domready, Drupal, drupalSettings, drupalTranslations) {
'use strict';
/**
* Helper to rethrow errors asynchronously.
*
* This way Errors bubbles up outside of the original callstack, making it
* easier to debug errors in the browser.
*
* @param {Error|string} error
* The error to be thrown.
*/
Drupal.throwError = function (error) {
setTimeout(function () { throw error; }, 0);
};
/**
* Custom error thrown after attach/detach if one or more behaviors failed.
* Initializes the JavaScript behaviors for page loads and Ajax requests.
*
* @callback Drupal~behaviorAttach
*
* @param {HTMLDocument|HTMLElement} context
* An element to detach behaviors from.
* @param {?object} settings
* An object containing settings for the current context. It is rarely used.
*
* @see Drupal.attachBehaviors
*/
/**
* Reverts and cleans up JavaScript behavior initialization.
*
* @callback Drupal~behaviorDetach
*
* @param {HTMLDocument|HTMLElement} context
* An element to attach behaviors to.
* @param {object} settings
* An object containing settings for the current context.
* @param {string} trigger
* One of `'unload'`, `'move'`, or `'serialize'`.
*
* @see Drupal.detachBehaviors
*/
/**
* @typedef {object} Drupal~behavior
*
* @prop {Drupal~behaviorAttach} attach
* Function run on page load and after an Ajax call.
* @prop {Drupal~behaviorDetach} detach
* Function run when content is serialized or removed from the page.
*/
/**
* Holds all initialization methods.
*
* @namespace Drupal.behaviors
*
* @type {Object.<string, Drupal~behavior>}
*/
/**
* Defines a behavior to be run during attach and detach phases.
*
* Attaches all registered behaviors to a page element.
*
* Behaviors are event-triggered actions that attach to page elements,
* enhancing default non-JavaScript UIs. Behaviors are registered in the
* {@link Drupal.behaviors} object using the method 'attach' and optionally
* also 'detach'.
*
* {@link Drupal.attachBehaviors} is added below to the `jQuery.ready` event
* and therefore runs on initial page load. Developers implementing Ajax in
* their solutions should also call this function after new page content has
* been loaded, feeding in an element to be processed, in order to attach all
* behaviors to the new content.
*
* Behaviors should use `var elements =
* $(context).find(selector).once('behavior-name');` to ensure the behavior is
* attached only once to a given element. (Doing so enables the reprocessing
* of given elements, which may be needed on occasion despite the ability to
* limit behavior attachment to a particular element.)
*
* @example
* Drupal.behaviors.behaviorName = {
* attach: function (context, settings) {
* // ...
* },
* detach: function (context, settings, trigger) {
* // ...
* }
* };
*
* @param {HTMLDocument|HTMLElement} [context=document]
* An element to attach behaviors to.
* @param {object} [settings=drupalSettings]
* An object containing settings for the current context. If none is given,
* the global {@link drupalSettings} object is used.
*
* @see Drupal~behaviorAttach
* @see Drupal.detachBehaviors
*
* @throws {Drupal~DrupalBehaviorError}
*/
Drupal.attachBehaviors = function (context, settings) {
context = context || document;
settings = settings || drupalSettings;
var behaviors = Drupal.behaviors;
// Execute all of them.
for (var i in behaviors) {
if (behaviors.hasOwnProperty(i) && typeof behaviors[i].attach === 'function') {
// Don't stop the execution of behaviors in case of an error.
try {
behaviors[i].attach(context, settings);
}
catch (e) {
Drupal.throwError(e);
}
}
}
};
// Attach all behaviors.
domready(function () { Drupal.attachBehaviors(document, drupalSettings); });
/**
* Detaches registered behaviors from a page element.
*
* Developers implementing Ajax in their solutions should call this function
* before page content is about to be removed, feeding in an element to be
* processed, in order to allow special behaviors to detach from the content.
*
* Such implementations should use `.findOnce()` and `.removeOnce()` to find
* elements with their corresponding `Drupal.behaviors.behaviorName.attach`
* implementation, i.e. `.removeOnce('behaviorName')`, to ensure the behavior
* is detached only from previously processed elements.
*
* @param {HTMLDocument|HTMLElement} [context=document]
* An element to detach behaviors from.
* @param {object} [settings=drupalSettings]
* An object containing settings for the current context. If none given,
* the global {@link drupalSettings} object is used.
* @param {string} [trigger='unload']
* A string containing what's causing the behaviors to be detached. The
* possible triggers are:
* - `'unload'`: The context element is being removed from the DOM.
* - `'move'`: The element is about to be moved within the DOM (for example,
* during a tabledrag row swap). After the move is completed,
* {@link Drupal.attachBehaviors} is called, so that the behavior can undo
* whatever it did in response to the move. Many behaviors won't need to
* do anything simply in response to the element being moved, but because
* IFRAME elements reload their "src" when being moved within the DOM,
* behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
* take some action.
* - `'serialize'`: When an Ajax form is submitted, this is called with the
* form as the context. This provides every behavior within the form an
* opportunity to ensure that the field elements have correct content
* in them before the form is serialized. The canonical use-case is so
* that WYSIWYG editors can update the hidden textarea to which they are
* bound.
*
* @throws {Drupal~DrupalBehaviorError}
*
* @see Drupal~behaviorDetach
* @see Drupal.attachBehaviors
*/
Drupal.detachBehaviors = function (context, settings, trigger) {
context = context || document;
settings = settings || drupalSettings;
trigger = trigger || 'unload';
var behaviors = Drupal.behaviors;
// Execute all of them.
for (var i in behaviors) {
if (behaviors.hasOwnProperty(i) && typeof behaviors[i].detach === 'function') {
// Don't stop the execution of behaviors in case of an error.
try {
behaviors[i].detach(context, settings, trigger);
}
catch (e) {
Drupal.throwError(e);
}
}
}
};
/**
* Encodes special characters in a plain-text string for display as HTML.
*
* @param {string} str
* The string to be encoded.
*
* @return {string}
* The encoded string.
*
* @ingroup sanitization
*/
Drupal.checkPlain = function (str) {
str = str.toString()
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
return str;
};
/**
* Replaces placeholders with sanitized values in a string.
*
* @param {string} str
* A string with placeholders.
* @param {object} args
* An object of replacements pairs to make. Incidences of any key in this
* array are replaced with the corresponding value. Based on the first
* character of the key, the value is escaped and/or themed:
* - `'!variable'`: inserted as is.
* - `'@variable'`: escape plain text to HTML ({@link Drupal.checkPlain}).
* - `'%variable'`: escape text and theme as a placeholder for user-
* submitted content ({@link Drupal.checkPlain} +
* `{@link Drupal.theme}('placeholder')`).
*
* @return {string}
*
* @see Drupal.t
*/
Drupal.formatString = function (str, args) {
// Keep args intact.
var processedArgs = {};
// Transform arguments before inserting them.
for (var key in args) {
if (args.hasOwnProperty(key)) {
switch (key.charAt(0)) {
// Escaped only.
case '@':
processedArgs[key] = Drupal.checkPlain(args[key]);
break;
// Pass-through.
case '!':
processedArgs[key] = args[key];
break;
// Escaped and placeholder.
default:
processedArgs[key] = Drupal.theme('placeholder', args[key]);
break;
}
}
}
return Drupal.stringReplace(str, processedArgs, null);
};
/**
* Replaces substring.
*
* The longest keys will be tried first. Once a substring has been replaced,
* its new value will not be searched again.
*
* @param {string} str
* A string with placeholders.
* @param {object} args
* Key-value pairs.
* @param {Array|null} keys
* Array of keys from `args`. Internal use only.
*
* @return {string}
* The replaced string.
*/
Drupal.stringReplace = function (str, args, keys) {
if (str.length === 0) {
return str;
}
// If the array of keys is not passed then collect the keys from the args.
if (!Array.isArray(keys)) {
keys = [];
for (var k in args) {
if (args.hasOwnProperty(k)) {
keys.push(k);
}
}
// Order the keys by the character length. The shortest one is the first.
keys.sort(function (a, b) { return a.length - b.length; });
}
if (keys.length === 0) {
return str;
}
// Take next longest one from the end.
var key = keys.pop();
var fragments = str.split(key);
if (keys.length) {
for (var i = 0; i < fragments.length; i++) {
// Process each fragment with a copy of remaining keys.
fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
}
}
return fragments.join(args[key]);
};
/**
* Translates strings to the page language, or a given language.
*
* See the documentation of the server-side t() function for further details.
*
* @param {string} str
* A string containing the English text to translate.
* @param {Object.<string, string>} [args]
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See {@link Drupal.formatString}.
* @param {object} [options]
* Additional options for translation.
* @param {string} [options.context='']
* The context the source string belongs to.
*
* @return {string}
* The formatted string.
* The translated string.
*/
Drupal.t = function (str, args, options) {
options = options || {};
options.context = options.context || '';
// Fetch the localized version of the string.
if (typeof drupalTranslations !== 'undefined' && drupalTranslations.strings && drupalTranslations.strings[options.context] && drupalTranslations.strings[options.context][str]) {
str = drupalTranslations.strings[options.context][str];
}
if (args) {
str = Drupal.formatString(str, args);
}
return str;
};
/**
* Returns the URL to a Drupal page.
*
* @param {string} path
* Drupal path to transform to URL.
*
* @return {string}
* The full URL.
*/
Drupal.url = function (path) {
return drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix + path;
};
/**
* Returns the passed in URL as an absolute URL.
*
* @param {string} url
* The URL string to be normalized to an absolute URL.
*
* @return {string}
* The normalized, absolute URL.
*
* @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
* @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
* @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
*/
Drupal.url.toAbsolute = function (url) {
var urlParsingNode = document.createElement('a');
// Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
// strings may throw an exception.
try {
url = decodeURIComponent(url);
}
catch (e) {
// Empty.
}
urlParsingNode.setAttribute('href', url);
// IE <= 7 normalizes the URL when assigned to the anchor node similar to
// the other browsers.
return urlParsingNode.cloneNode(false).href;
};
/**
* Returns true if the URL is within Drupal's base path.
*
* @param {string} url
* The URL string to be tested.
*
* @return {bool}
* `true` if local.
*
* @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
*/
Drupal.url.isLocal = function (url) {
// Always use browser-derived absolute URLs in the comparison, to avoid
// attempts to break out of the base path using directory traversal.
var absoluteUrl = Drupal.url.toAbsolute(url);
var protocol = location.protocol;
// Consider URLs that match this site's base URL but use HTTPS instead of HTTP
// as local as well.
if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
protocol = 'https:';
}
var baseUrl = protocol + '//' + location.host + drupalSettings.path.baseUrl.slice(0, -1);
// Decoding non-UTF-8 strings may throw an exception.
try {
absoluteUrl = decodeURIComponent(absoluteUrl);
}
catch (e) {
// Empty.
}
try {
baseUrl = decodeURIComponent(baseUrl);
}
catch (e) {
// Empty.
}
// The given URL matches the site's base URL, or has a path under the site's
// base URL.
return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
};
/**
* Formats a string containing a count of items.
*
* This function ensures that the string is pluralized correctly. Since
* {@link Drupal.t} is called by this function, make sure not to pass
* already-localized strings to it.
*
* See the documentation of the server-side
* \Drupal\Core\StringTranslation\TranslationInterface::formatPlural()
* function for more details.
*
* @param {number} count
* The item count to display.
* @param {string} singular
* The string for the singular case. Please make sure it is clear this is
* singular, to ease translation (e.g. use "1 new comment" instead of "1
* new"). Do not use @count in the singular string.
* @param {string} plural
* The string for the plural case. Please make sure it is clear this is
* plural, to ease translation. Use @count in place of the item count, as in
* "@count new comments".
* @param {object} [args]
* An object of replacements pairs to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* See {@link Drupal.formatString}.
* Note that you do not need to include @count in this array.
* This replacement is done automatically for the plural case.
* @param {object} [options]
* The options to pass to the {@link Drupal.t} function.
*
* @return {string}
* A translated string.
*/
Drupal.formatPlural = function (count, singular, plural, args, options) {
args = args || {};
args['@count'] = count;
var pluralDelimiter = drupalSettings.pluralDelimiter;
var translations = Drupal.t(singular + pluralDelimiter + plural, args, options).split(pluralDelimiter);
var index = 0;
// Determine the index of the plural form.
if (typeof drupalTranslations !== 'undefined' && drupalTranslations.pluralFormula) {
index = count in drupalTranslations.pluralFormula ? drupalTranslations.pluralFormula[count] : drupalTranslations.pluralFormula['default'];
}
else if (args['@count'] !== 1) {
index = 1;
}
return translations[index];
};
/**
* Encodes a Drupal path for use in a URL.
*
* For aesthetic reasons slashes are not escaped.
*
* @param {string} item
* Unencoded path.
*
* @return {string}
* The encoded path.
*/
Drupal.encodePath = function (item) {
return window.encodeURIComponent(item).replace(/%2F/g, '/');
};
/**
* Generates the themed representation of a Drupal object.
*
* All requests for themed output must go through this function. It examines
* the request and routes it to the appropriate theme function. If the current
* theme does not provide an override function, the generic theme function is
* called.
*
* @example
* <caption>To retrieve the HTML for text that should be emphasized and
* displayed as a placeholder inside a sentence.</caption>
* Drupal.theme('placeholder', text);
*
* @namespace
*
* @param {function} func
* The name of the theme function to call.
* @param {...args}
* Additional arguments to pass along to the theme function.
*
* @return {string|object|HTMLElement|jQuery}
* Any data the theme function returns. This could be a plain HTML string,
* but also a complex object.
*/
Drupal.theme = function (func) {
var args = Array.prototype.slice.apply(arguments, [1]);
if (func in Drupal.theme) {
return Drupal.theme[func].apply(this, args);
}
};
/**
* Formats text for emphasized display in a placeholder inside a sentence.
*
* @param {string} str
* The text to format (plain-text).
*
* @return {string}
* The formatted text (html).
*/
Drupal.theme.placeholder = function (str) {
return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
};
})(domready, Drupal, window.drupalSettings, window.drupalTranslations);
;
/*!
* jQuery UI Core 1.11.4
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,r){var i,s,o,u=t.nodeName.toLowerCase();return"area"===u?(i=t.parentNode,s=i.name,!t.href||!s||i.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap='#"+s+"']")[0],!!o&&n(o))):(/^(input|select|textarea|button|object)$/.test(u)?!t.disabled:"a"===u?t.href||r:r)&&n(t)}function n(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return e.css(this,"visibility")==="hidden"}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var n=this.css("position"),r=n==="absolute",i=t?/(auto|scroll|hidden)/:/(auto|scroll)/,s=this.parents().filter(function(){var t=e(this);return r&&t.css("position")==="static"?!1:i.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return n==="fixed"||!s.length?e(this[0].ownerDocument||document):s},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(n){return t(n,!isNaN(e.attr(n,"tabindex")))},tabbable:function(n){var r=e.attr(n,"tabindex"),i=isNaN(r);return(i||r>=0)&&t(n,!i)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,n){function o(t,n,i,s){return e.each(r,function(){n-=parseFloat(e.css(t,"padding"+this))||0,i&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var r=n==="Width"?["Left","Right"]:["Top","Bottom"],i=n.toLowerCase(),s={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+n]=function(t){return t===undefined?s["inner"+n].call(this):this.each(function(){e(this).css(i,o(this,t)+"px")})},e.fn["outer"+n]=function(t,r){return typeof t!="number"?s["outer"+n].call(this,t):this.each(function(){e(this).css(i,o(this,t,!0,r)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(n,r){return typeof n=="number"?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(t!==undefined)return this.css("zIndex",t);if(this.length){var n=e(this[0]),r,i;while(n.length&&n[0]!==document){r=n.css("position");if(r==="absolute"||r==="relative"||r==="fixed"){i=parseInt(n.css("zIndex"),10);if(!isNaN(i)&&i!==0)return i}n=n.parent()}}return 0}}),e.ui.plugin={add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n,r){var i,s=e.plugins[t];if(!s)return;if(!r&&(!e.element[0].parentNode||e.element[0].parentNode.nodeType===11))return;for(i=0;i<s.length;i++)e.options[s[i][0]]&&s[i][1].apply(e.element,n)}}});;
/**
* @file
* Attaches behaviors for the Contextual module.
*/
(function ($, Drupal, drupalSettings, _, Backbone, JSON, storage) {
'use strict';
var options = $.extend(drupalSettings.contextual,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
open: Drupal.t('Open'),
close: Drupal.t('Close')
}
}
);
// Clear the cached contextual links whenever the current user's set of
// permissions changes.
var cachedPermissionsHash = storage.getItem('Drupal.contextual.permissionsHash');
var permissionsHash = drupalSettings.user.permissionsHash;
if (cachedPermissionsHash !== permissionsHash) {
if (typeof permissionsHash === 'string') {
_.chain(storage).keys().each(function (key) {
if (key.substring(0, 18) === 'Drupal.contextual.') {
storage.removeItem(key);
}
});
}
storage.setItem('Drupal.contextual.permissionsHash', permissionsHash);
}
/**
* Initializes a contextual link: updates its DOM, sets up model and views.
*
* @param {jQuery} $contextual
* A contextual links placeholder DOM element, containing the actual
* contextual links as rendered by the server.
* @param {string} html
* The server-side rendered HTML for this contextual link.
*/
function initContextual($contextual, html) {
var $region = $contextual.closest('.contextual-region');
var contextual = Drupal.contextual;
$contextual
// Update the placeholder to contain its rendered contextual links.
.html(html)
// Use the placeholder as a wrapper with a specific class to provide
// positioning and behavior attachment context.
.addClass('contextual')
// Ensure a trigger element exists before the actual contextual links.
.prepend(Drupal.theme('contextualTrigger'));
// Set the destination parameter on each of the contextual links.
var destination = 'destination=' + Drupal.encodePath(drupalSettings.path.currentPath);
$contextual.find('.contextual-links a').each(function () {
var url = this.getAttribute('href');
var glue = (url.indexOf('?') === -1) ? '?' : '&';
this.setAttribute('href', url + glue + destination);
});
// Create a model and the appropriate views.
var model = new contextual.StateModel({
title: $region.find('h2').eq(0).text().trim()
});
var viewOptions = $.extend({el: $contextual, model: model}, options);
contextual.views.push({
visual: new contextual.VisualView(viewOptions),
aural: new contextual.AuralView(viewOptions),
keyboard: new contextual.KeyboardView(viewOptions)
});
contextual.regionViews.push(new contextual.RegionView(
$.extend({el: $region, model: model}, options))
);
// Add the model to the collection. This must happen after the views have
// been associated with it, otherwise collection change event handlers can't
// trigger the model change event handler in its views.
contextual.collection.add(model);
// Let other JavaScript react to the adding of a new contextual link.
$(document).trigger('drupalContextualLinkAdded', {
$el: $contextual,
$region: $region,
model: model
});
// Fix visual collisions between contextual link triggers.
adjustIfNestedAndOverlapping($contextual);
}
/**
* Determines if a contextual link is nested & overlapping, if so: adjusts it.
*
* This only deals with two levels of nesting; deeper levels are not touched.
*
* @param {jQuery} $contextual
* A contextual links placeholder DOM element, containing the actual
* contextual links as rendered by the server.
*/
function adjustIfNestedAndOverlapping($contextual) {
var $contextuals = $contextual
// @todo confirm that .closest() is not sufficient
.parents('.contextual-region').eq(-1)
.find('.contextual');
// Early-return when there's no nesting.
if ($contextuals.length === 1) {
return;
}
// If the two contextual links overlap, then we move the second one.
var firstTop = $contextuals.eq(0).offset().top;
var secondTop = $contextuals.eq(1).offset().top;
if (firstTop === secondTop) {
var $nestedContextual = $contextuals.eq(1);
// Retrieve height of nested contextual link.
var height = 0;
var $trigger = $nestedContextual.find('.trigger');
// Elements with the .visually-hidden class have no dimensions, so this
// class must be temporarily removed to the calculate the height.
$trigger.removeClass('visually-hidden');
height = $nestedContextual.height();
$trigger.addClass('visually-hidden');
// Adjust nested contextual link's position.
$nestedContextual.css({top: $nestedContextual.position().top + height});
}
}
/**
* Attaches outline behavior for regions associated with contextual links.
*
* Events
* Contextual triggers an event that can be used by other scripts.
* - drupalContextualLinkAdded: Triggered when a contextual link is added.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the outline behavior to the right context.
*/
Drupal.behaviors.contextual = {
attach: function (context) {
var $context = $(context);
// Find all contextual links placeholders, if any.
var $placeholders = $context.find('[data-contextual-id]').once('contextual-render');
if ($placeholders.length === 0) {
return;
}
// Collect the IDs for all contextual links placeholders.
var ids = [];
$placeholders.each(function () {
ids.push($(this).attr('data-contextual-id'));
});
// Update all contextual links placeholders whose HTML is cached.
var uncachedIDs = _.filter(ids, function initIfCached(contextualID) {
var html = storage.getItem('Drupal.contextual.' + contextualID);
if (html !== null) {
// Initialize after the current execution cycle, to make the AJAX
// request for retrieving the uncached contextual links as soon as
// possible, but also to ensure that other Drupal behaviors have had
// the chance to set up an event listener on the Backbone collection
// Drupal.contextual.collection.
window.setTimeout(function () {
initContextual($context.find('[data-contextual-id="' + contextualID + '"]'), html);
});
return false;
}
return true;
});
// Perform an AJAX request to let the server render the contextual links
// for each of the placeholders.
if (uncachedIDs.length > 0) {
$.ajax({
url: Drupal.url('contextual/render'),
type: 'POST',
data: {'ids[]': uncachedIDs},
dataType: 'json',
success: function (results) {
_.each(results, function (html, contextualID) {
// Store the metadata.
storage.setItem('Drupal.contextual.' + contextualID, html);
// If the rendered contextual links are empty, then the current
// user does not have permission to access the associated links:
// don't render anything.
if (html.length > 0) {
// Update the placeholders to contain its rendered contextual
// links. Usually there will only be one placeholder, but it's
// possible for multiple identical placeholders exist on the
// page (probably because the same content appears more than
// once).
$placeholders = $context.find('[data-contextual-id="' + contextualID + '"]');
// Initialize the contextual links.
for (var i = 0; i < $placeholders.length; i++) {
initContextual($placeholders.eq(i), html);
}
}
});
}
});
}
}
};
/**
* Namespace for contextual related functionality.
*
* @namespace
*/
Drupal.contextual = {
/**
* The {@link Drupal.contextual.View} instances associated with each list
* element of contextual links.
*
* @type {Array}
*/
views: [],
/**
* The {@link Drupal.contextual.RegionView} instances associated with each
* contextual region element.
*
* @type {Array}
*/
regionViews: []
};
/**
* A Backbone.Collection of {@link Drupal.contextual.StateModel} instances.
*
* @type {Backbone.Collection}
*/
Drupal.contextual.collection = new Backbone.Collection([], {model: Drupal.contextual.StateModel});
/**
* A trigger is an interactive element often bound to a click handler.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.contextualTrigger = function () {
return '<button class="trigger visually-hidden focusable" type="button"></button>';
};
})(jQuery, Drupal, drupalSettings, _, Backbone, window.JSON, window.sessionStorage);
;
/**
* @file
* A Backbone Model for the state of a contextual link's trigger, list & region.
*/
(function (Drupal, Backbone) {
'use strict';
/**
* Models the state of a contextual link's trigger, list & region.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.contextual.StateModel = Backbone.Model.extend(/** @lends Drupal.contextual.StateModel# */{
/**
* @type {object}
*
* @prop {string} title
* @prop {bool} regionIsHovered
* @prop {bool} hasFocus
* @prop {bool} isOpen
* @prop {bool} isLocked
*/
defaults: /** @lends Drupal.contextual.StateModel# */{
/**
* The title of the entity to which these contextual links apply.
*
* @type {string}
*/
title: '',
/**
* Represents if the contextual region is being hovered.
*
* @type {bool}
*/
regionIsHovered: false,
/**
* Represents if the contextual trigger or options have focus.
*
* @type {bool}
*/
hasFocus: false,
/**
* Represents if the contextual options for an entity are available to
* be selected (i.e. whether the list of options is visible).
*
* @type {bool}
*/
isOpen: false,
/**
* When the model is locked, the trigger remains active.
*
* @type {bool}
*/
isLocked: false
},
/**
* Opens or closes the contextual link.
*
* If it is opened, then also give focus.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
toggleOpen: function () {
var newIsOpen = !this.get('isOpen');
this.set('isOpen', newIsOpen);
if (newIsOpen) {
this.focus();
}
return this;
},
/**
* Closes this contextual link.
*
* Does not call blur() because we want to allow a contextual link to have
* focus, yet be closed for example when hovering.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
close: function () {
this.set('isOpen', false);
return this;
},
/**
* Gives focus to this contextual link.
*
* Also closes + removes focus from every other contextual link.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
focus: function () {
this.set('hasFocus', true);
var cid = this.cid;
this.collection.each(function (model) {
if (model.cid !== cid) {
model.close().blur();
}
});
return this;
},
/**
* Removes focus from this contextual link, unless it is open.
*
* @return {Drupal.contextual.StateModel}
* The current contextual state model.
*/
blur: function () {
if (!this.get('isOpen')) {
this.set('hasFocus', false);
}
return this;
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides the aural view of a contextual link.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextual.AuralView = Backbone.View.extend(/** @lends Drupal.contextual.AuralView# */{
/**
* Renders the aural view of a contextual link (i.e. screen reader support).
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
*/
initialize: function (options) {
this.options = options;
this.listenTo(this.model, 'change', this.render);
// Use aria-role form so that the number of items in the list is spoken.
this.$el.attr('role', 'form');
// Initial render.
this.render();
},
/**
* @inheritdoc
*/
render: function () {
var isOpen = this.model.get('isOpen');
// Set the hidden property of the links.
this.$el.find('.contextual-links')
.prop('hidden', !isOpen);
// Update the view of the trigger.
this.$el.find('.trigger')
.text(Drupal.t('@action @title configuration options', {
'@action': (!isOpen) ? this.options.strings.open : this.options.strings.close,
'@title': this.model.get('title')
}))
.attr('aria-pressed', isOpen);
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides keyboard interaction for a contextual link.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextual.KeyboardView = Backbone.View.extend(/** @lends Drupal.contextual.KeyboardView# */{
/**
* @type {object}
*/
events: {
'focus .trigger': 'focus',
'focus .contextual-links a': 'focus',
'blur .trigger': function () { this.model.blur(); },
'blur .contextual-links a': function () {
// Set up a timeout to allow a user to tab between the trigger and the
// contextual links without the menu dismissing.
var that = this;
this.timer = window.setTimeout(function () {
that.model.close().blur();
}, 150);
}
},
/**
* Provides keyboard interaction for a contextual link.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
/**
* The timer is used to create a delay before dismissing the contextual
* links on blur. This is only necessary when keyboard users tab into
* contextual links without edit mode (i.e. without TabbingManager).
* That means that if we decide to disable tabbing of contextual links
* without edit mode, all this timer logic can go away.
*
* @type {NaN|number}
*/
this.timer = NaN;
},
/**
* Sets focus on the model; Clears the timer that dismisses the links.
*/
focus: function () {
// Clear the timeout that might have been set by blurring a link.
window.clearTimeout(this.timer);
this.model.focus();
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that renders the visual view of a contextual region element.
*/
(function (Drupal, Backbone, Modernizr) {
'use strict';
Drupal.contextual.RegionView = Backbone.View.extend(/** @lends Drupal.contextual.RegionView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
var mapping = {
mouseenter: function () { this.model.set('regionIsHovered', true); },
mouseleave: function () {
this.model.close().blur().set('regionIsHovered', false);
}
};
// We don't want mouse hover events on touch.
if (Modernizr.touchevents) {
mapping = {};
}
return mapping;
},
/**
* Renders the visual view of a contextual region element.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:hasFocus', this.render);
},
/**
* @inheritdoc
*
* @return {Drupal.contextual.RegionView}
* The current contextual region view.
*/
render: function () {
this.$el.toggleClass('focus', this.model.get('hasFocus'));
return this;
}
});
})(Drupal, Backbone, Modernizr);
;
/**
* @file
* A Backbone View that provides the visual view of a contextual link.
*/
(function (Drupal, Backbone, Modernizr) {
'use strict';
Drupal.contextual.VisualView = Backbone.View.extend(/** @lends Drupal.contextual.VisualView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
var mapping = {
'click .trigger': function () { this.model.toggleOpen(); },
'touchend .trigger': touchEndToClick,
'click .contextual-links a': function () { this.model.close().blur(); },
'touchend .contextual-links a': touchEndToClick
};
// We only want mouse hover events on non-touch.
if (!Modernizr.touchevents) {
mapping.mouseenter = function () { this.model.focus(); };
}
return mapping;
},
/**
* Renders the visual view of a contextual link. Listens to mouse & touch.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
/**
* @inheritdoc
*
* @return {Drupal.contextual.VisualView}
* The current contextual visual view.
*/
render: function () {
var isOpen = this.model.get('isOpen');
// The trigger should be visible when:
// - the mouse hovered over the region,
// - the trigger is locked,
// - and for as long as the contextual menu is open.
var isVisible = this.model.get('isLocked') || this.model.get('regionIsHovered') || isOpen;
this.$el
// The open state determines if the links are visible.
.toggleClass('open', isOpen)
// Update the visibility of the trigger.
.find('.trigger').toggleClass('visually-hidden', !isVisible);
// Nested contextual region handling: hide any nested contextual triggers.
if ('isOpen' in this.model.changed) {
this.$el.closest('.contextual-region')
.find('.contextual .trigger:not(:first)')
.toggle(!isOpen);
}
return this;
}
});
})(Drupal, Backbone, Modernizr);
;
/**
* @file
* Attaches behaviors for Drupal's active link marking.
*/
(function (Drupal, drupalSettings) {
'use strict';
/**
* Append is-active class.
*
* The link is only active if its path corresponds to the current path, the
* language of the linked path is equal to the current language, and if the
* query parameters of the link equal those of the current request, since the
* same request with different query parameters may yield a different page
* (e.g. pagers, exposed View filters).
*
* Does not discriminate based on element type, so allows you to set the
* is-active class on any element: a, li…
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.activeLinks = {
attach: function (context) {
// Start by finding all potentially active links.
var path = drupalSettings.path;
var queryString = JSON.stringify(path.currentQuery);
var querySelector = path.currentQuery ? "[data-drupal-link-query='" + queryString + "']" : ':not([data-drupal-link-query])';
var originalSelectors = ['[data-drupal-link-system-path="' + path.currentPath + '"]'];
var selectors;
// If this is the front page, we have to check for the <front> path as
// well.
if (path.isFront) {
originalSelectors.push('[data-drupal-link-system-path="<front>"]');
}
// Add language filtering.
selectors = [].concat(
// Links without any hreflang attributes (most of them).
originalSelectors.map(function (selector) { return selector + ':not([hreflang])'; }),
// Links with hreflang equals to the current language.
originalSelectors.map(function (selector) { return selector + '[hreflang="' + path.currentLanguage + '"]'; })
);
// Add query string selector for pagers, exposed filters.
selectors = selectors.map(function (current) { return current + querySelector; });
// Query the DOM.
var activeLinks = context.querySelectorAll(selectors.join(','));
var il = activeLinks.length;
for (var i = 0; i < il; i++) {
activeLinks[i].classList.add('is-active');
}
},
detach: function (context, settings, trigger) {
if (trigger === 'unload') {
var activeLinks = context.querySelectorAll('[data-drupal-link-system-path].is-active');
var il = activeLinks.length;
for (var i = 0; i < il; i++) {
activeLinks[i].classList.remove('is-active');
}
}
}
};
})(Drupal, drupalSettings);
;
/**
* @file
* Progress bar.
*/
(function ($, Drupal) {
'use strict';
/**
* Theme function for the progress bar.
*
* @param {string} id
*
* @return {string}
* The HTML for the progress bar.
*/
Drupal.theme.progressBar = function (id) {
return '<div id="' + id + '" class="progress" aria-live="polite">' +
'<div class="progress__label"> </div>' +
'<div class="progress__track"><div class="progress__bar"></div></div>' +
'<div class="progress__percentage"></div>' +
'<div class="progress__description"> </div>' +
'</div>';
};
/**
* A progressbar object. Initialized with the given id. Must be inserted into
* the DOM afterwards through progressBar.element.
*
* Method is the function which will perform the HTTP request to get the
* progress bar state. Either "GET" or "POST".
*
* @example
* pb = new Drupal.ProgressBar('myProgressBar');
* some_element.appendChild(pb.element);
*
* @constructor
*
* @param {string} id
* @param {function} updateCallback
* @param {string} method
* @param {function} errorCallback
*/
Drupal.ProgressBar = function (id, updateCallback, method, errorCallback) {
this.id = id;
this.method = method || 'GET';
this.updateCallback = updateCallback;
this.errorCallback = errorCallback;
// The WAI-ARIA setting aria-live="polite" will announce changes after
// users
// have completed their current activity and not interrupt the screen
// reader.
this.element = $(Drupal.theme('progressBar', id));
};
$.extend(Drupal.ProgressBar.prototype, /** @lends Drupal.ProgressBar# */{
/**
* Set the percentage and status message for the progressbar.
*
* @param {number} percentage
* @param {string} message
* @param {string} label
*/
setProgress: function (percentage, message, label) {
if (percentage >= 0 && percentage <= 100) {
$(this.element).find('div.progress__bar').css('width', percentage + '%');
$(this.element).find('div.progress__percentage').html(percentage + '%');
}
$('div.progress__description', this.element).html(message);
$('div.progress__label', this.element).html(label);
if (this.updateCallback) {
this.updateCallback(percentage, message, this);
}
},
/**
* Start monitoring progress via Ajax.
*
* @param {string} uri
* @param {number} delay
*/
startMonitoring: function (uri, delay) {
this.delay = delay;
this.uri = uri;
this.sendPing();
},
/**
* Stop monitoring progress via Ajax.
*/
stopMonitoring: function () {
clearTimeout(this.timer);
// This allows monitoring to be stopped from within the callback.
this.uri = null;
},
/**
* Request progress data from server.
*/
sendPing: function () {
if (this.timer) {
clearTimeout(this.timer);
}
if (this.uri) {
var pb = this;
// When doing a post request, you need non-null data. Otherwise a
// HTTP 411 or HTTP 406 (with Apache mod_security) error may result.
var uri = this.uri;
if (uri.indexOf('?') === -1) {
uri += '?';
}
else {
uri += '&';
}
uri += '_format=json';
$.ajax({
type: this.method,
url: uri,
data: '',
success: function (progress) {
// Display errors.
if (progress.status === 0) {
pb.displayError(progress.data);
return;
}
// Update display.
pb.setProgress(progress.percentage, progress.message, progress.label);
// Schedule next timer.
pb.timer = setTimeout(function () { pb.sendPing(); }, pb.delay);
},
error: function (xmlhttp) {
var e = new Drupal.AjaxError(xmlhttp, pb.uri);
pb.displayError('<pre>' + e.message + '</pre>');
}
});
}
},
/**
* Display errors on the page.
*
* @param {string} string
*/
displayError: function (string) {
var error = $('<div class="messages messages--error"></div>').html(string);
$(this.element).before(error).hide();
if (this.errorCallback) {
this.errorCallback(this);
}
}
});
})(jQuery, Drupal);
;
/**
* @file
* Provides Ajax page updating via jQuery $.ajax.
*
* Ajax is a method of making a request via JavaScript while viewing an HTML
* page. The request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*/
(function ($, window, Drupal, drupalSettings) {
'use strict';
/**
* Attaches the Ajax behavior to each Ajax form element.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.AJAX = {
attach: function (context, settings) {
function loadAjaxBehavior(base) {
var element_settings = settings.ajax[base];
if (typeof element_settings.selector === 'undefined') {
element_settings.selector = '#' + base;
}
$(element_settings.selector).once('drupal-ajax').each(function () {
element_settings.element = this;
element_settings.base = base;
Drupal.ajax(element_settings);
});
}
// Load all Ajax behaviors specified in the settings.
for (var base in settings.ajax) {
if (settings.ajax.hasOwnProperty(base)) {
loadAjaxBehavior(base);
}
}
// Bind Ajax behaviors to all items showing the class.
$('.use-ajax').once('ajax').each(function () {
var element_settings = {};
// Clicked links look better with the throbber than the progress bar.
element_settings.progress = {type: 'throbber'};
// For anchor tags, these will go to the target of the anchor rather
// than the usual location.
if ($(this).attr('href')) {
element_settings.url = $(this).attr('href');
element_settings.event = 'click';
}
element_settings.dialogType = $(this).data('dialog-type');
element_settings.dialog = $(this).data('dialog-options');
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
// This class means to submit the form to the action using Ajax.
$('.use-ajax-submit').once('ajax').each(function () {
var element_settings = {};
// Ajax submits specified in this manner automatically submit to the
// normal form action.
element_settings.url = $(this.form).attr('action');
// Form submit button clicks need to tell the form what was clicked so
// it gets passed in the POST request.
element_settings.setClick = true;
// Form buttons use the 'click' event rather than mousedown.
element_settings.event = 'click';
// Clicked form buttons look better with the throbber than the progress
// bar.
element_settings.progress = {type: 'throbber'};
element_settings.base = $(this).attr('id');
element_settings.element = this;
Drupal.ajax(element_settings);
});
}
};
/**
* Extends Error to provide handling for Errors in Ajax.
*
* @constructor
*
* @augments Error
*
* @param {XMLHttpRequest} xmlhttp
* XMLHttpRequest object used for the failed request.
* @param {string} uri
* The URI where the error occurred.
* @param {string} customMessage
* The custom message.
*/
Drupal.AjaxError = function (xmlhttp, uri, customMessage) {
var statusCode;
var statusText;
var pathText;
var responseText;
var readyStateText;
if (xmlhttp.status) {
statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status});
}
else {
statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.');
}
statusCode += '\n' + Drupal.t('Debugging information follows.');
pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri});
statusText = '';
// In some cases, when statusCode === 0, xmlhttp.statusText may not be
// defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
// catch that and the test causes an exception. So we need to catch the
// exception here.
try {
statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)});
}
catch (e) {
// Empty.
}
responseText = '';
// Again, we don't have a way to know for sure whether accessing
// xmlhttp.responseText is going to throw an exception. So we'll catch it.
try {
responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)});
}
catch (e) {
// Empty.
}
// Make the responseText more readable by stripping HTML tags and newlines.
responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
responseText = responseText.replace(/[\n]+\s+/g, '\n');
// We don't need readyState except for status == 0.
readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : '';
customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : '';
/**
* Formatted and translated error message.
*
* @type {string}
*/
this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
/**
* Used by some browsers to display a more accurate stack trace.
*
* @type {string}
*/
this.name = 'AjaxError';
};
Drupal.AjaxError.prototype = new Error();
Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
/**
* Provides Ajax page updating via jQuery $.ajax.
*
* This function is designed to improve developer experience by wrapping the
* initialization of {@link Drupal.Ajax} objects and storing all created
* objects in the {@link Drupal.ajax.instances} array.
*
* @example
* Drupal.behaviors.myCustomAJAXStuff = {
* attach: function (context, settings) {
*
* var ajaxSettings = {
* url: 'my/url/path',
* // If the old version of Drupal.ajax() needs to be used those
* // properties can be added
* base: 'myBase',
* element: $(context).find('.someElement')
* };
*
* var myAjaxObject = Drupal.ajax(ajaxSettings);
*
* // Declare a new Ajax command specifically for this Ajax object.
* myAjaxObject.commands.insert = function (ajax, response, status) {
* $('#my-wrapper').append(response.data);
* alert('New content was appended to #my-wrapper');
* };
*
* // This command will remove this Ajax object from the page.
* myAjaxObject.commands.destroyObject = function (ajax, response, status) {
* Drupal.ajax.instances[this.instanceIndex] = null;
* };
*
* // Programmatically trigger the Ajax request.
* myAjaxObject.execute();
* }
* };
*
* @param {object} settings
* The settings object passed to {@link Drupal.Ajax} constructor.
* @param {string} [settings.base]
* Base is passed to {@link Drupal.Ajax} constructor as the 'base'
* parameter.
* @param {HTMLElement} [settings.element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
*
* @return {Drupal.Ajax}
*
* @see Drupal.AjaxCommands
*/
Drupal.ajax = function (settings) {
if (arguments.length !== 1) {
throw new Error('Drupal.ajax() function must be called with one configuration object only');
}
// Map those config keys to variables for the old Drupal.ajax function.
var base = settings.base || false;
var element = settings.element || false;
delete settings.base;
delete settings.element;
// By default do not display progress for ajax calls without an element.
if (!settings.progress && !element) {
settings.progress = false;
}
var ajax = new Drupal.Ajax(base, element, settings);
ajax.instanceIndex = Drupal.ajax.instances.length;
Drupal.ajax.instances.push(ajax);
return ajax;
};
/**
* Contains all created Ajax objects.
*
* @type {Array.<Drupal.Ajax>}
*/
Drupal.ajax.instances = [];
/**
* Ajax constructor.
*
* The Ajax request returns an array of commands encoded in JSON, which is
* then executed to make any changes that are necessary to the page.
*
* Drupal uses this file to enhance form elements with `#ajax['url']` and
* `#ajax['wrapper']` properties. If set, this file will automatically be
* included to provide Ajax capabilities.
*
* @constructor
*
* @param {string} [base]
* Base parameter of {@link Drupal.Ajax} constructor
* @param {HTMLElement} [element]
* Element parameter of {@link Drupal.Ajax} constructor, element on which
* event listeners will be bound.
* @param {object} element_settings
* @param {string} element_settings.url
* Target of the Ajax request.
* @param {string} [element_settings.event]
* Event bound to settings.element which will trigger the Ajax request.
* @param {string} [element_settings.method]
* Name of the jQuery method used to insert new content in the targeted
* element.
*/
Drupal.Ajax = function (base, element, element_settings) {
var defaults = {
event: element ? 'mousedown' : null,
keypress: true,
selector: base ? '#' + base : null,
effect: 'none',
speed: 'none',
method: 'replaceWith',
progress: {
type: 'throbber',
message: Drupal.t('Please wait...')
},
submit: {
js: true
}
};
$.extend(this, defaults, element_settings);
/**
* @type {Drupal.AjaxCommands}
*/
this.commands = new Drupal.AjaxCommands();
this.instanceIndex = false;
// @todo Remove this after refactoring the PHP code to:
// - Call this 'selector'.
// - Include the '#' for ID-based selectors.
// - Support non-ID-based selectors.
if (this.wrapper) {
/**
* @type {string}
*/
this.wrapper = '#' + this.wrapper;
}
/**
* @type {HTMLElement}
*/
this.element = element;
/**
* @type {object}
*/
this.element_settings = element_settings;
// If there isn't a form, jQuery.ajax() will be used instead, allowing us to
// bind Ajax to links as well.
if (this.element && this.element.form) {
/**
* @type {jQuery}
*/
this.$form = $(this.element.form);
}
// If no Ajax callback URL was given, use the link href or form action.
if (!this.url) {
var $element = $(this.element);
if ($element.is('a')) {
this.url = $element.attr('href');
}
else if (this.element && element.form) {
this.url = this.$form.attr('action');
}
}
// Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
// the server detect when it needs to degrade gracefully.
// There are four scenarios to check for:
// 1. /nojs/
// 2. /nojs$ - The end of a URL string.
// 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
// 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
var originalUrl = this.url;
this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1');
// If the 'nojs' version of the URL is trusted, also trust the 'ajax'
// version.
if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
drupalSettings.ajaxTrustedUrl[this.url] = true;
}
// Set the options for the ajaxSubmit function.
// The 'this' variable will not persist inside of the options object.
var ajax = this;
/**
* Options for the ajaxSubmit function.
*
* @name Drupal.Ajax#options
*
* @type {object}
*
* @prop {string} url
* @prop {object} data
* @prop {function} beforeSerialize
* @prop {function} beforeSubmit
* @prop {function} beforeSend
* @prop {function} success
* @prop {function} complete
* @prop {string} dataType
* @prop {object} accepts
* @prop {string} accepts.json
* @prop {string} type
*/
ajax.options = {
url: ajax.url,
data: ajax.submit,
beforeSerialize: function (element_settings, options) {
return ajax.beforeSerialize(element_settings, options);
},
beforeSubmit: function (form_values, element_settings, options) {
ajax.ajaxing = true;
return ajax.beforeSubmit(form_values, element_settings, options);
},
beforeSend: function (xmlhttprequest, options) {
ajax.ajaxing = true;
return ajax.beforeSend(xmlhttprequest, options);
},
success: function (response, status, xmlhttprequest) {
// Sanity check for browser support (object expected).
// When using iFrame uploads, responses must be returned as a string.
if (typeof response === 'string') {
response = $.parseJSON(response);
}
// Prior to invoking the response's commands, verify that they can be
// trusted by checking for a response header. See
// \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
// - Empty responses are harmless so can bypass verification. This
// avoids an alert message for server-generated no-op responses that
// skip Ajax rendering.
// - Ajax objects with trusted URLs (e.g., ones defined server-side via
// #ajax) can bypass header verification. This is especially useful
// for Ajax with multipart forms. Because IFRAME transport is used,
// the response headers cannot be accessed for verification.
if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
var customMessage = Drupal.t('The response failed verification so will not be processed.');
return ajax.error(xmlhttprequest, ajax.url, customMessage);
}
}
return ajax.success(response, status);
},
complete: function (xmlhttprequest, status) {
ajax.ajaxing = false;
if (status === 'error' || status === 'parsererror') {
return ajax.error(xmlhttprequest, ajax.url);
}
},
dataType: 'json',
type: 'POST'
};
if (element_settings.dialog) {
ajax.options.data.dialogOptions = element_settings.dialog;
}
// Ensure that we have a valid URL by adding ? when no query parameter is
// yet available, otherwise append using &.
if (ajax.options.url.indexOf('?') === -1) {
ajax.options.url += '?';
}
else {
ajax.options.url += '&';
}
ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax');
// Bind the ajaxSubmit function to the element event.
$(ajax.element).on(element_settings.event, function (event) {
if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
}
return ajax.eventResponse(this, event);
});
// If necessary, enable keyboard submission so that Ajax behaviors
// can be triggered through keyboard input as well as e.g. a mousedown
// action.
if (element_settings.keypress) {
$(ajax.element).on('keypress', function (event) {
return ajax.keypressResponse(this, event);
});
}
// If necessary, prevent the browser default action of an additional event.
// For example, prevent the browser default action of a click, even if the
// Ajax behavior binds to mousedown.
if (element_settings.prevent) {
$(ajax.element).on(element_settings.prevent, false);
}
};
/**
* URL query attribute to indicate the wrapper used to render a request.
*
* The wrapper format determines how the HTML is wrapped, for example in a
* modal dialog.
*
* @const {string}
*/
Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
/**
* Request parameter to indicate that a request is a Drupal Ajax request.
*
* @const
*/
Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
/**
* Execute the ajax request.
*
* Allows developers to execute an Ajax request manually without specifying
* an event to respond to.
*/
Drupal.Ajax.prototype.execute = function () {
// Do not perform another ajax command if one is already in progress.
if (this.ajaxing) {
return;
}
try {
this.beforeSerialize(this.element, this.options);
$.ajax(this.options);
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
this.ajaxing = false;
window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message);
}
};
/**
* Handle a key press.
*
* The Ajax object will, if instructed, bind to a key press response. This
* will test to see if the key press is valid to trigger this event and
* if it is, trigger it for us and prevent other keypresses from triggering.
* In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
* and 32. RETURN is often used to submit a form when in a textfield, and
* SPACE is often used to activate an element without submitting.
*
* @param {HTMLElement} element
* @param {jQuery.Event} event
*/
Drupal.Ajax.prototype.keypressResponse = function (element, event) {
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Detect enter key and space bar and allow the standard response for them,
// except for form elements of type 'text', 'tel', 'number' and 'textarea',
// where the spacebar activation causes inappropriate activation if
// #ajax['keypress'] is TRUE. On a text-type widget a space should always
// be a space.
if (event.which === 13 || (event.which === 32 && element.type !== 'text' &&
element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) {
event.preventDefault();
event.stopPropagation();
$(ajax.element_settings.element).trigger(ajax.element_settings.event);
}
};
/**
* Handle an event that triggers an Ajax response.
*
* When an event that triggers an Ajax response happens, this method will
* perform the actual Ajax call. It is bound to the event using
* bind() in the constructor, and it uses the options specified on the
* Ajax object.
*
* @param {HTMLElement} element
* @param {jQuery.Event} event
*/
Drupal.Ajax.prototype.eventResponse = function (element, event) {
event.preventDefault();
event.stopPropagation();
// Create a synonym for this to reduce code confusion.
var ajax = this;
// Do not perform another Ajax command if one is already in progress.
if (ajax.ajaxing) {
return;
}
try {
if (ajax.$form) {
// If setClick is set, we must set this to ensure that the button's
// value is passed.
if (ajax.setClick) {
// Mark the clicked button. 'form.clk' is a special variable for
// ajaxSubmit that tells the system which element got clicked to
// trigger the submit. Without it there would be no 'op' or
// equivalent.
element.form.clk = element;
}
ajax.$form.ajaxSubmit(ajax.options);
}
else {
ajax.beforeSerialize(ajax.element, ajax.options);
$.ajax(ajax.options);
}
}
catch (e) {
// Unset the ajax.ajaxing flag here because it won't be unset during
// the complete response.
ajax.ajaxing = false;
window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message);
}
};
/**
* Handler for the form serialization.
*
* Runs before the beforeSend() handler (see below), and unlike that one, runs
* before field data is collected.
*
* @param {HTMLElement} element
* @param {object} options
* @param {object} options.data
*/
Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
// Allow detaching behaviors to update field values before collecting them.
// This is only needed when field values are added to the POST data, so only
// when there is a form such that this.$form.ajaxSubmit() is used instead of
// $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
// isn't called, but don't rely on that: explicitly check this.$form.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
}
// Inform Drupal that this is an AJAX request.
options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
// Allow Drupal to return new JavaScript and CSS files to load without
// returning the ones already loaded.
// @see \Drupal\Core\Theme\AjaxBasePageNegotiator
// @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
// @see system_js_settings_alter()
var pageState = drupalSettings.ajaxPageState;
options.data['ajax_page_state[theme]'] = pageState.theme;
options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
options.data['ajax_page_state[libraries]'] = pageState.libraries;
};
/**
* Modify form values prior to form submission.
*
* @param {object} form_values
* @param {HTMLElement} element
* @param {object} options
*/
Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
// This function is left empty to make it simple to override for modules
// that wish to add functionality here.
};
/**
* Prepare the Ajax request before it is sent.
*
* @param {XMLHttpRequest} xmlhttprequest
* @param {object} options
* @param {object} options.extraData
*/
Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
// For forms without file inputs, the jQuery Form plugin serializes the
// form values, and then calls jQuery's $.ajax() function, which invokes
// this handler. In this circumstance, options.extraData is never used. For
// forms with file inputs, the jQuery Form plugin uses the browser's normal
// form submission mechanism, but captures the response in a hidden IFRAME.
// In this circumstance, it calls this handler first, and then appends
// hidden fields to the form to submit the values in options.extraData.
// There is no simple way to know which submission mechanism will be used,
// so we add to extraData regardless, and allow it to be ignored in the
// former case.
if (this.$form) {
options.extraData = options.extraData || {};
// Let the server know when the IFRAME submission mechanism is used. The
// server can use this information to wrap the JSON response in a
// TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
options.extraData.ajax_iframe_upload = '1';
// The triggering element is about to be disabled (see below), but if it
// contains a value (e.g., a checkbox, textfield, select, etc.), ensure
// that value is included in the submission. As per above, submissions
// that use $.ajax() are already serialized prior to the element being
// disabled, so this is only needed for IFRAME submissions.
var v = $.fieldValue(this.element);
if (v !== null) {
options.extraData[this.element.name] = v;
}
}
// Disable the element that received the change to prevent user interface
// interaction while the Ajax request is in progress. ajax.ajaxing prevents
// the element from triggering a new request, but does not prevent the user
// from changing its value.
$(this.element).prop('disabled', true);
if (!this.progress || !this.progress.type) {
return;
}
// Insert progress indicator.
var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase();
if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
this[progressIndicatorMethod].call(this);
}
};
/**
* Sets the progress bar progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
if (this.progress.message) {
progressBar.setProgress(-1, this.progress.message);
}
if (this.progress.url) {
progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
}
this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
this.progress.object = progressBar;
$(this.element).after(this.progress.element);
};
/**
* Sets the throbber progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber"> </div></div>');
if (this.progress.message) {
this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>');
}
$(this.element).after(this.progress.element);
};
/**
* Sets the fullscreen progress indicator.
*/
Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen"> </div>');
$('body').after(this.progress.element);
};
/**
* Handler for the form redirection completion.
*
* @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
* @param {number} status
*/
Drupal.Ajax.prototype.success = function (response, status) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
$(this.element).prop('disabled', false);
for (var i in response) {
if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
this.commands[response[i].command](this, response[i], status);
}
}
// Reattach behaviors, if they were detached in beforeSerialize(). The
// attachBehaviors() called on the new content from processing the response
// commands is not sufficient, because behaviors from the entire form need
// to be reattached.
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
// Remove any response-specific settings so they don't get used on the next
// call by mistake.
this.settings = null;
};
/**
* Build an effect object to apply an effect when adding new HTML.
*
* @param {object} response
* @param {string} [response.effect]
* @param {string|number} [response.speed]
*
* @return {object}
*/
Drupal.Ajax.prototype.getEffect = function (response) {
var type = response.effect || this.effect;
var speed = response.speed || this.speed;
var effect = {};
if (type === 'none') {
effect.showEffect = 'show';
effect.hideEffect = 'hide';
effect.showSpeed = '';
}
else if (type === 'fade') {
effect.showEffect = 'fadeIn';
effect.hideEffect = 'fadeOut';
effect.showSpeed = speed;
}
else {
effect.showEffect = type + 'Toggle';
effect.hideEffect = type + 'Toggle';
effect.showSpeed = speed;
}
return effect;
};
/**
* Handler for the form redirection error.
*
* @param {object} xmlhttprequest
* @param {string} uri
* @param {string} customMessage
*/
Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
// Remove the progress element.
if (this.progress.element) {
$(this.progress.element).remove();
}
if (this.progress.object) {
this.progress.object.stopMonitoring();
}
// Undo hide.
$(this.wrapper).show();
// Re-enable the element.
$(this.element).prop('disabled', false);
// Reattach behaviors, if they were detached in beforeSerialize().
if (this.$form) {
var settings = this.settings || drupalSettings;
Drupal.attachBehaviors(this.$form.get(0), settings);
}
throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
};
/**
* @typedef {object} Drupal.AjaxCommands~commandDefinition
*
* @prop {string} command
* @prop {string} [method]
* @prop {string} [selector]
* @prop {string} [data]
* @prop {object} [settings]
* @prop {bool} [asterisk]
* @prop {string} [text]
* @prop {string} [title]
* @prop {string} [url]
* @prop {object} [argument]
* @prop {string} [name]
* @prop {string} [value]
* @prop {string} [old]
* @prop {string} [new]
* @prop {bool} [merge]
* @prop {Array} [args]
*
* @see Drupal.AjaxCommands
*/
/**
* Provide a series of commands that the client will perform.
*
* @constructor
*/
Drupal.AjaxCommands = function () {};
Drupal.AjaxCommands.prototype = {
/**
* Command to insert new content into the DOM.
*
* @param {Drupal.Ajax} ajax
* @param {object} response
* @param {string} response.data
* @param {string} [response.method]
* @param {string} [response.selector]
* @param {object} [response.settings]
* @param {number} [status]
*/
insert: function (ajax, response, status) {
// Get information from the response. If it is not there, default to
// our presets.
var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
var method = response.method || ajax.method;
var effect = ajax.getEffect(response);
var settings;
// We don't know what response.data contains: it might be a string of text
// without HTML, so don't rely on jQuery correctly interpreting
// $(response.data) as new HTML rather than a CSS selector. Also, if
// response.data contains top-level text nodes, they get lost with either
// $(response.data) or $('<div></div>').replaceWith(response.data).
var new_content_wrapped = $('<div></div>').html(response.data);
var new_content = new_content_wrapped.contents();
// For legacy reasons, the effects processing code assumes that
// new_content consists of a single top-level element. Also, it has not
// been sufficiently tested whether attachBehaviors() can be successfully
// called with a context object that includes top-level text nodes.
// However, to give developers full control of the HTML appearing in the
// page, and to enable Ajax content to be inserted in places where DIV
// elements are not allowed (e.g., within TABLE, TR, and SPAN parents),
// we check if the new content satisfies the requirement of a single
// top-level element, and only use the container DIV created above when
// it doesn't. For more information, please see
// https://www.drupal.org/node/736066.
if (new_content.length !== 1 || new_content.get(0).nodeType !== 1) {
new_content = new_content_wrapped;
}
// If removing content from the wrapper, detach behaviors first.
switch (method) {
case 'html':
case 'replaceWith':
case 'replaceAll':
case 'empty':
case 'remove':
settings = response.settings || ajax.settings || drupalSettings;
Drupal.detachBehaviors(wrapper.get(0), settings);
}
// Add the new content to the page.
wrapper[method](new_content);
// Immediately hide the new content if we're using any effects.
if (effect.showEffect !== 'show') {
new_content.hide();
}
// Determine which effect to use and what content will receive the
// effect, then show the new content.
if (new_content.find('.ajax-new-content').length > 0) {
new_content.find('.ajax-new-content').hide();
new_content.show();
new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
}
else if (effect.showEffect !== 'show') {
new_content[effect.showEffect](effect.showSpeed);
}
// Attach all JavaScript behaviors to the new content, if it was
// successfully added to the page, this if statement allows
// `#ajax['wrapper']` to be optional.
if (new_content.parents('html').length > 0) {
// Apply any settings from the returned JSON if available.
settings = response.settings || ajax.settings || drupalSettings;
Drupal.attachBehaviors(new_content.get(0), settings);
}
},
/**
* Command to remove a chunk from the page.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.selector
* @param {object} [response.settings]
* @param {number} [status]
*/
remove: function (ajax, response, status) {
var settings = response.settings || ajax.settings || drupalSettings;
$(response.selector).each(function () {
Drupal.detachBehaviors(this, settings);
})
.remove();
},
/**
* Command to mark a chunk changed.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.selector
* @param {bool} [response.asterisk]
* @param {number} [status]
*/
changed: function (ajax, response, status) {
if (!$(response.selector).hasClass('ajax-changed')) {
$(response.selector).addClass('ajax-changed');
if (response.asterisk) {
$(response.selector).find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> ');
}
}
},
/**
* Command to provide an alert.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.text
* @param {string} response.title
* @param {number} [status]
*/
alert: function (ajax, response, status) {
window.alert(response.text, response.title);
},
/**
* Command to set the window.location, redirecting the browser.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.url
* @param {number} [status]
*/
redirect: function (ajax, response, status) {
window.location = response.url;
},
/**
* Command to provide the jQuery css() function.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {object} response.argument
* @param {number} [status]
*/
css: function (ajax, response, status) {
$(response.selector).css(response.argument);
},
/**
* Command to set the settings used for other commands in this response.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {bool} response.merge
* @param {object} response.settings
* @param {number} [status]
*/
settings: function (ajax, response, status) {
if (response.merge) {
$.extend(true, drupalSettings, response.settings);
}
else {
ajax.settings = response.settings;
}
},
/**
* Command to attach data using jQuery's data API.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.name
* @param {string} response.selector
* @param {string|object} response.value
* @param {number} [status]
*/
data: function (ajax, response, status) {
$(response.selector).data(response.name, response.value);
},
/**
* Command to apply a jQuery method.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {Array} response.args
* @param {string} response.method
* @param {string} response.selector
* @param {number} [status]
*/
invoke: function (ajax, response, status) {
var $element = $(response.selector);
$element[response.method].apply($element, response.args);
},
/**
* Command to restripe a table.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.selector
* @param {number} [status]
*/
restripe: function (ajax, response, status) {
// :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.
$(response.selector).find('> tbody > tr:visible, > tr:visible')
.removeClass('odd even')
.filter(':even').addClass('odd').end()
.filter(':odd').addClass('even');
},
/**
* Command to update a form's build ID.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.old
* @param {string} response.new
* @param {number} [status]
*/
update_build_id: function (ajax, response, status) {
$('input[name="form_build_id"][value="' + response.old + '"]').val(response.new);
},
/**
* Command to add css.
*
* Uses the proprietary addImport method if available as browsers which
* support that method ignore @import statements in dynamically added
* stylesheets.
*
* @param {Drupal.Ajax} [ajax]
* @param {object} response
* @param {string} response.data
* @param {number} [status]
*/
add_css: function (ajax, response, status) {
// Add the styles in the normal way.
$('head').prepend(response.data);
// Add imports in the styles using the addImport method if available.
var match;
var importMatch = /^@import url\("(.*)"\);$/igm;
if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
importMatch.lastIndex = 0;
do {
match = importMatch.exec(response.data);
document.styleSheets[0].addImport(match[1]);
} while (match);
}
}
};
})(jQuery, this, Drupal, drupalSettings);
;
/**
* @file
* Adapted from underscore.js with the addition Drupal namespace.
*/
/**
* Limits the invocations of a function in a given time frame.
*
* The debounce function wrapper should be used sparingly. One clear use case
* is limiting the invocation of a callback attached to the window resize event.
*
* Before using the debounce function wrapper, consider first whether the
* callback could be attached to an event that fires less frequently or if the
* function can be written in such a way that it is only invoked under specific
* conditions.
*
* @param {function} func
* The function to be invoked.
* @param {number} wait
* The time period within which the callback function should only be
* invoked once. For example if the wait period is 250ms, then the callback
* will only be called at most 4 times per second.
* @param {bool} immediate
* Whether we wait at the beginning or end to execute the function.
*
* @return {function}
* The debounced function.
*/
Drupal.debounce = function (func, wait, immediate) {
'use strict';
var timeout;
var result;
return function () {
var context = this;
var args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
};
;
/**
* @file
* Adds an HTML element and method to trigger audio UAs to read system messages.
*
* Use {@link Drupal.announce} to indicate to screen reader users that an
* element on the page has changed state. For instance, if clicking a link
* loads 10 more items into a list, one might announce the change like this.
*
* @example
* $('#search-list')
* .on('itemInsert', function (event, data) {
* // Insert the new items.
* $(data.container.el).append(data.items.el);
* // Announce the change to the page contents.
* Drupal.announce(Drupal.t('@count items added to @container',
* {'@count': data.items.length, '@container': data.container.title}
* ));
* });
*/
(function (Drupal, debounce) {
'use strict';
var liveElement;
var announcements = [];
/**
* Builds a div element with the aria-live attribute and add it to the DOM.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.drupalAnnounce = {
attach: function (context) {
// Create only one aria-live element.
if (!liveElement) {
liveElement = document.createElement('div');
liveElement.id = 'drupal-live-announce';
liveElement.className = 'visually-hidden';
liveElement.setAttribute('aria-live', 'polite');
liveElement.setAttribute('aria-busy', 'false');
document.body.appendChild(liveElement);
}
}
};
/**
* Concatenates announcements to a single string; appends to the live region.
*/
function announce() {
var text = [];
var priority = 'polite';
var announcement;
// Create an array of announcement strings to be joined and appended to the
// aria live region.
var il = announcements.length;
for (var i = 0; i < il; i++) {
announcement = announcements.pop();
text.unshift(announcement.text);
// If any of the announcements has a priority of assertive then the group
// of joined announcements will have this priority.
if (announcement.priority === 'assertive') {
priority = 'assertive';
}
}
if (text.length) {
// Clear the liveElement so that repeated strings will be read.
liveElement.innerHTML = '';
// Set the busy state to true until the node changes are complete.
liveElement.setAttribute('aria-busy', 'true');
// Set the priority to assertive, or default to polite.
liveElement.setAttribute('aria-live', priority);
// Print the text to the live region. Text should be run through
// Drupal.t() before being passed to Drupal.announce().
liveElement.innerHTML = text.join('\n');
// The live text area is updated. Allow the AT to announce the text.
liveElement.setAttribute('aria-busy', 'false');
}
}
/**
* Triggers audio UAs to read the supplied text.
*
* The aria-live region will only read the text that currently populates its
* text node. Replacing text quickly in rapid calls to announce results in
* only the text from the most recent call to {@link Drupal.announce} being
* read. By wrapping the call to announce in a debounce function, we allow for
* time for multiple calls to {@link Drupal.announce} to queue up their
* messages. These messages are then joined and append to the aria-live region
* as one text node.
*
* @param {string} text
* A string to be read by the UA.
* @param {string} [priority='polite']
* A string to indicate the priority of the message. Can be either
* 'polite' or 'assertive'.
*
* @return {function}
*
* @see http://www.w3.org/WAI/PF/aria-practices/#liveprops
*/
Drupal.announce = function (text, priority) {
// Save the text and priority into a closure variable. Multiple simultaneous
// announcements will be concatenated and read in sequence.
announcements.push({
text: text,
priority: priority
});
// Immediately invoke the function that debounce returns. 200 ms is right at
// the cusp where humans notice a pause, so we will wait
// at most this much time before the set of queued announcements is read.
return (debounce(announce, 200)());
};
}(Drupal, Drupal.debounce));
;
window.matchMedia||(window.matchMedia=function(){"use strict";var e=window.styleMedia||window.media;if(!e){var t=document.createElement("style"),i=document.getElementsByTagName("script")[0],n=null;t.type="text/css";t.id="matchmediajs-test";i.parentNode.insertBefore(t,i);n="getComputedStyle"in window&&window.getComputedStyle(t,null)||t.currentStyle;e={matchMedium:function(e){var i="@media "+e+"{ #matchmediajs-test { width: 1px; } }";if(t.styleSheet){t.styleSheet.cssText=i}else{t.textContent=i}return n.width==="1px"}}}return function(t){return{matches:e.matchMedium(t||"all"),media:t||"all"}}}());
;
(function(){if(window.matchMedia&&window.matchMedia("all").addListener){return false}var e=window.matchMedia,i=e("only all").matches,n=false,t=0,a=[],r=function(i){clearTimeout(t);t=setTimeout(function(){for(var i=0,n=a.length;i<n;i++){var t=a[i].mql,r=a[i].listeners||[],o=e(t.media).matches;if(o!==t.matches){t.matches=o;for(var s=0,l=r.length;s<l;s++){r[s].call(window,t)}}}},30)};window.matchMedia=function(t){var o=e(t),s=[],l=0;o.addListener=function(e){if(!i){return}if(!n){n=true;window.addEventListener("resize",r,true)}if(l===0){l=a.push({mql:o,listeners:s})}s.push(e)};o.removeListener=function(e){for(var i=0,n=s.length;i<n;i++){if(s[i]===e){s.splice(i,1)}}};return o}})();
;
/**
* @file
* Manages elements that can offset the size of the viewport.
*
* Measures and reports viewport offset dimensions from elements like the
* toolbar that can potentially displace the positioning of other elements.
*/
/**
* @typedef {object} Drupal~displaceOffset
*
* @prop {number} top
* @prop {number} left
* @prop {number} right
* @prop {number} bottom
*/
/**
* Triggers when layout of the page changes.
*
* This is used to position fixed element on the page during page resize and
* Toolbar toggling.
*
* @event drupalViewportOffsetChange
*/
(function ($, Drupal, debounce) {
'use strict';
/**
* @name Drupal.displace.offsets
*
* @type {Drupal~displaceOffset}
*/
var offsets = {
top: 0,
right: 0,
bottom: 0,
left: 0
};
/**
* Registers a resize handler on the window.
*
* @type {Drupal~behavior}
*/
Drupal.behaviors.drupalDisplace = {
attach: function () {
// Mark this behavior as processed on the first pass.
if (this.displaceProcessed) {
return;
}
this.displaceProcessed = true;
$(window).on('resize.drupalDisplace', debounce(displace, 200));
}
};
/**
* Informs listeners of the current offset dimensions.
*
* @function Drupal.displace
*
* @prop {Drupal~displaceOffset} offsets
*
* @param {bool} [broadcast]
* When true or undefined, causes the recalculated offsets values to be
* broadcast to listeners.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*
* @fires event:drupalViewportOffsetChange
*/
function displace(broadcast) {
offsets = Drupal.displace.offsets = calculateOffsets();
if (typeof broadcast === 'undefined' || broadcast) {
$(document).trigger('drupalViewportOffsetChange', offsets);
}
return offsets;
}
/**
* Determines the viewport offsets.
*
* @return {Drupal~displaceOffset}
* An object whose keys are the for sides an element -- top, right, bottom
* and left. The value of each key is the viewport displacement distance for
* that edge.
*/
function calculateOffsets() {
return {
top: calculateOffset('top'),
right: calculateOffset('right'),
bottom: calculateOffset('bottom'),
left: calculateOffset('left')
};
}
/**
* Gets a specific edge's offset.
*
* Any element with the attribute data-offset-{edge} e.g. data-offset-top will
* be considered in the viewport offset calculations. If the attribute has a
* numeric value, that value will be used. If no value is provided, one will
* be calculated using the element's dimensions and placement.
*
* @function Drupal.displace.calculateOffset
*
* @param {string} edge
* The name of the edge to calculate. Can be 'top', 'right',
* 'bottom' or 'left'.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function calculateOffset(edge) {
var edgeOffset = 0;
var displacingElements = document.querySelectorAll('[data-offset-' + edge + ']');
var n = displacingElements.length;
for (var i = 0; i < n; i++) {
var el = displacingElements[i];
// If the element is not visible, do consider its dimensions.
if (el.style.display === 'none') {
continue;
}
// If the offset data attribute contains a displacing value, use it.
var displacement = parseInt(el.getAttribute('data-offset-' + edge), 10);
// If the element's offset data attribute exits
// but is not a valid number then get the displacement
// dimensions directly from the element.
if (isNaN(displacement)) {
displacement = getRawOffset(el, edge);
}
// If the displacement value is larger than the current value for this
// edge, use the displacement value.
edgeOffset = Math.max(edgeOffset, displacement);
}
return edgeOffset;
}
/**
* Calculates displacement for element based on its dimensions and placement.
*
* @param {HTMLElement} el
* The jQuery element whose dimensions and placement will be measured.
*
* @param {string} edge
* The name of the edge of the viewport that the element is associated
* with.
*
* @return {number}
* The viewport displacement distance for the requested edge.
*/
function getRawOffset(el, edge) {
var $el = $(el);
var documentElement = document.documentElement;
var displacement = 0;
var horizontal = (edge === 'left' || edge === 'right');
// Get the offset of the element itself.
var placement = $el.offset()[horizontal ? 'left' : 'top'];
// Subtract scroll distance from placement to get the distance
// to the edge of the viewport.
placement -= window['scroll' + (horizontal ? 'X' : 'Y')] || document.documentElement['scroll' + (horizontal) ? 'Left' : 'Top'] || 0;
// Find the displacement value according to the edge.
switch (edge) {
// Left and top elements displace as a sum of their own offset value
// plus their size.
case 'top':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerHeight();
break;
case 'left':
// Total displacement is the sum of the elements placement and size.
displacement = placement + $el.outerWidth();
break;
// Right and bottom elements displace according to their left and
// top offset. Their size isn't important.
case 'bottom':
displacement = documentElement.clientHeight - placement;
break;
case 'right':
displacement = documentElement.clientWidth - placement;
break;
default:
displacement = 0;
}
return displacement;
}
/**
* Assign the displace function to a property of the Drupal global object.
*
* @ignore
*/
Drupal.displace = displace;
$.extend(Drupal.displace, {
/**
* Expose offsets to other scripts to avoid having to recalculate offsets.
*
* @ignore
*/
offsets: offsets,
/**
* Expose method to compute a single edge offsets.
*
* @ignore
*/
calculateOffset: calculateOffset
});
})(jQuery, Drupal, Drupal.debounce);
;
/**
* @file
* Builds a nested accordion widget.
*
* Invoke on an HTML list element with the jQuery plugin pattern.
*
* @example
* $('.toolbar-menu').drupalToolbarMenu();
*/
(function ($, Drupal, drupalSettings) {
'use strict';
/**
* Store the open menu tray.
*/
var activeItem = Drupal.url(drupalSettings.path.currentPath);
$.fn.drupalToolbarMenu = function () {
var ui = {
handleOpen: Drupal.t('Extend'),
handleClose: Drupal.t('Collapse')
};
/**
* Handle clicks from the disclosure button on an item with sub-items.
*
* @param {Object} event
* A jQuery Event object.
*/
function toggleClickHandler(event) {
var $toggle = $(event.target);
var $item = $toggle.closest('li');
// Toggle the list item.
toggleList($item);
// Close open sibling menus.
var $openItems = $item.siblings().filter('.open');
toggleList($openItems, false);
}
/**
* Handle clicks from a menu item link.
*
* @param {Object} event
* A jQuery Event object.
*/
function linkClickHandler(event) {
// If the toolbar is positioned fixed (and therefore hiding content
// underneath), then users expect clicks in the administration menu tray
// to take them to that destination but for the menu tray to be closed
// after clicking: otherwise the toolbar itself is obstructing the view
// of the destination they chose.
if (!Drupal.toolbar.models.toolbarModel.get('isFixed')) {
Drupal.toolbar.models.toolbarModel.set('activeTab', null);
}
// Stopping propagation to make sure that once a toolbar-box is clicked
// (the whitespace part), the page is not redirected anymore.
event.stopPropagation();
}
/**
* Toggle the open/close state of a list is a menu.
*
* @param {jQuery} $item
* The li item to be toggled.
*
* @param {Boolean} switcher
* A flag that forces toggleClass to add or a remove a class, rather than
* simply toggling its presence.
*/
function toggleList($item, switcher) {
var $toggle = $item.children('.toolbar-box').children('.toolbar-handle');
switcher = (typeof switcher !== 'undefined') ? switcher : !$item.hasClass('open');
// Toggle the item open state.
$item.toggleClass('open', switcher);
// Twist the toggle.
$toggle.toggleClass('open', switcher);
// Adjust the toggle text.
$toggle
.find('.action')
// Expand Structure, Collapse Structure.
.text((switcher) ? ui.handleClose : ui.handleOpen);
}
/**
* Add markup to the menu elements.
*
* Items with sub-elements have a list toggle attached to them. Menu item
* links and the corresponding list toggle are wrapped with in a div
* classed with .toolbar-box. The .toolbar-box div provides a positioning
* context for the item list toggle.
*
* @param {jQuery} $menu
* The root of the menu to be initialized.
*/
function initItems($menu) {
var options = {
class: 'toolbar-icon toolbar-handle',
action: ui.handleOpen,
text: ''
};
// Initialize items and their links.
$menu.find('li > a').wrap('<div class="toolbar-box">');
// Add a handle to each list item if it has a menu.
$menu.find('li').each(function (index, element) {
var $item = $(element);
if ($item.children('ul.toolbar-menu').length) {
var $box = $item.children('.toolbar-box');
options.text = Drupal.t('@label', {'@label': $box.find('a').text()});
$item.children('.toolbar-box')
.append(Drupal.theme('toolbarMenuItemToggle', options));
}
});
}
/**
* Adds a level class to each list based on its depth in the menu.
*
* This function is called recursively on each sub level of lists elements
* until the depth of the menu is exhausted.
*
* @param {jQuery} $lists
* A jQuery object of ul elements.
*
* @param {number} level
* The current level number to be assigned to the list elements.
*/
function markListLevels($lists, level) {
level = (!level) ? 1 : level;
var $lis = $lists.children('li').addClass('level-' + level);
$lists = $lis.children('ul');
if ($lists.length) {
markListLevels($lists, level + 1);
}
}
/**
* On page load, open the active menu item.
*
* Marks the trail of the active link in the menu back to the root of the
* menu with .menu-item--active-trail.
*
* @param {jQuery} $menu
* The root of the menu.
*/
function openActiveItem($menu) {
var pathItem = $menu.find('a[href="' + location.pathname + '"]');
if (pathItem.length && !activeItem) {
activeItem = location.pathname;
}
if (activeItem) {
var $activeItem = $menu.find('a[href="' + activeItem + '"]').addClass('menu-item--active');
var $activeTrail = $activeItem.parentsUntil('.root', 'li').addClass('menu-item--active-trail');
toggleList($activeTrail, true);
}
}
// Return the jQuery object.
return this.each(function (selector) {
var $menu = $(this).once('toolbar-menu');
if ($menu.length) {
// Bind event handlers.
$menu
.on('click.toolbar', '.toolbar-box', toggleClickHandler)
.on('click.toolbar', '.toolbar-box a', linkClickHandler);
$menu.addClass('root');
initItems($menu);
markListLevels($menu);
// Restore previous and active states.
openActiveItem($menu);
}
});
};
/**
* A toggle is an interactive element often bound to a click handler.
*
* @param {object} options
* Options for the button.
* @param {string} options.class
* Class to set on the button.
* @param {string} options.action
* Action for the button.
* @param {string} options.text
* Used as label for the button.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.toolbarMenuItemToggle = function (options) {
return '<button class="' + options['class'] + '"><span class="action">' + options.action + '</span><span class="label">' + options.text + '</span></button>';
};
}(jQuery, Drupal, drupalSettings));
;
/**
* @file
* Defines the behavior of the Drupal administration toolbar.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
// Merge run-time settings with the defaults.
var options = $.extend(
{
breakpoints: {
'toolbar.narrow': '',
'toolbar.standard': '',
'toolbar.wide': ''
}
},
drupalSettings.toolbar,
// Merge strings on top of drupalSettings so that they are not mutable.
{
strings: {
horizontal: Drupal.t('Horizontal orientation'),
vertical: Drupal.t('Vertical orientation')
}
}
);
/**
* Registers tabs with the toolbar.
*
* The Drupal toolbar allows modules to register top-level tabs. These may
* point directly to a resource or toggle the visibility of a tray.
*
* Modules register tabs with hook_toolbar().
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the toolbar rendering functionality to the toolbar element.
*/
Drupal.behaviors.toolbar = {
attach: function (context) {
// Verify that the user agent understands media queries. Complex admin
// toolbar layouts require media query support.
if (!window.matchMedia('only screen').matches) {
return;
}
// Process the administrative toolbar.
$(context).find('#toolbar-administration').once('toolbar').each(function () {
// Establish the toolbar models and views.
var model = Drupal.toolbar.models.toolbarModel = new Drupal.toolbar.ToolbarModel({
locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')) || false,
activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID')))
});
Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({
el: this,
model: model,
strings: options.strings
});
Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({
el: this,
model: model
});
// Render collapsible menus.
var menuModel = Drupal.toolbar.models.menuModel = new Drupal.toolbar.MenuModel();
Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({
el: $(this).find('.toolbar-menu-administration').get(0),
model: menuModel,
strings: options.strings
});
// Handle the resolution of Drupal.toolbar.setSubtrees.
// This is handled with a deferred so that the function may be invoked
// asynchronously.
Drupal.toolbar.setSubtrees.done(function (subtrees) {
menuModel.set('subtrees', subtrees);
var theme = drupalSettings.ajaxPageState.theme;
localStorage.setItem('Drupal.toolbar.subtrees.' + theme, JSON.stringify(subtrees));
// Indicate on the toolbarModel that subtrees are now loaded.
model.set('areSubtreesLoaded', true);
});
// Attach a listener to the configured media query breakpoints.
for (var label in options.breakpoints) {
if (options.breakpoints.hasOwnProperty(label)) {
var mq = options.breakpoints[label];
var mql = Drupal.toolbar.mql[label] = window.matchMedia(mq);
// Curry the model and the label of the media query breakpoint to
// the mediaQueryChangeHandler function.
mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
// Fire the mediaQueryChangeHandler for each configured breakpoint
// so that they process once.
Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql);
}
}
// Trigger an initial attempt to load menu subitems. This first attempt
// is made after the media query handlers have had an opportunity to
// process. The toolbar starts in the vertical orientation by default,
// unless the viewport is wide enough to accommodate a horizontal
// orientation. Thus we give the Toolbar a chance to determine if it
// should be set to horizontal orientation before attempting to load
// menu subtrees.
Drupal.toolbar.views.toolbarVisualView.loadSubtrees();
$(document)
// Update the model when the viewport offset changes.
.on('drupalViewportOffsetChange.toolbar', function (event, offsets) {
model.set('offsets', offsets);
});
// Broadcast model changes to other modules.
model
.on('change:orientation', function (model, orientation) {
$(document).trigger('drupalToolbarOrientationChange', orientation);
})
.on('change:activeTab', function (model, tab) {
$(document).trigger('drupalToolbarTabChange', tab);
})
.on('change:activeTray', function (model, tray) {
$(document).trigger('drupalToolbarTrayChange', tray);
});
// If the toolbar's orientation is horizontal and no active tab is
// defined then show the tray of the first toolbar tab by default (but
// not the first 'Home' toolbar tab).
if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) {
Drupal.toolbar.models.toolbarModel.set({
activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0)
});
}
});
}
};
/**
* Toolbar methods of Backbone objects.
*
* @namespace
*/
Drupal.toolbar = {
/**
* A hash of View instances.
*
* @type {object.<string, Backbone.View>}
*/
views: {},
/**
* A hash of Model instances.
*
* @type {object.<string, Backbone.Model>}
*/
models: {},
/**
* A hash of MediaQueryList objects tracked by the toolbar.
*
* @type {object.<string, object>}
*/
mql: {},
/**
* Accepts a list of subtree menu elements.
*
* A deferred object that is resolved by an inlined JavaScript callback.
*
* @type {jQuery.Deferred}
*
* @see toolbar_subtrees_jsonp().
*/
setSubtrees: new $.Deferred(),
/**
* Respond to configured narrow media query changes.
*
* @param {Drupal.toolbar.ToolbarModel} model
* A toolbar model
* @param {string} label
* Media query label.
* @param {object} mql
* A MediaQueryList object.
*/
mediaQueryChangeHandler: function (model, label, mql) {
switch (label) {
case 'toolbar.narrow':
model.set({
isOriented: mql.matches,
isTrayToggleVisible: false
});
// If the toolbar doesn't have an explicit orientation yet, or if the
// narrow media query doesn't match then set the orientation to
// vertical.
if (!mql.matches || !model.get('orientation')) {
model.set({orientation: 'vertical'}, {validate: true});
}
break;
case 'toolbar.standard':
model.set({
isFixed: mql.matches
});
break;
case 'toolbar.wide':
model.set({
orientation: ((mql.matches) ? 'horizontal' : 'vertical')
}, {validate: true});
// The tray orientation toggle visibility does not need to be
// validated.
model.set({
isTrayToggleVisible: mql.matches
});
break;
default:
break;
}
}
};
/**
* A toggle is an interactive element often bound to a click handler.
*
* @return {string}
* A string representing a DOM fragment.
*/
Drupal.theme.toolbarOrientationToggle = function () {
return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' +
'<button class="toolbar-icon" type="button"></button>' +
'</div></div>';
};
/**
* Ajax command to set the toolbar subtrees.
*
* @param {Drupal.Ajax} ajax
* {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
* @param {object} response
* JSON response from the Ajax request.
* @param {number} [status]
* XMLHttpRequest status.
*/
Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) {
Drupal.toolbar.setSubtrees.resolve(response.subtrees);
};
}(jQuery, Drupal, drupalSettings));
;
/**
* @file
* A Backbone Model for collapsible menus.
*/
(function (Backbone, Drupal) {
'use strict';
/**
* Backbone Model for collapsible menus.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.toolbar.MenuModel = Backbone.Model.extend(/** @lends Drupal.toolbar.MenuModel# */{
/**
* @type {object}
*
* @prop {object} subtrees
*/
defaults: /** @lends Drupal.toolbar.MenuModel# */{
/**
* @type {object}
*/
subtrees: {}
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone Model for the toolbar.
*/
(function (Backbone, Drupal) {
'use strict';
/**
* Backbone model for the toolbar.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.toolbar.ToolbarModel = Backbone.Model.extend(/** @lends Drupal.toolbar.ToolbarModel# */{
/**
* @type {object}
*
* @prop activeTab
* @prop activeTray
* @prop isOriented
* @prop isFixed
* @prop areSubtreesLoaded
* @prop isViewportOverflowConstrained
* @prop orientation
* @prop locked
* @prop isTrayToggleVisible
* @prop height
* @prop offsets
*/
defaults: /** @lends Drupal.toolbar.ToolbarModel# */{
/**
* The active toolbar tab. All other tabs should be inactive under
* normal circumstances. It will remain active across page loads. The
* active item is stored as an ID selector e.g. '#toolbar-item--1'.
*
* @type {string}
*/
activeTab: null,
/**
* Represents whether a tray is open or not. Stored as an ID selector e.g.
* '#toolbar-item--1-tray'.
*
* @type {string}
*/
activeTray: null,
/**
* Indicates whether the toolbar is displayed in an oriented fashion,
* either horizontal or vertical.
*
* @type {bool}
*/
isOriented: false,
/**
* Indicates whether the toolbar is positioned absolute (false) or fixed
* (true).
*
* @type {bool}
*/
isFixed: false,
/**
* Menu subtrees are loaded through an AJAX request only when the Toolbar
* is set to a vertical orientation.
*
* @type {bool}
*/
areSubtreesLoaded: false,
/**
* If the viewport overflow becomes constrained, isFixed must be true so
* that elements in the trays aren't lost off-screen and impossible to
* get to.
*
* @type {bool}
*/
isViewportOverflowConstrained: false,
/**
* The orientation of the active tray.
*
* @type {string}
*/
orientation: 'vertical',
/**
* A tray is locked if a user toggled it to vertical. Otherwise a tray
* will switch between vertical and horizontal orientation based on the
* configured breakpoints. The locked state will be maintained across page
* loads.
*
* @type {bool}
*/
locked: false,
/**
* Indicates whether the tray orientation toggle is visible.
*
* @type {bool}
*/
isTrayToggleVisible: false,
/**
* The height of the toolbar.
*
* @type {number}
*/
height: null,
/**
* The current viewport offsets determined by {@link Drupal.displace}. The
* offsets suggest how a module might position is components relative to
* the viewport.
*
* @type {object}
*
* @prop {number} top
* @prop {number} right
* @prop {number} bottom
* @prop {number} left
*/
offsets: {
top: 0,
right: 0,
bottom: 0,
left: 0
}
},
/**
* @inheritdoc
*
* @param {object} attributes
* Attributes for the toolbar.
* @param {object} options
* Options for the toolbar.
*
* @return {string|undefined}
* Returns an error message if validation failed.
*/
validate: function (attributes, options) {
// Prevent the orientation being set to horizontal if it is locked, unless
// override has not been passed as an option.
if (attributes.orientation === 'horizontal' && this.get('locked') && !options.override) {
return Drupal.t('The toolbar cannot be set to a horizontal orientation when it is locked.');
}
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone view for the body element.
*/
(function ($, Drupal, Backbone) {
'use strict';
Drupal.toolbar.BodyVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.BodyVisualView# */{
/**
* Adjusts the body element with the toolbar position and dimension changes.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:orientation change:offsets change:activeTray change:isOriented change:isFixed change:isViewportOverflowConstrained', this.render);
},
/**
* @inheritdoc
*/
render: function () {
var $body = $('body');
var orientation = this.model.get('orientation');
var isOriented = this.model.get('isOriented');
var isViewportOverflowConstrained = this.model.get('isViewportOverflowConstrained');
$body
// We are using JavaScript to control media-query handling for two
// reasons: (1) Using JavaScript let's us leverage the breakpoint
// configurations and (2) the CSS is really complex if we try to hide
// some styling from browsers that don't understand CSS media queries.
// If we drive the CSS from classes added through JavaScript,
// then the CSS becomes simpler and more robust.
.toggleClass('toolbar-vertical', (orientation === 'vertical'))
.toggleClass('toolbar-horizontal', (isOriented && orientation === 'horizontal'))
// When the toolbar is fixed, it will not scroll with page scrolling.
.toggleClass('toolbar-fixed', (isViewportOverflowConstrained || this.model.get('isFixed')))
// Toggle the toolbar-tray-open class on the body element. The class is
// applied when a toolbar tray is active. Padding might be applied to
// the body element to prevent the tray from overlapping content.
.toggleClass('toolbar-tray-open', !!this.model.get('activeTray'))
// Apply padding to the top of the body to offset the placement of the
// toolbar bar element.
.css('padding-top', this.model.get('offsets').top);
}
});
}(jQuery, Drupal, Backbone));
;
/**
* @file
* A Backbone view for the collapsible menus.
*/
(function ($, Backbone, Drupal) {
'use strict';
Drupal.toolbar.MenuVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.MenuVisualView# */{
/**
* Backbone View for collapsible menus.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:subtrees', this.render);
},
/**
* @inheritdoc
*/
render: function () {
var subtrees = this.model.get('subtrees');
// Add subtrees.
for (var id in subtrees) {
if (subtrees.hasOwnProperty(id)) {
this.$el
.find('#toolbar-link-' + id)
.once('toolbar-subtrees')
.after(subtrees[id]);
}
}
// Render the main menu as a nested, collapsible accordion.
if ('drupalToolbarMenu' in $.fn) {
this.$el
.children('.toolbar-menu')
.drupalToolbarMenu();
}
}
});
}(jQuery, Backbone, Drupal));
;
/**
* @file
* A Backbone view for the aural feedback of the toolbar.
*/
(function (Backbone, Drupal) {
'use strict';
Drupal.toolbar.ToolbarAuralView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarAuralView# */{
/**
* Backbone view for the aural feedback of the toolbar.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
* @param {object} options.strings
* Various strings to use in the view.
*/
initialize: function (options) {
this.strings = options.strings;
this.listenTo(this.model, 'change:orientation', this.onOrientationChange);
this.listenTo(this.model, 'change:activeTray', this.onActiveTrayChange);
},
/**
* Announces an orientation change.
*
* @param {Drupal.toolbar.ToolbarModel} model
* The toolbar model in question.
* @param {string} orientation
* The new value of the orientation attribute in the model.
*/
onOrientationChange: function (model, orientation) {
Drupal.announce(Drupal.t('Tray orientation changed to @orientation.', {
'@orientation': orientation
}));
},
/**
* Announces a changed active tray.
*
* @param {Drupal.toolbar.ToolbarModel} model
* The toolbar model in question.
* @param {HTMLElement} tray
* The new value of the tray attribute in the model.
*/
onActiveTrayChange: function (model, tray) {
var relevantTray = (tray === null) ? model.previous('activeTray') : tray;
var action = (tray === null) ? Drupal.t('closed') : Drupal.t('opened');
var trayNameElement = relevantTray.querySelector('.toolbar-tray-name');
var text;
if (trayNameElement !== null) {
text = Drupal.t('Tray "@tray" @action.', {
'@tray': trayNameElement.textContent, '@action': action
});
}
else {
text = Drupal.t('Tray @action.', {'@action': action});
}
Drupal.announce(text);
}
});
}(Backbone, Drupal));
;
/**
* @file
* A Backbone view for the toolbar element. Listens to mouse & touch.
*/
(function ($, Drupal, drupalSettings, Backbone) {
'use strict';
Drupal.toolbar.ToolbarVisualView = Backbone.View.extend(/** @lends Drupal.toolbar.ToolbarVisualView# */{
/**
* Event map for the `ToolbarVisualView`.
*
* @return {object}
* A map of events.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
return {
'click .toolbar-bar .toolbar-tab': 'onTabClick',
'click .toolbar-toggle-orientation button': 'onOrientationToggleClick',
'touchend .toolbar-bar .toolbar-tab': touchEndToClick,
'touchend .toolbar-toggle-orientation button': touchEndToClick
};
},
/**
* Backbone view for the toolbar element. Listens to mouse & touch.
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view object.
* @param {object} options.strings
* Various strings to use in the view.
*/
initialize: function (options) {
this.strings = options.strings;
this.listenTo(this.model, 'change:activeTab change:orientation change:isOriented change:isTrayToggleVisible', this.render);
this.listenTo(this.model, 'change:mqMatches', this.onMediaQueryChange);
this.listenTo(this.model, 'change:offsets', this.adjustPlacement);
// Add the tray orientation toggles.
this.$el
.find('.toolbar-tray .toolbar-lining')
.append(Drupal.theme('toolbarOrientationToggle'));
// Trigger an activeTab change so that listening scripts can respond on
// page load. This will call render.
this.model.trigger('change:activeTab');
},
/**
* @inheritdoc
*
* @return {Drupal.toolbar.ToolbarVisualView}
* The `ToolbarVisualView` instance.
*/
render: function () {
this.updateTabs();
this.updateTrayOrientation();
this.updateBarAttributes();
// Load the subtrees if the orientation of the toolbar is changed to
// vertical. This condition responds to the case that the toolbar switches
// from horizontal to vertical orientation. The toolbar starts in a
// vertical orientation by default and then switches to horizontal during
// initialization if the media query conditions are met. Simply checking
// that the orientation is vertical here would result in the subtrees
// always being loaded, even when the toolbar initialization ultimately
// results in a horizontal orientation.
//
// @see Drupal.behaviors.toolbar.attach() where admin menu subtrees
// loading is invoked during initialization after media query conditions
// have been processed.
if (this.model.changed.orientation === 'vertical' || this.model.changed.activeTab) {
this.loadSubtrees();
}
// Trigger a recalculation of viewport displacing elements. Use setTimeout
// to ensure this recalculation happens after changes to visual elements
// have processed.
window.setTimeout(function () {
Drupal.displace(true);
}, 0);
return this;
},
/**
* Responds to a toolbar tab click.
*
* @param {jQuery.Event} event
* The event triggered.
*/
onTabClick: function (event) {
// If this tab has a tray associated with it, it is considered an
// activatable tab.
if (event.target.hasAttribute('data-toolbar-tray')) {
var activeTab = this.model.get('activeTab');
var clickedTab = event.target;
// Set the event target as the active item if it is not already.
this.model.set('activeTab', (!activeTab || clickedTab !== activeTab) ? clickedTab : null);
event.preventDefault();
event.stopPropagation();
}
},
/**
* Toggles the orientation of a toolbar tray.
*
* @param {jQuery.Event} event
* The event triggered.
*/
onOrientationToggleClick: function (event) {
var orientation = this.model.get('orientation');
// Determine the toggle-to orientation.
var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical';
var locked = (antiOrientation === 'vertical') ? true : false;
// Remember the locked state.
if (locked) {
localStorage.setItem('Drupal.toolbar.trayVerticalLocked', 'true');
}
else {
localStorage.removeItem('Drupal.toolbar.trayVerticalLocked');
}
// Update the model.
this.model.set({
locked: locked,
orientation: antiOrientation
}, {
validate: true,
override: true
});
event.preventDefault();
event.stopPropagation();
},
/**
* Updates the display of the tabs: toggles a tab and the associated tray.
*/
updateTabs: function () {
var $tab = $(this.model.get('activeTab'));
// Deactivate the previous tab.
$(this.model.previous('activeTab'))
.removeClass('is-active')
.prop('aria-pressed', false);
// Deactivate the previous tray.
$(this.model.previous('activeTray'))
.removeClass('is-active');
// Activate the selected tab.
if ($tab.length > 0) {
$tab
.addClass('is-active')
// Mark the tab as pressed.
.prop('aria-pressed', true);
var name = $tab.attr('data-toolbar-tray');
// Store the active tab name or remove the setting.
var id = $tab.get(0).id;
if (id) {
localStorage.setItem('Drupal.toolbar.activeTabID', JSON.stringify(id));
}
// Activate the associated tray.
var $tray = this.$el.find('[data-toolbar-tray="' + name + '"].toolbar-tray');
if ($tray.length) {
$tray.addClass('is-active');
this.model.set('activeTray', $tray.get(0));
}
else {
// There is no active tray.
this.model.set('activeTray', null);
}
}
else {
// There is no active tray.
this.model.set('activeTray', null);
localStorage.removeItem('Drupal.toolbar.activeTabID');
}
},
/**
* Update the attributes of the toolbar bar element.
*/
updateBarAttributes: function () {
var isOriented = this.model.get('isOriented');
if (isOriented) {
this.$el.find('.toolbar-bar').attr('data-offset-top', '');
}
else {
this.$el.find('.toolbar-bar').removeAttr('data-offset-top');
}
// Toggle between a basic vertical view and a more sophisticated
// horizontal and vertical display of the toolbar bar and trays.
this.$el.toggleClass('toolbar-oriented', isOriented);
},
/**
* Updates the orientation of the active tray if necessary.
*/
updateTrayOrientation: function () {
var orientation = this.model.get('orientation');
// The antiOrientation is used to render the view of action buttons like
// the tray orientation toggle.
var antiOrientation = (orientation === 'vertical') ? 'horizontal' : 'vertical';
// Update the orientation of the trays.
var $trays = this.$el.find('.toolbar-tray')
.removeClass('toolbar-tray-horizontal toolbar-tray-vertical')
.addClass('toolbar-tray-' + orientation);
// Update the tray orientation toggle button.
var iconClass = 'toolbar-icon-toggle-' + orientation;
var iconAntiClass = 'toolbar-icon-toggle-' + antiOrientation;
var $orientationToggle = this.$el.find('.toolbar-toggle-orientation')
.toggle(this.model.get('isTrayToggleVisible'));
$orientationToggle.find('button')
.val(antiOrientation)
.attr('title', this.strings[antiOrientation])
.text(this.strings[antiOrientation])
.removeClass(iconClass)
.addClass(iconAntiClass);
// Update data offset attributes for the trays.
var dir = document.documentElement.dir;
var edge = (dir === 'rtl') ? 'right' : 'left';
// Remove data-offset attributes from the trays so they can be refreshed.
$trays.removeAttr('data-offset-left data-offset-right data-offset-top');
// If an active vertical tray exists, mark it as an offset element.
$trays.filter('.toolbar-tray-vertical.is-active').attr('data-offset-' + edge, '');
// If an active horizontal tray exists, mark it as an offset element.
$trays.filter('.toolbar-tray-horizontal.is-active').attr('data-offset-top', '');
},
/**
* Sets the tops of the trays so that they align with the bottom of the bar.
*/
adjustPlacement: function () {
var $trays = this.$el.find('.toolbar-tray');
if (!this.model.get('isOriented')) {
$trays.css('margin-top', 0);
$trays.removeClass('toolbar-tray-horizontal').addClass('toolbar-tray-vertical');
}
else {
// The toolbar container is invisible. Its placement is used to
// determine the container for the trays.
$trays.css('margin-top', this.$el.find('.toolbar-bar').outerHeight());
}
},
/**
* Calls the endpoint URI that builds an AJAX command with the rendered
* subtrees.
*
* The rendered admin menu subtrees HTML is cached on the client in
* localStorage until the cache of the admin menu subtrees on the server-
* side is invalidated. The subtreesHash is stored in localStorage as well
* and compared to the subtreesHash in drupalSettings to determine when the
* admin menu subtrees cache has been invalidated.
*/
loadSubtrees: function () {
var $activeTab = $(this.model.get('activeTab'));
var orientation = this.model.get('orientation');
// Only load and render the admin menu subtrees if:
// (1) They have not been loaded yet.
// (2) The active tab is the administration menu tab, indicated by the
// presence of the data-drupal-subtrees attribute.
// (3) The orientation of the tray is vertical.
if (!this.model.get('areSubtreesLoaded') && typeof $activeTab.data('drupal-subtrees') !== 'undefined' && orientation === 'vertical') {
var subtreesHash = drupalSettings.toolbar.subtreesHash;
var theme = drupalSettings.ajaxPageState.theme;
var endpoint = Drupal.url('toolbar/subtrees/' + subtreesHash);
var cachedSubtreesHash = localStorage.getItem('Drupal.toolbar.subtreesHash.' + theme);
var cachedSubtrees = JSON.parse(localStorage.getItem('Drupal.toolbar.subtrees.' + theme));
var isVertical = this.model.get('orientation') === 'vertical';
// If we have the subtrees in localStorage and the subtree hash has not
// changed, then use the cached data.
if (isVertical && subtreesHash === cachedSubtreesHash && cachedSubtrees) {
Drupal.toolbar.setSubtrees.resolve(cachedSubtrees);
}
// Only make the call to get the subtrees if the orientation of the
// toolbar is vertical.
else if (isVertical) {
// Remove the cached menu information.
localStorage.removeItem('Drupal.toolbar.subtreesHash.' + theme);
localStorage.removeItem('Drupal.toolbar.subtrees.' + theme);
// The AJAX response's command will trigger the resolve method of the
// Drupal.toolbar.setSubtrees Promise.
Drupal.ajax({url: endpoint}).execute();
// Cache the hash for the subtrees locally.
localStorage.setItem('Drupal.toolbar.subtreesHash.' + theme, subtreesHash);
}
}
}
});
}(jQuery, Drupal, drupalSettings, Backbone));
;
/*! jquery.cookie v1.4.1 | MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?a(require("jquery")):a(jQuery)}(function(a){function b(a){return h.raw?a:encodeURIComponent(a)}function c(a){return h.raw?a:decodeURIComponent(a)}function d(a){return b(h.json?JSON.stringify(a):String(a))}function e(a){0===a.indexOf('"')&&(a=a.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"));try{return a=decodeURIComponent(a.replace(g," ")),h.json?JSON.parse(a):a}catch(b){}}function f(b,c){var d=h.raw?b:e(b);return a.isFunction(c)?c(d):d}var g=/\+/g,h=a.cookie=function(e,g,i){if(void 0!==g&&!a.isFunction(g)){if(i=a.extend({},h.defaults,i),"number"==typeof i.expires){var j=i.expires,k=i.expires=new Date;k.setTime(+k+864e5*j)}return document.cookie=[b(e),"=",d(g),i.expires?"; expires="+i.expires.toUTCString():"",i.path?"; path="+i.path:"",i.domain?"; domain="+i.domain:"",i.secure?"; secure":""].join("")}for(var l=e?void 0:{},m=document.cookie?document.cookie.split("; "):[],n=0,o=m.length;o>n;n++){var p=m[n].split("="),q=c(p.shift()),r=p.join("=");if(e&&e===q){l=f(r,g);break}e||void 0===(r=f(r))||(l[q]=r)}return l};h.defaults={},a.removeCookie=function(b,c){return void 0===a.cookie(b)?!1:(a.cookie(b,"",a.extend({},c,{expires:-1})),!a.cookie(b))}});;
/* jQuery Foundation Joyride Plugin 2.1 | Copyright 2012, ZURB | www.opensource.org/licenses/mit-license.php */
(function(e,t,n){"use strict";var r={version:"2.0.3",tipLocation:"bottom",nubPosition:"auto",scroll:!0,scrollSpeed:300,timer:0,autoStart:!1,startTimerOnClick:!0,startOffset:0,nextButton:!0,tipAnimation:"fade",pauseAfter:[],tipAnimationFadeSpeed:300,cookieMonster:!1,cookieName:"joyride",cookieDomain:!1,cookiePath:!1,localStorage:!1,localStorageKey:"joyride",tipContainer:"body",modal:!1,expose:!1,postExposeCallback:e.noop,preRideCallback:e.noop,postRideCallback:e.noop,preStepCallback:e.noop,postStepCallback:e.noop,template:{link:'<a href="#close" class="joyride-close-tip">X</a>',timer:'<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>',tip:'<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>',wrapper:'<div class="joyride-content-wrapper" role="dialog"></div>',button:'<a href="#" class="joyride-next-tip"></a>',modal:'<div class="joyride-modal-bg"></div>',expose:'<div class="joyride-expose-wrapper"></div>',exposeCover:'<div class="joyride-expose-cover"></div>'}},i=i||!1,s={},o={init:function(n){return this.each(function(){e.isEmptyObject(s)?(s=e.extend(!0,r,n),s.document=t.document,s.$document=e(s.document),s.$window=e(t),s.$content_el=e(this),s.$body=e(s.tipContainer),s.body_offset=e(s.tipContainer).position(),s.$tip_content=e("> li",s.$content_el),s.paused=!1,s.attempts=0,s.tipLocationPatterns={top:["bottom"],bottom:[],left:["right","top","bottom"],right:["left","top","bottom"]},o.jquery_check(),e.isFunction(e.cookie)||(s.cookieMonster=!1),(!s.cookieMonster||!e.cookie(s.cookieName))&&(!s.localStorage||!o.support_localstorage()||!localStorage.getItem(s.localStorageKey))&&(s.$tip_content.each(function(t){o.create({$li:e(this),index:t})}),s.autoStart&&(!s.startTimerOnClick&&s.timer>0?(o.show("init"),o.startTimer()):o.show("init"))),s.$document.on("click.joyride",".joyride-next-tip, .joyride-modal-bg",function(e){e.preventDefault(),s.$li.next().length<1?o.end():s.timer>0?(clearTimeout(s.automate),o.hide(),o.show(),o.startTimer()):(o.hide(),o.show())}),s.$document.on("click.joyride",".joyride-close-tip",function(e){e.preventDefault(),o.end()}),s.$window.bind("resize.joyride",function(t){if(s.$li){if(s.exposed&&s.exposed.length>0){var n=e(s.exposed);n.each(function(){var t=e(this);o.un_expose(t),o.expose(t)})}o.is_phone()?o.pos_phone():o.pos_default()}})):o.restart()})},resume:function(){o.set_li(),o.show()},nextTip:function(){s.$li.next().length<1?o.end():s.timer>0?(clearTimeout(s.automate),o.hide(),o.show(),o.startTimer()):(o.hide(),o.show())},tip_template:function(t){var n,r,i;return t.tip_class=t.tip_class||"",n=e(s.template.tip).addClass(t.tip_class),r=e.trim(e(t.li).html())+o.button_text(t.button_text)+s.template.link+o.timer_instance(t.index),i=e(s.template.wrapper),t.li.attr("data-aria-labelledby")&&i.attr("aria-labelledby",t.li.attr("data-aria-labelledby")),t.li.attr("data-aria-describedby")&&i.attr("aria-describedby",t.li.attr("data-aria-describedby")),n.append(i),n.first().attr("data-index",t.index),e(".joyride-content-wrapper",n).append(r),n[0]},timer_instance:function(t){var n;return t===0&&s.startTimerOnClick&&s.timer>0||s.timer===0?n="":n=o.outerHTML(e(s.template.timer)[0]),n},button_text:function(t){return s.nextButton?(t=e.trim(t)||"Next",t=o.outerHTML(e(s.template.button).append(t)[0])):t="",t},create:function(t){var n=t.$li.attr("data-button")||t.$li.attr("data-text"),r=t.$li.attr("class"),i=e(o.tip_template({tip_class:r,index:t.index,button_text:n,li:t.$li}));e(s.tipContainer).append(i)},show:function(t){var r={},i,u=[],a=0,f,l=null;if(s.$li===n||e.inArray(s.$li.index(),s.pauseAfter)===-1){s.paused?s.paused=!1:o.set_li(t),s.attempts=0;if(s.$li.length&&s.$target.length>0){t&&(s.preRideCallback(s.$li.index(),s.$next_tip),s.modal&&o.show_modal()),s.preStepCallback(s.$li.index(),s.$next_tip),u=(s.$li.data("options")||":").split(";"),a=u.length;for(i=a-1;i>=0;i--)f=u[i].split(":"),f.length===2&&(r[e.trim(f[0])]=e.trim(f[1]));s.tipSettings=e.extend({},s,r),s.tipSettings.tipLocationPattern=s.tipLocationPatterns[s.tipSettings.tipLocation],s.modal&&s.expose&&o.expose(),!/body/i.test(s.$target.selector)&&s.scroll&&o.scroll_to(),o.is_phone()?o.pos_phone(!0):o.pos_default(!0),l=e(".joyride-timer-indicator",s.$next_tip),/pop/i.test(s.tipAnimation)?(l.outerWidth(0),s.timer>0?(s.$next_tip.show(),l.animate({width:e(".joyride-timer-indicator-wrap",s.$next_tip).outerWidth()},s.timer)):s.$next_tip.show()):/fade/i.test(s.tipAnimation)&&(l.outerWidth(0),s.timer>0?(s.$next_tip.fadeIn(s.tipAnimationFadeSpeed),s.$next_tip.show(),l.animate({width:e(".joyride-timer-indicator-wrap",s.$next_tip).outerWidth()},s.timer)):s.$next_tip.fadeIn(s.tipAnimationFadeSpeed)),s.$current_tip=s.$next_tip,e(".joyride-next-tip",s.$current_tip).focus(),o.tabbable(s.$current_tip)}else s.$li&&s.$target.length<1?o.show():o.end()}else s.paused=!0},is_phone:function(){return i?i.mq("only screen and (max-width: 767px)"):s.$window.width()<767?!0:!1},support_localstorage:function(){return i?i.localstorage:!!t.localStorage},hide:function(){s.modal&&s.expose&&o.un_expose(),s.modal||e(".joyride-modal-bg").hide(),s.$current_tip.hide(),s.postStepCallback(s.$li.index(),s.$current_tip)},set_li:function(e){e?(s.$li=s.$tip_content.eq(s.startOffset),o.set_next_tip(),s.$current_tip=s.$next_tip):(s.$li=s.$li.next(),o.set_next_tip()),o.set_target()},set_next_tip:function(){s.$next_tip=e(".joyride-tip-guide[data-index="+s.$li.index()+"]")},set_target:function(){var t=s.$li.attr("data-class"),n=s.$li.attr("data-id"),r=function(){return n?e(s.document.getElementById(n)):t?e("."+t).filter(":visible").first():e("body")};s.$target=r()},scroll_to:function(){var t,n;t=s.$window.height()/2,n=Math.ceil(s.$target.offset().top-t+s.$next_tip.outerHeight()),e("html, body").stop().animate({scrollTop:n},s.scrollSpeed)},paused:function(){return e.inArray(s.$li.index()+1,s.pauseAfter)===-1?!0:!1},destroy:function(){e.isEmptyObject(s)||s.$document.off(".joyride"),e(t).off(".joyride"),e(".joyride-close-tip, .joyride-next-tip, .joyride-modal-bg").off(".joyride"),e(".joyride-tip-guide, .joyride-modal-bg").remove(),clearTimeout(s.automate),s={}},restart:function(){s.autoStart?(o.hide(),s.$li=n,o.show("init")):(!s.startTimerOnClick&&s.timer>0?(o.show("init"),o.startTimer()):o.show("init"),s.autoStart=!0)},pos_default:function(t){var n=Math.ceil(s.$window.height()/2),r=s.$next_tip.offset(),i=e(".joyride-nub",s.$next_tip),u=Math.ceil(i.outerWidth()/2),a=Math.ceil(i.outerHeight()/2),f=t||!1;f&&(s.$next_tip.css("visibility","hidden"),s.$next_tip.show());if(!/body/i.test(s.$target.selector)){var l=s.tipSettings.tipAdjustmentY?parseInt(s.tipSettings.tipAdjustmentY):0,c=s.tipSettings.tipAdjustmentX?parseInt(s.tipSettings.tipAdjustmentX):0;o.bottom()?(s.$next_tip.css({top:s.$target.offset().top+a+s.$target.outerHeight()+l,left:s.$target.offset().left+c}),/right/i.test(s.tipSettings.nubPosition)&&s.$next_tip.css("left",s.$target.offset().left-s.$next_tip.outerWidth()+s.$target.outerWidth()),o.nub_position(i,s.tipSettings.nubPosition,"top")):o.top()?(s.$next_tip.css({top:s.$target.offset().top-s.$next_tip.outerHeight()-a+l,left:s.$target.offset().left+c}),o.nub_position(i,s.tipSettings.nubPosition,"bottom")):o.right()?(s.$next_tip.css({top:s.$target.offset().top+l,left:s.$target.outerWidth()+s.$target.offset().left+u+c}),o.nub_position(i,s.tipSettings.nubPosition,"left")):o.left()&&(s.$next_tip.css({top:s.$target.offset().top+l,left:s.$target.offset().left-s.$next_tip.outerWidth()-u+c}),o.nub_position(i,s.tipSettings.nubPosition,"right")),!o.visible(o.corners(s.$next_tip))&&s.attempts<s.tipSettings.tipLocationPattern.length&&(i.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),s.tipSettings.tipLocation=s.tipSettings.tipLocationPattern[s.attempts],s.attempts++,o.pos_default(!0))}else s.$li.length&&o.pos_modal(i);f&&(s.$next_tip.hide(),s.$next_tip.css("visibility","visible"))},pos_phone:function(t){var n=s.$next_tip.outerHeight(),r=s.$next_tip.offset(),i=s.$target.outerHeight(),u=e(".joyride-nub",s.$next_tip),a=Math.ceil(u.outerHeight()/2),f=t||!1;u.removeClass("bottom").removeClass("top").removeClass("right").removeClass("left"),f&&(s.$next_tip.css("visibility","hidden"),s.$next_tip.show()),/body/i.test(s.$target.selector)?s.$li.length&&o.pos_modal(u):o.top()?(s.$next_tip.offset({top:s.$target.offset().top-n-a}),u.addClass("bottom")):(s.$next_tip.offset({top:s.$target.offset().top+i+a}),u.addClass("top")),f&&(s.$next_tip.hide(),s.$next_tip.css("visibility","visible"))},pos_modal:function(e){o.center(),e.hide(),o.show_modal()},show_modal:function(){e(".joyride-modal-bg").length<1&&e("body").append(s.template.modal).show(),/pop/i.test(s.tipAnimation)?e(".joyride-modal-bg").show():e(".joyride-modal-bg").fadeIn(s.tipAnimationFadeSpeed)},expose:function(){var n,r,i,u,a="expose-"+Math.floor(Math.random()*1e4);if(arguments.length>0&&arguments[0]instanceof e)i=arguments[0];else{if(!s.$target||!!/body/i.test(s.$target.selector))return!1;i=s.$target}if(i.length<1)return t.console&&console.error("element not valid",i),!1;n=e(s.template.expose),s.$body.append(n),n.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),r=e(s.template.exposeCover),u={zIndex:i.css("z-index"),position:i.css("position")},i.css("z-index",n.css("z-index")*1+1),u.position=="static"&&i.css("position","relative"),i.data("expose-css",u),r.css({top:i.offset().top,left:i.offset().left,width:i.outerWidth(!0),height:i.outerHeight(!0)}),s.$body.append(r),n.addClass(a),r.addClass(a),s.tipSettings.exposeClass&&(n.addClass(s.tipSettings.exposeClass),r.addClass(s.tipSettings.exposeClass)),i.data("expose",a),s.postExposeCallback(s.$li.index(),s.$next_tip,i),o.add_exposed(i)},un_expose:function(){var n,r,i,u,a=!1;if(arguments.length>0&&arguments[0]instanceof e)r=arguments[0];else{if(!s.$target||!!/body/i.test(s.$target.selector))return!1;r=s.$target}if(r.length<1)return t.console&&console.error("element not valid",r),!1;n=r.data("expose"),i=e("."+n),arguments.length>1&&(a=arguments[1]),a===!0?e(".joyride-expose-wrapper,.joyride-expose-cover").remove():i.remove(),u=r.data("expose-css"),u.zIndex=="auto"?r.css("z-index",""):r.css("z-index",u.zIndex),u.position!=r.css("position")&&(u.position=="static"?r.css("position",""):r.css("position",u.position)),r.removeData("expose"),r.removeData("expose-z-index"),o.remove_exposed(r)},add_exposed:function(t){s.exposed=s.exposed||[],t instanceof e?s.exposed.push(t[0]):typeof t=="string"&&s.exposed.push(t)},remove_exposed:function(t){var n;t instanceof e?n=t[0]:typeof t=="string"&&(n=t),s.exposed=s.exposed||[];for(var r=0;r<s.exposed.length;r++)if(s.exposed[r]==n){s.exposed.splice(r,1);return}},center:function(){var e=s.$window;return s.$next_tip.css({top:(e.height()-s.$next_tip.outerHeight())/2+e.scrollTop(),left:(e.width()-s.$next_tip.outerWidth())/2+e.scrollLeft()}),!0},bottom:function(){return/bottom/i.test(s.tipSettings.tipLocation)},top:function(){return/top/i.test(s.tipSettings.tipLocation)},right:function(){return/right/i.test(s.tipSettings.tipLocation)},left:function(){return/left/i.test(s.tipSettings.tipLocation)},corners:function(e){var t=s.$window,n=t.height()/2,r=Math.ceil(s.$target.offset().top-n+s.$next_tip.outerHeight()),i=t.width()+t.scrollLeft(),o=t.height()+r,u=t.height()+t.scrollTop(),a=t.scrollTop();return r<a&&(r<0?a=0:a=r),o>u&&(u=o),[e.offset().top<a,i<e.offset().left+e.outerWidth(),u<e.offset().top+e.outerHeight(),t.scrollLeft()>e.offset().left]},visible:function(e){var t=e.length;while(t--)if(e[t])return!1;return!0},nub_position:function(e,t,n){t==="auto"?e.addClass(n):e.addClass(t)},startTimer:function(){s.$li.length?s.automate=setTimeout(function(){o.hide(),o.show(),o.startTimer()},s.timer):clearTimeout(s.automate)},end:function(){s.cookieMonster&&e.cookie(s.cookieName,"ridden",{expires:365,domain:s.cookieDomain,path:s.cookiePath}),s.localStorage&&localStorage.setItem(s.localStorageKey,!0),s.timer>0&&clearTimeout(s.automate),s.modal&&s.expose&&o.un_expose(),s.$current_tip&&s.$current_tip.hide(),s.$li&&(s.postStepCallback(s.$li.index(),s.$current_tip),s.postRideCallback(s.$li.index(),s.$current_tip)),e(".joyride-modal-bg").hide()},jquery_check:function(){return e.isFunction(e.fn.on)?!0:(e.fn.on=function(e,t,n){return this.delegate(t,e,n)},e.fn.off=function(e,t,n){return this.undelegate(t,e,n)},!1)},outerHTML:function(e){return e.outerHTML||(new XMLSerializer).serializeToString(e)},version:function(){return s.version},tabbable:function(t){e(t).on("keydown",function(n){if(!n.isDefaultPrevented()&&n.keyCode&&n.keyCode===27){n.preventDefault(),o.end();return}if(n.keyCode!==9)return;var r=e(t).find(":tabbable"),i=r.filter(":first"),s=r.filter(":last");n.target===s[0]&&!n.shiftKey?(i.focus(1),n.preventDefault()):n.target===i[0]&&n.shiftKey&&(s.focus(1),n.preventDefault())})}};e.fn.joyride=function(t){if(o[t])return o[t].apply(this,Array.prototype.slice.call(arguments,1));if(typeof t=="object"||!t)return o.init.apply(this,arguments);e.error("Method "+t+" does not exist on jQuery.joyride")}})(jQuery,this);
;
/**
* @file
* Attaches behaviors for the Tour module's toolbar tab.
*/
(function ($, Backbone, Drupal, document) {
'use strict';
var queryString = decodeURI(window.location.search);
/**
* Attaches the tour's toolbar tab behavior.
*
* It uses the query string for:
* - tour: When ?tour=1 is present, the tour will start automatically after
* the page has loaded.
* - tips: Pass ?tips=class in the url to filter the available tips to the
* subset which match the given class.
*
* @example
* http://example.com/foo?tour=1&tips=bar
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attach tour functionality on `tour` events.
*/
Drupal.behaviors.tour = {
attach: function (context) {
$('body').once('tour').each(function () {
var model = new Drupal.tour.models.StateModel();
new Drupal.tour.views.ToggleTourView({
el: $(context).find('#toolbar-tab-tour'),
model: model
});
model
// Allow other scripts to respond to tour events.
.on('change:isActive', function (model, isActive) {
$(document).trigger((isActive) ? 'drupalTourStarted' : 'drupalTourStopped');
})
// Initialization: check whether a tour is available on the current
// page.
.set('tour', $(context).find('ol#tour'));
// Start the tour immediately if toggled via query string.
if (/tour=?/i.test(queryString)) {
model.set('isActive', true);
}
});
}
};
/**
* @namespace
*/
Drupal.tour = Drupal.tour || {
/**
* @namespace Drupal.tour.models
*/
models: {},
/**
* @namespace Drupal.tour.views
*/
views: {}
};
/**
* Backbone Model for tours.
*
* @constructor
*
* @augments Backbone.Model
*/
Drupal.tour.models.StateModel = Backbone.Model.extend(/** @lends Drupal.tour.models.StateModel# */{
/**
* @type {object}
*/
defaults: /** @lends Drupal.tour.models.StateModel# */{
/**
* Indicates whether the Drupal root window has a tour.
*
* @type {Array}
*/
tour: [],
/**
* Indicates whether the tour is currently running.
*
* @type {bool}
*/
isActive: false,
/**
* Indicates which tour is the active one (necessary to cleanly stop).
*
* @type {Array}
*/
activeTour: []
}
});
Drupal.tour.views.ToggleTourView = Backbone.View.extend(/** @lends Drupal.tour.views.ToggleTourView# */{
/**
* @type {object}
*/
events: {click: 'onClick'},
/**
* Handles edit mode toggle interactions.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change:tour change:isActive', this.render);
this.listenTo(this.model, 'change:isActive', this.toggleTour);
},
/**
* @inheritdoc
*
* @return {Drupal.tour.views.ToggleTourView}
* The `ToggleTourView` view.
*/
render: function () {
// Render the visibility.
this.$el.toggleClass('hidden', this._getTour().length === 0);
// Render the state.
var isActive = this.model.get('isActive');
this.$el.find('button')
.toggleClass('is-active', isActive)
.prop('aria-pressed', isActive);
return this;
},
/**
* Model change handler; starts or stops the tour.
*/
toggleTour: function () {
if (this.model.get('isActive')) {
var $tour = this._getTour();
this._removeIrrelevantTourItems($tour, this._getDocument());
var that = this;
if ($tour.find('li').length) {
$tour.joyride({
autoStart: true,
postRideCallback: function () { that.model.set('isActive', false); },
// HTML segments for tip layout.
template: {
link: '<a href=\"#close\" class=\"joyride-close-tip\">×</a>',
button: '<a href=\"#\" class=\"button button--primary joyride-next-tip\"></a>'
}
});
this.model.set({isActive: true, activeTour: $tour});
}
}
else {
this.model.get('activeTour').joyride('destroy');
this.model.set({isActive: false, activeTour: []});
}
},
/**
* Toolbar tab click event handler; toggles isActive.
*
* @param {jQuery.Event} event
* The click event.
*/
onClick: function (event) {
this.model.set('isActive', !this.model.get('isActive'));
event.preventDefault();
event.stopPropagation();
},
/**
* Gets the tour.
*
* @return {jQuery}
* A jQuery element pointing to a `<ol>` containing tour items.
*/
_getTour: function () {
return this.model.get('tour');
},
/**
* Gets the relevant document as a jQuery element.
*
* @return {jQuery}
* A jQuery element pointing to the document within which a tour would be
* started given the current state.
*/
_getDocument: function () {
return $(document);
},
/**
* Removes tour items for elements that don't have matching page elements.
*
* Or that are explicitly filtered out via the 'tips' query string.
*
* @example
* <caption>This will filter out tips that do not have a matching
* page element or don't have the "bar" class.</caption>
* http://example.com/foo?tips=bar
*
* @param {jQuery} $tour
* A jQuery element pointing to a `<ol>` containing tour items.
* @param {jQuery} $document
* A jQuery element pointing to the document within which the elements
* should be sought.
*
* @see Drupal.tour.views.ToggleTourView#_getDocument
*/
_removeIrrelevantTourItems: function ($tour, $document) {
var removals = false;
var tips = /tips=([^&]+)/.exec(queryString);
$tour
.find('li')
.each(function () {
var $this = $(this);
var itemId = $this.attr('data-id');
var itemClass = $this.attr('data-class');
// If the query parameter 'tips' is set, remove all tips that don't
// have the matching class.
if (tips && !$(this).hasClass(tips[1])) {
removals = true;
$this.remove();
return;
}
// Remove tip from the DOM if there is no corresponding page element.
if ((!itemId && !itemClass) ||
(itemId && $document.find('#' + itemId).length) ||
(itemClass && $document.find('.' + itemClass).length)) {
return;
}
removals = true;
$this.remove();
});
// If there were removals, we'll have to do some clean-up.
if (removals) {
var total = $tour.find('li').length;
if (!total) {
this.model.set({tour: []});
}
$tour
.find('li')
// Rebuild the progress data.
.each(function (index) {
var progress = Drupal.t('!tour_item of !total', {'!tour_item': index + 1, '!total': total});
$(this).find('.tour-progress').text(progress);
})
// Update the last item to have "End tour" as the button.
.eq(-1)
.attr('data-text', Drupal.t('End tour'));
}
}
});
})(jQuery, Backbone, Drupal, document);
;
/**
* @file
* Manages page tabbing modifications made by modules.
*/
/**
* Allow modules to respond to the constrain event.
*
* @event drupalTabbingConstrained
*/
/**
* Allow modules to respond to the tabbingContext release event.
*
* @event drupalTabbingContextReleased
*/
/**
* Allow modules to respond to the constrain event.
*
* @event drupalTabbingContextActivated
*/
/**
* Allow modules to respond to the constrain event.
*
* @event drupalTabbingContextDeactivated
*/
(function ($, Drupal) {
'use strict';
/**
* Provides an API for managing page tabbing order modifications.
*
* @constructor Drupal~TabbingManager
*/
function TabbingManager() {
/**
* Tabbing sets are stored as a stack. The active set is at the top of the
* stack. We use a JavaScript array as if it were a stack; we consider the
* first element to be the bottom and the last element to be the top. This
* allows us to use JavaScript's built-in Array.push() and Array.pop()
* methods.
*
* @type {Array.<Drupal~TabbingContext>}
*/
this.stack = [];
}
/**
* Add public methods to the TabbingManager class.
*/
$.extend(TabbingManager.prototype, /** @lends Drupal~TabbingManager# */{
/**
* Constrain tabbing to the specified set of elements only.
*
* Makes elements outside of the specified set of elements unreachable via
* the tab key.
*
* @param {jQuery} elements
* The set of elements to which tabbing should be constrained. Can also
* be a jQuery-compatible selector string.
*
* @return {Drupal~TabbingContext}
*
* @fires event:drupalTabbingConstrained
*/
constrain: function (elements) {
// Deactivate all tabbingContexts to prepare for the new constraint. A
// tabbingContext instance will only be reactivated if the stack is
// unwound to it in the _unwindStack() method.
var il = this.stack.length;
for (var i = 0; i < il; i++) {
this.stack[i].deactivate();
}
// The "active tabbing set" are the elements tabbing should be constrained
// to.
var $elements = $(elements).find(':tabbable').addBack(':tabbable');
var tabbingContext = new TabbingContext({
// The level is the current height of the stack before this new
// tabbingContext is pushed on top of the stack.
level: this.stack.length,
$tabbableElements: $elements
});
this.stack.push(tabbingContext);
// Activates the tabbingContext; this will manipulate the DOM to constrain
// tabbing.
tabbingContext.activate();
// Allow modules to respond to the constrain event.
$(document).trigger('drupalTabbingConstrained', tabbingContext);
return tabbingContext;
},
/**
* Restores a former tabbingContext when an active one is released.
*
* The TabbingManager stack of tabbingContext instances will be unwound
* from the top-most released tabbingContext down to the first non-released
* tabbingContext instance. This non-released instance is then activated.
*/
release: function () {
// Unwind as far as possible: find the topmost non-released
// tabbingContext.
var toActivate = this.stack.length - 1;
while (toActivate >= 0 && this.stack[toActivate].released) {
toActivate--;
}
// Delete all tabbingContexts after the to be activated one. They have
// already been deactivated, so their effect on the DOM has been reversed.
this.stack.splice(toActivate + 1);
// Get topmost tabbingContext, if one exists, and activate it.
if (toActivate >= 0) {
this.stack[toActivate].activate();
}
},
/**
* Makes all elements outside the of the tabbingContext's set untabbable.
*
* Elements made untabbable have their original tabindex and autofocus
* values stored so that they might be restored later when this
* tabbingContext is deactivated.
*
* @param {Drupal~TabbingContext} tabbingContext
* The TabbingContext instance that has been activated.
*/
activate: function (tabbingContext) {
var $set = tabbingContext.$tabbableElements;
var level = tabbingContext.level;
// Determine which elements are reachable via tabbing by default.
var $disabledSet = $(':tabbable')
// Exclude elements of the active tabbing set.
.not($set);
// Set the disabled set on the tabbingContext.
tabbingContext.$disabledElements = $disabledSet;
// Record the tabindex for each element, so we can restore it later.
var il = $disabledSet.length;
for (var i = 0; i < il; i++) {
this.recordTabindex($disabledSet.eq(i), level);
}
// Make all tabbable elements outside of the active tabbing set
// unreachable.
$disabledSet
.prop('tabindex', -1)
.prop('autofocus', false);
// Set focus on an element in the tabbingContext's set of tabbable
// elements. First, check if there is an element with an autofocus
// attribute. Select the last one from the DOM order.
var $hasFocus = $set.filter('[autofocus]').eq(-1);
// If no element in the tabbable set has an autofocus attribute, select
// the first element in the set.
if ($hasFocus.length === 0) {
$hasFocus = $set.eq(0);
}
$hasFocus.trigger('focus');
},
/**
* Restores that tabbable state of a tabbingContext's disabled elements.
*
* Elements that were made untabbable have their original tabindex and
* autofocus values restored.
*
* @param {Drupal~TabbingContext} tabbingContext
* The TabbingContext instance that has been deactivated.
*/
deactivate: function (tabbingContext) {
var $set = tabbingContext.$disabledElements;
var level = tabbingContext.level;
var il = $set.length;
for (var i = 0; i < il; i++) {
this.restoreTabindex($set.eq(i), level);
}
},
/**
* Records the tabindex and autofocus values of an untabbable element.
*
* @param {jQuery} $el
* The set of elements that have been disabled.
* @param {number} level
* The stack level for which the tabindex attribute should be recorded.
*/
recordTabindex: function ($el, level) {
var tabInfo = $el.data('drupalOriginalTabIndices') || {};
tabInfo[level] = {
tabindex: $el[0].getAttribute('tabindex'),
autofocus: $el[0].hasAttribute('autofocus')
};
$el.data('drupalOriginalTabIndices', tabInfo);
},
/**
* Restores the tabindex and autofocus values of a reactivated element.
*
* @param {jQuery} $el
* The element that is being reactivated.
* @param {number} level
* The stack level for which the tabindex attribute should be restored.
*/
restoreTabindex: function ($el, level) {
var tabInfo = $el.data('drupalOriginalTabIndices');
if (tabInfo && tabInfo[level]) {
var data = tabInfo[level];
if (data.tabindex) {
$el[0].setAttribute('tabindex', data.tabindex);
}
// If the element did not have a tabindex at this stack level then
// remove it.
else {
$el[0].removeAttribute('tabindex');
}
if (data.autofocus) {
$el[0].setAttribute('autofocus', 'autofocus');
}
// Clean up $.data.
if (level === 0) {
// Remove all data.
$el.removeData('drupalOriginalTabIndices');
}
else {
// Remove the data for this stack level and higher.
var levelToDelete = level;
while (tabInfo.hasOwnProperty(levelToDelete)) {
delete tabInfo[levelToDelete];
levelToDelete++;
}
$el.data('drupalOriginalTabIndices', tabInfo);
}
}
}
});
/**
* Stores a set of tabbable elements.
*
* This constraint can be removed with the release() method.
*
* @constructor Drupal~TabbingContext
*
* @param {object} options
* A set of initiating values
* @param {number} options.level
* The level in the TabbingManager's stack of this tabbingContext.
* @param {jQuery} options.$tabbableElements
* The DOM elements that should be reachable via the tab key when this
* tabbingContext is active.
* @param {jQuery} options.$disabledElements
* The DOM elements that should not be reachable via the tab key when this
* tabbingContext is active.
* @param {bool} options.released
* A released tabbingContext can never be activated again. It will be
* cleaned up when the TabbingManager unwinds its stack.
* @param {bool} options.active
* When true, the tabbable elements of this tabbingContext will be reachable
* via the tab key and the disabled elements will not. Only one
* tabbingContext can be active at a time.
*/
function TabbingContext(options) {
$.extend(this, /** @lends Drupal~TabbingContext# */{
/**
* @type {?number}
*/
level: null,
/**
* @type {jQuery}
*/
$tabbableElements: $(),
/**
* @type {jQuery}
*/
$disabledElements: $(),
/**
* @type {bool}
*/
released: false,
/**
* @type {bool}
*/
active: false
}, options);
}
/**
* Add public methods to the TabbingContext class.
*/
$.extend(TabbingContext.prototype, /** @lends Drupal~TabbingContext# */{
/**
* Releases this TabbingContext.
*
* Once a TabbingContext object is released, it can never be activated
* again.
*
* @fires event:drupalTabbingContextReleased
*/
release: function () {
if (!this.released) {
this.deactivate();
this.released = true;
Drupal.tabbingManager.release(this);
// Allow modules to respond to the tabbingContext release event.
$(document).trigger('drupalTabbingContextReleased', this);
}
},
/**
* Activates this TabbingContext.
*
* @fires event:drupalTabbingContextActivated
*/
activate: function () {
// A released TabbingContext object can never be activated again.
if (!this.active && !this.released) {
this.active = true;
Drupal.tabbingManager.activate(this);
// Allow modules to respond to the constrain event.
$(document).trigger('drupalTabbingContextActivated', this);
}
},
/**
* Deactivates this TabbingContext.
*
* @fires event:drupalTabbingContextDeactivated
*/
deactivate: function () {
if (this.active) {
this.active = false;
Drupal.tabbingManager.deactivate(this);
// Allow modules to respond to the constrain event.
$(document).trigger('drupalTabbingContextDeactivated', this);
}
}
});
// Mark this behavior as processed on the first pass and return if it is
// already processed.
if (Drupal.tabbingManager) {
return;
}
/**
* @type {Drupal~TabbingManager}
*/
Drupal.tabbingManager = new TabbingManager();
}(jQuery, Drupal));
;
/**
* @file
* Attaches behaviors for the Contextual module's edit toolbar tab.
*/
(function ($, Drupal, Backbone) {
'use strict';
var strings = {
tabbingReleased: Drupal.t('Tabbing is no longer constrained by the Contextual module.'),
tabbingConstrained: Drupal.t('Tabbing is constrained to a set of @contextualsCount and the edit mode toggle.'),
pressEsc: Drupal.t('Press the esc key to exit.')
};
/**
* Initializes a contextual link: updates its DOM, sets up model and views.
*
* @param {HTMLElement} context
* A contextual links DOM element as rendered by the server.
*/
function initContextualToolbar(context) {
if (!Drupal.contextual || !Drupal.contextual.collection) {
return;
}
var contextualToolbar = Drupal.contextualToolbar;
var model = contextualToolbar.model = new contextualToolbar.StateModel({
// Checks whether localStorage indicates we should start in edit mode
// rather than view mode.
// @see Drupal.contextualToolbar.VisualView.persist
isViewing: localStorage.getItem('Drupal.contextualToolbar.isViewing') !== 'false'
}, {
contextualCollection: Drupal.contextual.collection
});
var viewOptions = {
el: $('.toolbar .toolbar-bar .contextual-toolbar-tab'),
model: model,
strings: strings
};
new contextualToolbar.VisualView(viewOptions);
new contextualToolbar.AuralView(viewOptions);
}
/**
* Attaches contextual's edit toolbar tab behavior.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches contextual toolbar behavior on a contextualToolbar-init event.
*/
Drupal.behaviors.contextualToolbar = {
attach: function (context) {
if ($('body').once('contextualToolbar-init').length) {
initContextualToolbar(context);
}
}
};
/**
* Namespace for the contextual toolbar.
*
* @namespace
*/
Drupal.contextualToolbar = {
/**
* The {@link Drupal.contextualToolbar.StateModel} instance.
*
* @type {?Drupal.contextualToolbar.StateModel}
*/
model: null
};
})(jQuery, Drupal, Backbone);
;
/**
* @file
* A Backbone Model for the state of Contextual module's edit toolbar tab.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextualToolbar.StateModel = Backbone.Model.extend(/** @lends Drupal.contextualToolbar.StateModel# */{
/**
* @type {object}
*
* @prop {bool} isViewing
* @prop {bool} isVisible
* @prop {number} contextualCount
* @prop {Drupal~TabbingContext} tabbingContext
*/
defaults: /** @lends Drupal.contextualToolbar.StateModel# */{
/**
* Indicates whether the toggle is currently in "view" or "edit" mode.
*
* @type {bool}
*/
isViewing: true,
/**
* Indicates whether the toggle should be visible or hidden. Automatically
* calculated, depends on contextualCount.
*
* @type {bool}
*/
isVisible: false,
/**
* Tracks how many contextual links exist on the page.
*
* @type {number}
*/
contextualCount: 0,
/**
* A TabbingContext object as returned by {@link Drupal~TabbingManager}:
* the set of tabbable elements when edit mode is enabled.
*
* @type {?Drupal~TabbingContext}
*/
tabbingContext: null
},
/**
* Models the state of the edit mode toggle.
*
* @constructs
*
* @augments Backbone.Model
*
* @param {object} attrs
* Attributes for the backbone model.
* @param {object} options
* An object with the following option:
* @param {Backbone.collection} options.contextualCollection
* The collection of {@link Drupal.contextual.StateModel} models that
* represent the contextual links on the page.
*/
initialize: function (attrs, options) {
// Respond to new/removed contextual links.
this.listenTo(options.contextualCollection, 'reset remove add', this.countContextualLinks);
this.listenTo(options.contextualCollection, 'add', this.lockNewContextualLinks);
// Automatically determine visibility.
this.listenTo(this, 'change:contextualCount', this.updateVisibility);
// Whenever edit mode is toggled, lock all contextual links.
this.listenTo(this, 'change:isViewing', function (model, isViewing) {
options.contextualCollection.each(function (contextualModel) {
contextualModel.set('isLocked', !isViewing);
});
});
},
/**
* Tracks the number of contextual link models in the collection.
*
* @param {Drupal.contextual.StateModel} contextualModel
* The contextual links model that was added or removed.
* @param {Backbone.Collection} contextualCollection
* The collection of contextual link models.
*/
countContextualLinks: function (contextualModel, contextualCollection) {
this.set('contextualCount', contextualCollection.length);
},
/**
* Lock newly added contextual links if edit mode is enabled.
*
* @param {Drupal.contextual.StateModel} contextualModel
* The contextual links model that was added.
* @param {Backbone.Collection} [contextualCollection]
* The collection of contextual link models.
*/
lockNewContextualLinks: function (contextualModel, contextualCollection) {
if (!this.get('isViewing')) {
contextualModel.set('isLocked', true);
}
},
/**
* Automatically updates visibility of the view/edit mode toggle.
*/
updateVisibility: function () {
this.set('isVisible', this.get('contextualCount') > 0);
}
});
})(Drupal, Backbone);
;
/**
* @file
* A Backbone View that provides the aural view of the edit mode toggle.
*/
(function ($, Drupal, Backbone, _) {
'use strict';
Drupal.contextualToolbar.AuralView = Backbone.View.extend(/** @lends Drupal.contextualToolbar.AuralView# */{
/**
* Tracks whether the tabbing constraint announcement has been read once.
*
* @type {bool}
*/
announcedOnce: false,
/**
* Renders the aural view of the edit mode toggle (screen reader support).
*
* @constructs
*
* @augments Backbone.View
*
* @param {object} options
* Options for the view.
*/
initialize: function (options) {
this.options = options;
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'change:isViewing', this.manageTabbing);
$(document).on('keyup', _.bind(this.onKeypress, this));
},
/**
* @inheritdoc
*
* @return {Drupal.contextualToolbar.AuralView}
* The current contextual toolbar aural view.
*/
render: function () {
// Render the state.
this.$el.find('button').attr('aria-pressed', !this.model.get('isViewing'));
return this;
},
/**
* Limits tabbing to the contextual links and edit mode toolbar tab.
*/
manageTabbing: function () {
var tabbingContext = this.model.get('tabbingContext');
// Always release an existing tabbing context.
if (tabbingContext) {
tabbingContext.release();
Drupal.announce(this.options.strings.tabbingReleased);
}
// Create a new tabbing context when edit mode is enabled.
if (!this.model.get('isViewing')) {
tabbingContext = Drupal.tabbingManager.constrain($('.contextual-toolbar-tab, .contextual'));
this.model.set('tabbingContext', tabbingContext);
this.announceTabbingConstraint();
this.announcedOnce = true;
}
},
/**
* Announces the current tabbing constraint.
*/
announceTabbingConstraint: function () {
var strings = this.options.strings;
Drupal.announce(Drupal.formatString(strings.tabbingConstrained, {
'@contextualsCount': Drupal.formatPlural(Drupal.contextual.collection.length, '@count contextual link', '@count contextual links')
}));
Drupal.announce(strings.pressEsc);
},
/**
* Responds to esc and tab key press events.
*
* @param {jQuery.Event} event
* The keypress event.
*/
onKeypress: function (event) {
// The first tab key press is tracked so that an annoucement about tabbing
// constraints can be raised if edit mode is enabled when the page is
// loaded.
if (!this.announcedOnce && event.keyCode === 9 && !this.model.get('isViewing')) {
this.announceTabbingConstraint();
// Set announce to true so that this conditional block won't run again.
this.announcedOnce = true;
}
// Respond to the ESC key. Exit out of edit mode.
if (event.keyCode === 27) {
this.model.set('isViewing', true);
}
}
});
})(jQuery, Drupal, Backbone, _);
;
/**
* @file
* A Backbone View that provides the visual view of the edit mode toggle.
*/
(function (Drupal, Backbone) {
'use strict';
Drupal.contextualToolbar.VisualView = Backbone.View.extend(/** @lends Drupal.contextualToolbar.VisualView# */{
/**
* Events for the Backbone view.
*
* @return {object}
* A mapping of events to be used in the view.
*/
events: function () {
// Prevents delay and simulated mouse events.
var touchEndToClick = function (event) {
event.preventDefault();
event.target.click();
};
return {
click: function () {
this.model.set('isViewing', !this.model.get('isViewing'));
},
touchend: touchEndToClick
};
},
/**
* Renders the visual view of the edit mode toggle.
*
* Listens to mouse & touch and handles edit mode toggle interactions.
*
* @constructs
*
* @augments Backbone.View
*/
initialize: function () {
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'change:isViewing', this.persist);
},
/**
* @inheritdoc
*
* @return {Drupal.contextualToolbar.VisualView}
* The current contextual toolbar visual view.
*/
render: function () {
// Render the visibility.
this.$el.toggleClass('hidden', !this.model.get('isVisible'));
// Render the state.
this.$el.find('button').toggleClass('is-active', !this.model.get('isViewing'));
return this;
},
/**
* Model change handler; persists the isViewing value to localStorage.
*
* `isViewing === true` is the default, so only stores in localStorage when
* it's not the default value (i.e. false).
*
* @param {Drupal.contextualToolbar.StateModel} model
* A {@link Drupal.contextualToolbar.StateModel} model.
* @param {bool} isViewing
* The value of the isViewing attribute in the model.
*/
persist: function (model, isViewing) {
if (!isViewing) {
localStorage.setItem('Drupal.contextualToolbar.isViewing', 'false');
}
else {
localStorage.removeItem('Drupal.contextualToolbar.isViewing');
}
}
});
})(Drupal, Backbone);
;
/**
* @file
* Replaces the home link in toolbar with a back to site link.
*/
(function ($, Drupal, drupalSettings) {
'use strict';
var pathInfo = drupalSettings.path;
var escapeAdminPath = sessionStorage.getItem('escapeAdminPath');
var windowLocation = window.location;
// Saves the last non-administrative page in the browser to be able to link
// back to it when browsing administrative pages. If there is a destination
// parameter there is not need to save the current path because the page is
// loaded within an existing "workflow".
if (!pathInfo.currentPathIsAdmin && !/destination=/.test(windowLocation.search)) {
sessionStorage.setItem('escapeAdminPath', windowLocation);
}
/**
* Replaces the "Home" link with "Back to site" link.
*
* Back to site link points to the last non-administrative page the user
* visited within the same browser tab.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the replacement functionality to the toolbar-escape-admin element.
*/
Drupal.behaviors.escapeAdmin = {
attach: function () {
var $toolbarEscape = $('[data-toolbar-escape-admin]').once('escapeAdmin');
if ($toolbarEscape.length && pathInfo.currentPathIsAdmin) {
if (escapeAdminPath !== null) {
$toolbarEscape.attr('href', escapeAdminPath);
}
else {
$toolbarEscape.text(Drupal.t('Home'));
}
$toolbarEscape.closest('.toolbar-tab').removeClass('hidden');
}
}
};
})(jQuery, Drupal, drupalSettings);
;
|
app/components/Layout/ContentGrid/index.js | hlex/vms | import React, { Component } from 'react';
class ContentGrid extends Component {
render() {
return (
<div className="content-grid-wrapper">
{
this.props.children
}
</div>
);
}
}
export default ContentGrid;
|
examples/FlatButton.js | 15lyfromsaturn/react-materialize | import React from 'react';
import Button from '../src/Button';
export default
<Button flat waves='light'>Button</Button>;
|
ajax/libs/rxjs/2.4.9/rx.lite.js | joeyparrish/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) {
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(); }
};
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
/** 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.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime);
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/**
* 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);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var 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)
};
/**
* 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;
});
};
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);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.count = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.count, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for 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 = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
//deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
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, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return new AnonymousObservable(function (observer) {
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 () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (observer) {
function handler() {
var results = arguments;
if (selector) {
try {
results = selector(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(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.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* 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) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onCompleted();
else
this.queue.push(Rx.Notification.createOnCompleted());
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0)
this.subject.onError(error);
else
this.queue.push(Rx.Notification.createOnError(error));
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value));
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while ((this.queue.length >= numberOfItems && numberOfItems > 0) ||
(this.queue.length > 0 && this.queue[0].kind !== 'N')) {
var first = this.queue.shift();
first.accept(this.subject);
if (first.kind === 'N') numberOfItems--;
else { this.disposeCurrentRequest(); this.queue = []; }
}
return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0};
}
//TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function
//if (this.hasFailed) {
// this.subject.onError(this.error);
//} else if (this.hasCompleted) {
// this.subject.onCompleted();
//}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable;
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
/**
* 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(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, 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));
|
app/__tests__/index.android.js | alex-friedl/crossplatform-push-notifications-example | import 'react-native';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
import React from 'react';
import Index from '../index';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
ajax/libs/ag-grid/4.0.6/lib/utils.js | iwdmb/cdnjs | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.0.6
* @link http://www.ag-grid.com/
* @license MIT
*/
var FUNCTION_STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var FUNCTION_ARGUMENT_NAMES = /([^\s,]+)/g;
var Utils = (function () {
function Utils() {
}
Utils.iterateObject = function (object, callback) {
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = object[key];
callback(key, value);
}
};
Utils.cloneObject = function (object) {
var copy = {};
var keys = Object.keys(object);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = object[key];
copy[key] = value;
}
return copy;
};
Utils.map = function (array, callback) {
var result = [];
for (var i = 0; i < array.length; i++) {
var item = array[i];
var mappedItem = callback(item);
result.push(mappedItem);
}
return result;
};
Utils.mapObject = function (object, callback) {
var result = [];
Utils.iterateObject(object, function (key, value) {
result.push(callback(value));
});
return result;
};
Utils.forEach = function (array, callback) {
if (!array) {
return;
}
for (var i = 0; i < array.length; i++) {
var value = array[i];
callback(value, i);
}
};
Utils.filter = function (array, callback) {
var result = [];
array.forEach(function (item) {
if (callback(item)) {
result.push(item);
}
});
return result;
};
Utils.assign = function (object, source) {
Utils.iterateObject(source, function (key, value) {
object[key] = value;
});
};
Utils.getFunctionParameters = function (func) {
var fnStr = func.toString().replace(FUNCTION_STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(FUNCTION_ARGUMENT_NAMES);
if (result === null) {
return [];
}
else {
return result;
}
};
Utils.find = function (collection, predicate, value) {
if (collection === null || collection === undefined) {
return null;
}
var firstMatchingItem;
for (var i = 0; i < collection.length; i++) {
var item = collection[i];
if (typeof predicate === 'string') {
if (item[predicate] === value) {
firstMatchingItem = item;
break;
}
}
else {
var callback = predicate;
if (callback(item)) {
firstMatchingItem = item;
break;
}
}
}
return firstMatchingItem;
};
Utils.toStrings = function (array) {
return this.map(array, function (item) {
if (item === undefined || item === null || !item.toString) {
return null;
}
else {
return item.toString();
}
});
};
Utils.iterateArray = function (array, callback) {
for (var index = 0; index < array.length; index++) {
var value = array[index];
callback(value, index);
}
};
//Returns true if it is a DOM node
//taken from: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
Utils.isNode = function (o) {
return (typeof Node === "function" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string");
};
//Returns true if it is a DOM element
//taken from: http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
Utils.isElement = function (o) {
return (typeof HTMLElement === "function" ? o instanceof HTMLElement :
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string");
};
Utils.isNodeOrElement = function (o) {
return this.isNode(o) || this.isElement(o);
};
//adds all type of change listeners to an element, intended to be a text field
Utils.addChangeListener = function (element, listener) {
element.addEventListener("changed", listener);
element.addEventListener("paste", listener);
element.addEventListener("input", listener);
// IE doesn't fire changed for special keys (eg delete, backspace), so need to
// listen for this further ones
element.addEventListener("keydown", listener);
element.addEventListener("keyup", listener);
};
//if value is undefined, null or blank, returns null, otherwise returns the value
Utils.makeNull = function (value) {
if (value === null || value === undefined || value === "") {
return null;
}
else {
return value;
}
};
Utils.missing = function (value) {
return !this.exists(value);
};
Utils.missingOrEmpty = function (value) {
return this.missing(value) || value.length === 0;
};
Utils.exists = function (value) {
if (value === null || value === undefined || value === '') {
return false;
}
else {
return true;
}
};
Utils.existsAndNotEmpty = function (value) {
return this.exists(value) && value.length > 0;
};
Utils.removeAllChildren = function (node) {
if (node) {
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}
};
Utils.removeElement = function (parent, cssSelector) {
this.removeFromParent(parent.querySelector(cssSelector));
};
Utils.removeFromParent = function (node) {
if (node && node.parentNode) {
node.parentNode.removeChild(node);
}
};
Utils.isVisible = function (element) {
return (element.offsetParent !== null);
};
/**
* loads the template and returns it as an element. makes up for no simple way in
* the dom api to load html directly, eg we cannot do this: document.createElement(template)
*/
Utils.loadTemplate = function (template) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = template;
return tempDiv.firstChild;
};
Utils.addOrRemoveCssClass = function (element, className, addOrRemove) {
if (addOrRemove) {
this.addCssClass(element, className);
}
else {
this.removeCssClass(element, className);
}
};
Utils.callIfPresent = function (func) {
if (func) {
func();
}
};
Utils.addCssClass = function (element, className) {
var _this = this;
if (!className || className.length === 0) {
return;
}
if (className.indexOf(' ') >= 0) {
className.split(' ').forEach(function (value) { return _this.addCssClass(element, value); });
return;
}
if (element.classList) {
element.classList.add(className);
}
else {
if (element.className && element.className.length > 0) {
var cssClasses = element.className.split(' ');
if (cssClasses.indexOf(className) < 0) {
cssClasses.push(className);
element.className = cssClasses.join(' ');
}
}
else {
element.className = className;
}
}
};
Utils.offsetHeight = function (element) {
return element && element.clientHeight ? element.clientHeight : 0;
};
Utils.offsetWidth = function (element) {
return element && element.clientWidth ? element.clientWidth : 0;
};
Utils.removeCssClass = function (element, className) {
if (element.className && element.className.length > 0) {
var cssClasses = element.className.split(' ');
var index = cssClasses.indexOf(className);
if (index >= 0) {
cssClasses.splice(index, 1);
element.className = cssClasses.join(' ');
}
}
};
Utils.removeFromArray = function (array, object) {
if (array.indexOf(object) >= 0) {
array.splice(array.indexOf(object), 1);
}
};
Utils.defaultComparator = function (valueA, valueB) {
var valueAMissing = valueA === null || valueA === undefined;
var valueBMissing = valueB === null || valueB === undefined;
if (valueAMissing && valueBMissing) {
return 0;
}
if (valueAMissing) {
return -1;
}
if (valueBMissing) {
return 1;
}
if (valueA < valueB) {
return -1;
}
else if (valueA > valueB) {
return 1;
}
else {
return 0;
}
};
Utils.formatWidth = function (width) {
if (typeof width === "number") {
return width + "px";
}
else {
return width;
}
};
Utils.formatNumberTwoDecimalPlacesAndCommas = function (value) {
// took this from: http://blog.tompawlak.org/number-currency-formatting-javascript
if (typeof value === 'number') {
return (Math.round(value * 100) / 100).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
else {
return '';
}
};
/**
* Tries to use the provided renderer.
*/
Utils.useRenderer = function (eParent, eRenderer, params) {
var resultFromRenderer = eRenderer(params);
//TypeScript type inference magic
if (typeof resultFromRenderer === 'string') {
var eTextSpan = document.createElement('span');
eTextSpan.innerHTML = resultFromRenderer;
eParent.appendChild(eTextSpan);
}
else if (this.isNodeOrElement(resultFromRenderer)) {
//a dom node or element was returned, so add child
eParent.appendChild(resultFromRenderer);
}
else {
if (this.exists(resultFromRenderer)) {
console.warn('ag-Grid: result from render should be either a string or a DOM object, got ' + typeof resultFromRenderer);
}
}
};
/**
* If icon provided, use this (either a string, or a function callback).
* if not, then use the second parameter, which is the svgFactory function
*/
Utils.createIcon = function (iconName, gridOptionsWrapper, column, svgFactoryFunc) {
var eResult = document.createElement('span');
eResult.appendChild(this.createIconNoSpan(iconName, gridOptionsWrapper, column, svgFactoryFunc));
return eResult;
};
Utils.createIconNoSpan = function (iconName, gridOptionsWrapper, colDefWrapper, svgFactoryFunc) {
var userProvidedIcon;
// check col for icon first
if (colDefWrapper && colDefWrapper.getColDef().icons) {
userProvidedIcon = colDefWrapper.getColDef().icons[iconName];
}
// it not in col, try grid options
if (!userProvidedIcon && gridOptionsWrapper.getIcons()) {
userProvidedIcon = gridOptionsWrapper.getIcons()[iconName];
}
// now if user provided, use it
if (userProvidedIcon) {
var rendererResult;
if (typeof userProvidedIcon === 'function') {
rendererResult = userProvidedIcon();
}
else if (typeof userProvidedIcon === 'string') {
rendererResult = userProvidedIcon;
}
else {
throw 'icon from grid options needs to be a string or a function';
}
if (typeof rendererResult === 'string') {
return this.loadTemplate(rendererResult);
}
else if (this.isNodeOrElement(rendererResult)) {
return rendererResult;
}
else {
throw 'iconRenderer should return back a string or a dom object';
}
}
else {
// otherwise we use the built in icon
return svgFactoryFunc();
}
};
Utils.addStylesToElement = function (eElement, styles) {
if (!styles) {
return;
}
Object.keys(styles).forEach(function (key) {
eElement.style[key] = styles[key];
});
};
Utils.getScrollbarWidth = function () {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
};
Utils.isKeyPressed = function (event, keyToCheck) {
var pressedKey = event.which || event.keyCode;
return pressedKey === keyToCheck;
};
Utils.setVisible = function (element, visible, visibleStyle) {
if (visible) {
if (this.exists(visibleStyle)) {
element.style.display = visibleStyle;
}
else {
element.style.display = 'inline';
}
}
else {
element.style.display = 'none';
}
};
Utils.isBrowserIE = function () {
if (this.isIE === undefined) {
this.isIE = false || !!document.documentMode; // At least IE6
}
return this.isIE;
};
Utils.isBrowserSafari = function () {
if (this.isSafari === undefined) {
this.isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
}
return this.isSafari;
};
// taken from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
Utils.getBodyWidth = function () {
if (document.body) {
return document.body.clientWidth;
}
if (window.innerHeight) {
return window.innerWidth;
}
if (document.documentElement && document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
}
return -1;
};
// taken from: http://stackoverflow.com/questions/1038727/how-to-get-browser-width-using-javascript-code
Utils.getBodyHeight = function () {
if (document.body) {
return document.body.clientHeight;
}
if (window.innerHeight) {
return window.innerHeight;
}
if (document.documentElement && document.documentElement.clientHeight) {
return document.documentElement.clientHeight;
}
return -1;
};
Utils.setCheckboxState = function (eCheckbox, state) {
if (typeof state === 'boolean') {
eCheckbox.checked = state;
eCheckbox.indeterminate = false;
}
else {
// isNodeSelected returns back undefined if it's a group and the children
// are a mix of selected and unselected
eCheckbox.indeterminate = true;
}
};
Utils.traverseNodesWithKey = function (nodes, callback) {
var keyParts = [];
recursiveSearchNodes(nodes);
function recursiveSearchNodes(nodes) {
nodes.forEach(function (node) {
if (node.group) {
keyParts.push(node.key);
var key = keyParts.join('|');
callback(node, key);
recursiveSearchNodes(node.children);
keyParts.pop();
}
});
}
};
// Taken from here: https://github.com/facebook/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
/**
* Mouse wheel (and 2-finger trackpad) support on the web sucks. It is
* complicated, thus this doc is long and (hopefully) detailed enough to answer
* your questions.
*
* If you need to react to the mouse wheel in a predictable way, this code is
* like your bestest friend. * hugs *
*
* As of today, there are 4 DOM event types you can listen to:
*
* 'wheel' -- Chrome(31+), FF(17+), IE(9+)
* 'mousewheel' -- Chrome, IE(6+), Opera, Safari
* 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!
* 'DOMMouseScroll' -- FF(0.9.7+) since 2003
*
* So what to do? The is the best:
*
* normalizeWheel.getEventType();
*
* In your event callback, use this code to get sane interpretation of the
* deltas. This code will return an object with properties:
*
* spinX -- normalized spin speed (use for zoom) - x plane
* spinY -- " - y plane
* pixelX -- normalized distance (to pixels) - x plane
* pixelY -- " - y plane
*
* Wheel values are provided by the browser assuming you are using the wheel to
* scroll a web page by a number of lines or pixels (or pages). Values can vary
* significantly on different platforms and browsers, forgetting that you can
* scroll at different speeds. Some devices (like trackpads) emit more events
* at smaller increments with fine granularity, and some emit massive jumps with
* linear speed or acceleration.
*
* This code does its best to normalize the deltas for you:
*
* - spin is trying to normalize how far the wheel was spun (or trackpad
* dragged). This is super useful for zoom support where you want to
* throw away the chunky scroll steps on the PC and make those equal to
* the slow and smooth tiny steps on the Mac. Key data: This code tries to
* resolve a single slow step on a wheel to 1.
*
* - pixel is normalizing the desired scroll delta in pixel units. You'll
* get the crazy differences between browsers, but at least it'll be in
* pixels!
*
* - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This
* should translate to positive value zooming IN, negative zooming OUT.
* This matches the newer 'wheel' event.
*
* Why are there spinX, spinY (or pixels)?
*
* - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn
* with a mouse. It results in side-scrolling in the browser by default.
*
* - spinY is what you expect -- it's the classic axis of a mouse wheel.
*
* - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and
* probably is by browsers in conjunction with fancy 3D controllers .. but
* you know.
*
* Implementation info:
*
* Examples of 'wheel' event if you scroll slowly (down) by one step with an
* average mouse:
*
* OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)
* OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)
* OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)
* Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)
* Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)
*
* On the trackpad:
*
* OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)
* OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)
*
* On other/older browsers.. it's more complicated as there can be multiple and
* also missing delta values.
*
* The 'wheel' event is more standard:
*
* http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents
*
* The basics is that it includes a unit, deltaMode (pixels, lines, pages), and
* deltaX, deltaY and deltaZ. Some browsers provide other values to maintain
* backward compatibility with older events. Those other values help us
* better normalize spin speed. Example of what the browsers provide:
*
* | event.wheelDelta | event.detail
* ------------------+------------------+--------------
* Safari v5/OS X | -120 | 0
* Safari v5/Win7 | -120 | 0
* Chrome v17/OS X | -120 | 0
* Chrome v17/Win7 | -120 | 0
* IE9/Win7 | -120 | undefined
* Firefox v4/OS X | undefined | 1
* Firefox v4/Win7 | undefined | 3
*
*/
Utils.normalizeWheel = function (event) {
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
// spinX, spinY
var sX = 0;
var sY = 0;
// pixelX, pixelY
var pX = 0;
var pY = 0;
// Legacy
if ('detail' in event) {
sY = event.detail;
}
if ('wheelDelta' in event) {
sY = -event.wheelDelta / 120;
}
if ('wheelDeltaY' in event) {
sY = -event.wheelDeltaY / 120;
}
if ('wheelDeltaX' in event) {
sX = -event.wheelDeltaX / 120;
}
// side scrolling on FF with DOMMouseScroll
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) {
pY = event.deltaY;
}
if ('deltaX' in event) {
pX = event.deltaX;
}
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode == 1) {
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
}
else {
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) {
sX = (pX < 1) ? -1 : 1;
}
if (pY && !sY) {
sY = (pY < 1) ? -1 : 1;
}
return { spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY };
};
return Utils;
})();
exports.Utils = Utils;
|
ajax/libs/mobx/2.0.6/mobx.umd.min.js | x112358/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.mobx=e()}}(function(){return function e(t,n,r){function o(a,s){if(!n[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};t[a][0].call(l.exports,function(e){var n=t[a][1][e];return o(n?n:e)},l,l.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){(function(e){function t(e,t){ne(e,"autorun methods cannot have modifiers"),Oe("function"==typeof e,"autorun expects a function"),Oe(0===e.length,"autorun expects a function without arguments"),t&&(e=e.bind(t));var n=new Le(e.name||"Autorun",function(){this.track(e)});return D()||Ue.inTransaction>0?Ue.pendingReactions.push(n):n.runReaction(),n.getDisposer()}function r(e,n,r){var o=!1,i=t(function(){e.call(r)&&(i?i():o=!0,n.call(r))});return o&&i(),i}function o(e,t,n){return Se("`autorunUntil` is deprecated, please use `when`."),r.apply(null,arguments)}function i(e,t,n){void 0===t&&(t=1),n&&(e=e.bind(n));var r=!1,o=new Le(e.name||"AutorunAsync",function(){r||(r=!0,setTimeout(function(){r=!1,o.isDisposed||o.track(e)},t))});return o.runReaction(),o.getDisposer()}function a(e,t,n,r){return arguments.length<3&&"function"==typeof e?s(e,t):u.apply(null,arguments)}function s(e,t){var n=Z(e,Ge.Recursive),r=n[0],o=n[1];return new Te(o,t,r===Ge.Structure,o.name||"ComputedValue")}function u(e,t,n,r){if(1===arguments.length){var o=e;return function(e,t,n){return u.call(null,e,t,n,o)}}Oe(n&&n.hasOwnProperty("get"),"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'"),$e(e,t);var i={},a=n.get;return Oe("object"==typeof e,"The @observable decorator can only be used on objects",t),Oe("function"==typeof a,"@observable expects a getter function if used on a property.",t),Oe(!n.set,"@observable properties cannot have a setter.",t),Oe(0===a.length,"@observable getter functions should not take arguments.",t),i.configurable=!0,i.enumerable=!1,i.get=function(){return ye(me(this,void 0,Ge.Recursive),t,r&&r.asStructure===!0?W(a):a),this[t]},i.set=c,n?i:void Object.defineProperty(e,t,i)}function c(){throw new Error("[ComputedValue] It is not allowed to assign new values to computed properties.")}function l(e,t){Oe("function"==typeof e&&1===e.length,"createTransformer expects a function that accepts one argument");var n={},r=Ue.resetId,o=function(r){function o(t,n){r.call(this,function(){return e(n)},null,!1,"Transformer-"+e.name+"-"+t),this.sourceIdentifier=t,this.sourceObject=n}return Pe(o,r),o.prototype.onBecomeUnobserved=function(){var e=this.value;r.prototype.onBecomeUnobserved.call(this),delete n[this.sourceIdentifier],t&&t(e,this.sourceObject)},o}(Te);return function(e){r!==Ue.resetId&&(n={},r=Ue.resetId);var t=f(e),i=n[t];return i?i.get():(i=n[t]=new o(t,e),i.get())}}function f(e){if(null===e||"object"!=typeof e)throw new Error("[mobx] transform expected some kind of object, got: "+e);var t=e.$transformId;return void 0===t&&(t=U(),Object.defineProperty(e,"$transformId",{configurable:!0,writable:!0,enumerable:!1,value:t})),t}function h(e,t){return D()||console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."),a(e,t).get()}function p(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return Oe(arguments.length>=2,"extendObservable expected 2 or more arguments"),Oe("object"==typeof e,"extendObservable expects an object as first argument"),Oe(!(e instanceof Qe),"extendObservable should not be used on maps, use map.merge instead"),t.forEach(function(t){Oe("object"==typeof t,"all arguments of extendObservable should be objects"),v(e,t,Ge.Recursive,null)}),e}function v(e,t,n,r){var o=me(e,r,n);for(var i in t)if(t.hasOwnProperty(i)){if(e===t&&!Ee(e,i))continue;ye(o,i,t[i])}return e}function d(e,t){var n=Ue.allowStateChanges;Ue.allowStateChanges=e;var r=t();return Ue.allowStateChanges=n,r}function b(e,t,n){void 0===n&&(n=!1),Ie&&Ie.emit({id:e.id,name:e.name+"@"+e.id,node:e,state:t,changed:n})}function m(e){return y(e)}function y(e){var t={id:e.id,name:e.name+"@"+e.id};return e.observing&&e.observing.length&&(t.dependencies=je(e.observing).map(y)),t}function g(e){return x(e)}function x(e){var t={id:e.id,name:e.name+"@"+e.id};return e.observers&&e.observers.length&&(t.observers=je(e.observers).map(x)),t}function w(e){var t=[],n=!1;return function(r){(e||r.changed)&&t.push(r),n||(n=!0,setTimeout(function(){console[console.table?"table":"dir"](t),t=[],n=!1},1))}}function O(e,t){void 0===e&&(e=!1),Ie||(Ie=new Ze);var n=t?function(n){(e||n.changed)&&t(n)}:w(e),r=Ie.on(n);return Ce(function(){r(),0===Ie.listeners.length&&(Ie=null)})}function S(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(e instanceof Qe||e instanceof Je)throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");if(we(e)){var n=e.$mobx;return n.values&&!!n.values[t]}return!1}return!!e.$mobx||e instanceof Fe||e instanceof Le||e instanceof Te}function C(e,t,n){if(Oe(arguments.length>=2&&arguments.length<=3,"Illegal decorator config",t),$e(e,t),n&&n.hasOwnProperty("get"))return Se("Using @observable on computed values is deprecated. Use @computed instead."),a.apply(null,arguments);var r={},o=void 0;return n&&(n.hasOwnProperty("value")?o=n.value:n.initializer&&(o=n.initializer(),"function"==typeof o&&(o=Q(o)))),Oe("object"==typeof e,"The @observable decorator can only be used on objects",t),r.configurable=!0,r.enumerable=!0,r.get=function(){var e=this;return d(!0,function(){ye(me(e,void 0,Ge.Recursive),t,o)}),this[t]},r.set=function(e){ye(me(this,void 0,Ge.Recursive),t,"function"==typeof e?Q(e):e)},n?r:void Object.defineProperty(e,t,r)}function j(e,t){if("string"==typeof arguments[1])return C.apply(null,arguments);if(Oe(1===arguments.length||2===arguments.length,"observable expects one or two arguments"),S(e))return e;var n=Z(e,Ge.Recursive),r=n[0],o=n[1],i=r===Ge.Reference?Me.Reference:R(o);switch(i){case Me.Array:case Me.PlainObject:return te(o,r);case Me.Reference:case Me.ComplexObject:return new Xe(o,r);case Me.ComplexFunction:throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");case Me.ViewFunction:return Se("Use `computed(expr)` instead of `observable(expr)`"),a(e,t)}Oe(!1,"Illegal State")}function R(e){return null===e||void 0===e?Me.Reference:"function"==typeof e?e.length?Me.ComplexFunction:Me.ViewFunction:Array.isArray(e)||e instanceof Je?Me.Array:"object"==typeof e?Re(e)?Me.PlainObject:Me.ComplexObject:Me.Reference}function _(e,t,n,r){return"function"==typeof n?E(e,t,n,r):k(e,t,n)}function k(e,t,n){return ve(e)?e.observe(t):be(e)?e.observe(t):we(e)?xe(e,t,n):e instanceof Xe||e instanceof Te?e.observe(t,n):Re(e)?k(j(e),t,n):void Oe(!1,"first argument of observe should be some observable value or plain object")}function E(e,t,n,r){var o="[mobx.observe] the provided observable map has no key with name: "+t;if(be(e)){if(!e._has(t))throw new Error(o);return _(e._data[t],n)}if(we(e)){if(!S(e,t))throw new Error(o);return _(e.$mobx.values[t],n,r)}return Re(e)?(p(e,{property:e[t]}),E(e,t,n,r)):void Oe(!1,"first argument of observe should be an (observable)object or observableMap if a property name is given")}function $(e,t,n){function r(r){return t&&n.push([e,r]),r}if(void 0===t&&(t=!0),void 0===n&&(n=null),t&&null===n&&(n=[]),t&&null!==e&&"object"==typeof e)for(var o=0,i=n.length;i>o;o++)if(n[o][0]===e)return n[o][1];if(!e)return e;if(Array.isArray(e)||e instanceof Je){var a=r([]);return a.push.apply(a,e.map(function(e){return $(e,t,n)})),a}if(e instanceof Qe){var a=r({});return e.forEach(function(e,r){return a[r]=$(e,t,n)}),a}if("object"==typeof e&&Re(e)){var a=r({});for(var s in e)e.hasOwnProperty(s)&&(a[s]=$(e[s],t,n));return a}return S(e)&&e.$mobx instanceof Xe?$(e(),t,n):e}function A(e){Oe(e.isDirty,"atom not dirty"),e.isDirty=!1,b(e,"READY",!0),q(e,!0)}function D(){return Ue.derivationStack.length>0}function P(){Oe(Ue.allowStateChanges,"It is not allowed to change the state when a computed value is being evaluated. Use 'autorun' to create reactive functions with side-effects. Or use 'extras.allowStateChanges(true, block)' to supress this message.")}function I(e){1===++e.dependencyStaleCount&&(b(e,"STALE"),N(e))}function M(e,t){if(Oe(e.dependencyStaleCount>0,"unexpected ready notification"),t&&(e.dependencyChangeCount+=1),0===--e.dependencyStaleCount)if(e.dependencyChangeCount>0){e.dependencyChangeCount=0,b(e,"PENDING");var n=e.onDependenciesReady();q(e,n)}else b(e,"READY",!1),q(e,!1)}function F(e,t){var n=e.observing;e.observing=[],Ue.derivationStack.push(e);var r=t();return T(e,n),r}function T(e,t){Ue.derivationStack.length-=1;for(var n=De(e.observing,t),r=n[0],o=n[1],i=0,a=r.length;a>i;i++){var s=r[i];Oe(!V(e,s),"Cycle detected",e),G(r[i],e)}for(var i=0,a=o.length;a>i;i++)z(o[i],e)}function V(e,t){var n=t.observing;if(void 0===n)return!1;if(-1!==n.indexOf(t))return!0;for(var r=n.length,o=0;r>o;o++)if(V(e,n[o]))return!0;return!1}function U(){return++Ue.mobxGuid}function L(){}function B(){var e=Ue.resetId,t=new Ve;for(var n in t)Ue[n]=t[n];Ue.resetId=e+1}function G(e,t){var n=e.observers,r=n.length;n[r]=t,0===r&&e.onBecomeObserved()}function z(e,t){var n=e.observers,r=n.indexOf(t);-1!==r&&n.splice(r,1),0===n.length&&e.onBecomeUnobserved()}function K(e){if(!(Ue.inUntracked>0)){var t=Ue.derivationStack,n=t.length;if(n>0){var r=t[n-1].observing,o=r.length;r[o-1]!==e&&r[o-2]!==e&&(r[o]=e)}}}function N(e){var t=e.observers.slice();t.forEach(I),e.staleObservers=e.staleObservers.concat(t)}function q(e,t){e.staleObservers.splice(0).forEach(function(e){return M(e,t)})}function H(e){Se("This feature is experimental and might be removed in a future minor release. Please report if you use this feature in production: https://github.com/mobxjs/mobx/issues/49"),Ue.inUntracked++;var t=e();return Ue.inUntracked--,t}function J(){if(!Ue.isRunningReactions){Ue.isRunningReactions=!0;for(var e=Ue.pendingReactions,t=0;e.length;){if(++t===Be)throw new Error("Reaction doesn't converge to a stable state. Probably there is a cycle in the reactive function: "+e[0].toString());for(var n=e.splice(0),r=0,o=n.length;o>r;r++)n[r].runReaction()}Ue.isRunningReactions=!1}}function Y(e,t){Ue.inTransaction+=1;var n=e.call(t);if(0===--Ue.inTransaction){for(var r=Ue.changedAtoms.splice(0),o=0,i=r.length;i>o;o++)A(r[o]);J()}return n}function Q(e){return new ze(e)}function W(e){return new Ke(e)}function X(e){return new Ne(e)}function Z(e,t){return e instanceof ze?[Ge.Reference,e.value]:e instanceof Ke?[Ge.Structure,e.value]:e instanceof Ne?[Ge.Flat,e.value]:[t,e]}function ee(e){return e===Q?Ge.Reference:e===W?Ge.Structure:e===X?Ge.Flat:(Oe(void 0===e,"Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: "+e),Ge.Recursive)}function te(e,t,n){var r;if(S(e))return e;switch(t){case Ge.Reference:return e;case Ge.Flat:ne(e,"Items inside 'asFlat' canont have modifiers"),r=Ge.Reference;break;case Ge.Structure:ne(e,"Items inside 'asStructure' canont have modifiers"),r=Ge.Structure;break;case Ge.Recursive:o=Z(e,Ge.Recursive),r=o[0],e=o[1];break;default:Oe(!1,"Illegal State")}return Array.isArray(e)&&Object.isExtensible(e)?he(e,r,n):Re(e)&&Object.isExtensible(e)?v(e,e,r,n):e;var o}function ne(e,t){if(e instanceof ze||e instanceof Ke||e instanceof Ne)throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. "+t)}function re(e){return e.atom.reportObserved(),e.values.length}function oe(e,t){if("number"!=typeof t||0>t)throw new Error("[mobx.array] Out of range: "+t);var n=e.values.length;t!==n&&(t>n?ae(e,n,0,new Array(t-n)):ae(e,t,n-t))}function ie(e,t,n){if(t!==e.lastKnownLength)throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");P(),e.lastKnownLength+=n,n>0&&t+n>qe&&fe(t+n)}function ae(e,t,n,r){var o=e.values.length;if(!(void 0!==r&&0!==r.length||0!==n&&0!==o))return[];void 0===t?t=0:t>o?t=o:0>t&&(t=Math.max(0,o+t)),n=2===arguments.length?o-t:void 0===n||null===n?0:Math.max(0,Math.min(n,o-t)),r=void 0===r?et:r.map(e.makeChildReactive);var i=r.length-n;ie(e,o,i);var a=(s=e.values).splice.apply(s,[t,n].concat(r));return ce(e,t,a,r),a;var s}function se(e){return ne(e,"Array values cannot have modifiers"),this.mode===Ge.Flat||this.mode===Ge.Reference?e:te(e,this.mode,this.atom.name+"@"+this.atom.id+" / ArrayEntry")}function ue(e,t,n){e.atom.reportChanged(),e.changeEvent&&e.changeEvent.emit({object:e.array,type:"update",index:t,oldValue:n})}function ce(e,t,n,r){0===n.length&&0===r.length||(e.atom.reportChanged(),e.changeEvent&&e.changeEvent.emit({object:e.array,type:"splice",index:t,addedCount:r.length,removed:n}))}function le(e){Object.defineProperty(Je.prototype,""+e,{enumerable:!1,configurable:!1,set:function(t){var n=this.$mobx,r=n.values;if(ne(t,"Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."),e<r.length){P();var o=r[e],i=n.mode===Ge.Structure?!Ae(o,t):o!==t;i&&(r[e]=n.makeChildReactive(t),ue(n,e,o))}else{if(e!==r.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+r.length);ae(n,e,0,[t])}},get:function(){var t=this.$mobx;return t&&e<t.values.length?(t.atom.reportObserved(),t.values[e]):void 0}})}function fe(e){for(var t=qe;e>t;t++)le(t);qe=e}function he(e,t,n){return new Je(e,t,n)}function pe(e){return Se("fastArray is deprecated. Please use `observable(asFlat([]))`"),he(e,Ge.Flat,null)}function ve(e){return e instanceof Je}function de(e,t){return new Qe(e,t)}function be(e){return e instanceof Qe}function me(e,t,n){if(void 0===t&&(t="ObservableObject"),void 0===n&&(n=Ge.Recursive),e.$mobx){if(e.$mobx.type!==We)throw new Error("The given object is observable but not an observable object");return e.$mobx}var r={type:We,values:{},events:void 0,id:U(),target:e,name:t,mode:n};return Object.defineProperty(e,"$mobx",{enumerable:!1,configurable:!1,writable:!1,value:r}),r}function ye(e,t,n){e.values[t]?e.target[t]=n:ge(e,t,n)}function ge(e,t,n){$e(e.target,t);var r,o=e.name+"@"+e.id+' / Prop "'+t+'"',i=!0;"function"==typeof n&&0===n.length?r=new Te(n,e.target,!1,o):n instanceof Ke&&"function"==typeof n.value&&0===n.value.length?r=new Te(n.value,e.target,!0,o):(i=!1,r=new Xe(n,e.mode,o)),e.values[t]=r,Object.defineProperty(e.target,t,{configurable:!0,enumerable:!i,get:function(){return r.get()},set:i?c:function(n){var o=r.value;r.set(n)&&void 0!==e.events&&e.events.emit({type:"update",object:this,name:t,oldValue:o})}}),void 0!==e.events&&e.events.emit({type:"add",object:e.target,name:t})}function xe(e,t,n){Oe(we(e),"Expected observable object"),Oe(n!==!0,"`observe` doesn't support the fire immediately property for observable objects.");var r=e.$mobx;return void 0===r.events&&(r.events=new Ze),e.$mobx.events.on(t)}function we(e){return e&&e.$mobx&&e.$mobx.type===We}function Oe(e,t,n){if(!e)throw new Error("[mobx] Invariant failed: "+t+(n?" in '"+n+"'":""))}function Se(e){-1===tt.indexOf(e)&&(tt.push(e),console.error("[mobx] Deprecated: "+e))}function Ce(e){var t=!1;return function(){return t?void 0:(t=!0,e.apply(this,arguments))}}function je(e){var t=[];return e.forEach(function(e){-1===t.indexOf(e)&&t.push(e)}),t}function Re(e){return null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype}function _e(e,t,n){return e?!Ae(t,n):t!==n}function ke(e,t){for(var n=0;n<t.length;n++)Object.defineProperty(e,t[n],{configurable:!0,writable:!0,enumerable:!1,value:e[t[n]]})}function Ee(e,t){var n=Object.getOwnPropertyDescriptor(e,t);return!n||n.configurable!==!1&&n.writable!==!1}function $e(e,t){Oe(Ee(e,t),"Cannot make property '"+t+"' observable, it is not configurable and writable in the target object")}function Ae(e,t){if(null===e&&null===t)return!0;if(void 0===e&&void 0===t)return!0;var n=Array.isArray(e)||ve(e);if(n!==(Array.isArray(t)||ve(t)))return!1;if(n){if(e.length!==t.length)return!1;for(var r=e.length;r>=0;r--)if(!Ae(e[r],t[r]))return!1;return!0}if("object"==typeof e&&"object"==typeof t){if(null===e||null===t)return!1;if(Object.keys(e).length!==Object.keys(t).length)return!1;for(var o in e){if(!t.hasOwnProperty(o))return!1;if(!Ae(e[o],t[o]))return!1}return!0}return e===t}function De(e,t){if(!t||!t.length)return[e,[]];if(!e||!e.length)return[[],t];for(var n=[],r=[],o=0,i=0,a=e.length,s=!1,u=0,c=0,l=t.length,f=!1,h=!1;!h&&!s;){if(!f){if(a>o&&l>u&&e[o]===t[u]){if(o++,u++,o===a&&u===l)return[n,r];continue}i=o,c=u,f=!0}c+=1,i+=1,c>=l&&(h=!0),i>=a&&(s=!0),s||e[i]!==t[u]?h||t[c]!==e[o]||(r.push.apply(r,t.slice(u,c)),u=c+1,o++,f=!1):(n.push.apply(n,e.slice(o,i)),o=i+1,u++,f=!1)}return n.push.apply(n,e.slice(o)),r.push.apply(r,t.slice(u)),[n,r]}var Pe=this&&this.__extends||function(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)};L(),n._={quickDiff:De,resetGlobalState:B},n.extras={allowStateChanges:d,getDependencyTree:m,getObserverTree:g,isComputingDerivation:D,resetGlobalState:B,trackTransitions:O},n.autorun=t,n.when=r,n.autorunUntil=o,n.autorunAsync=i,n.computed=a,n.createTransformer=l,n.expr=h,n.extendObservable=p;var Ie=null;n.isObservable=S,n.observable=j;var Me;!function(e){e[e.Reference=0]="Reference",e[e.PlainObject=1]="PlainObject",e[e.ComplexObject=2]="ComplexObject",e[e.Array=3]="Array",e[e.ViewFunction=4]="ViewFunction",e[e.ComplexFunction=5]="ComplexFunction"}(Me||(Me={})),n.observe=_,n.toJSON=$;var Fe=function(){function e(e,t,n){void 0===e&&(e="Atom"),void 0===t&&(t=nt),void 0===n&&(n=nt),this.name=e,this.onBecomeObserved=t,this.onBecomeUnobserved=n,this.id=U(),this.isDirty=!1,this.staleObservers=[],this.observers=[]}return e.prototype.reportObserved=function(){K(this)},e.prototype.reportChanged=function(){this.isDirty||(this.reportStale(),this.reportReady())},e.prototype.reportStale=function(){this.isDirty||(this.isDirty=!0,b(this,"STALE"),N(this))},e.prototype.reportReady=function(){Oe(this.isDirty,"atom not dirty"),Ue.inTransaction>0?Ue.changedAtoms.push(this):(A(this),J())},e.prototype.toString=function(){return this.name+"@"+this.id},e}();n.Atom=Fe;var Te=function(){function e(e,t,n,r){var o=this;void 0===r&&(r="ComputedValue"),this.derivation=e,this.scope=t,this.compareStructural=n,this.name=r,this.id=U(),this.isLazy=!0,this.isComputing=!1,this.staleObservers=[],this.observers=[],this.observing=[],this.dependencyChangeCount=0,this.dependencyStaleCount=0,this.value=void 0,this.peek=function(){o.isComputing=!0,Ue.isComputingComputedValue++;var n=Ue.allowStateChanges;Ue.allowStateChanges=!1;var r=e.call(t);return Ue.allowStateChanges=n,Ue.isComputingComputedValue--,o.isComputing=!1,r}}return e.prototype.onBecomeObserved=function(){},e.prototype.onBecomeUnobserved=function(){for(var e=0,t=this.observing.length;t>e;e++)z(this.observing[e],this);this.observing=[],this.isLazy=!0,this.value=void 0},e.prototype.onDependenciesReady=function(){var e=this.trackAndCompute();return b(this,"READY",e),e},e.prototype.get=function(){if(Oe(!this.isComputing,"Cycle detected",this.derivation),K(this),this.dependencyStaleCount>0)return this.peek();if(this.isLazy){if(!D())return this.peek();this.isLazy=!1,this.trackAndCompute()}return this.value},e.prototype.set=function(e){throw new Error("[ComputedValue '"+name+"'] It is not possible to assign a new value to a computed value.")},e.prototype.trackAndCompute=function(){var e=this.value;return this.value=F(this,this.peek),_e(this.compareStructural,this.value,e)},e.prototype.observe=function(e,n){var r=this,o=!0,i=void 0;return t(function(){var t=r.get();o&&!n||e(t,i),o=!1,i=t})},e.prototype.toString=function(){return this.name+"@"+this.id+"["+this.derivation.toString()+"]"},e}(),Ve=function(){function e(){this.version=1,this.derivationStack=[],this.mobxGuid=0,this.inTransaction=0,this.inUntracked=0,this.isRunningReactions=!1,this.isComputingComputedValue=0,this.changedAtoms=[],this.pendingReactions=[],this.allowStateChanges=!0,this.resetId=0}return e}(),Ue=function(){var t=new Ve;if(e.__mobservableTrackingStack||e.__mobservableViewStack)throw new Error("[mobx] An incompatible version of mobservable is already loaded.");if(e.__mobxGlobal&&e.__mobxGlobal.version!==t.version)throw new Error("[mobx] An incompatible version of mobx is already loaded.");return e.__mobxGlobal?e.__mobxGlobal:e.__mobxGlobal=t}();n.untracked=H;var Le=function(){function e(e,t){void 0===e&&(e="Reaction"),this.name=e,this.onInvalidate=t,this.id=U(),this.staleObservers=et,this.observers=et,this.observing=[],this.dependencyChangeCount=0,this.dependencyStaleCount=0,this.isDisposed=!1,this._isScheduled=!1}return e.prototype.onBecomeObserved=function(){},e.prototype.onBecomeUnobserved=function(){},e.prototype.onDependenciesReady=function(){return this._isScheduled||(this._isScheduled=!0,Ue.pendingReactions.push(this)),!1},e.prototype.isScheduled=function(){return this.dependencyStaleCount>0||this._isScheduled},e.prototype.runReaction=function(){this.isDisposed||(this._isScheduled=!1,this.onInvalidate(),b(this,"READY",!0))},e.prototype.track=function(e){F(this,e)},e.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=!0;for(var e=this.observing.splice(0),t=0,n=e.length;n>t;t++)z(e[t],this)}},e.prototype.getDisposer=function(){var e=this.dispose.bind(this);return e.$mobx=this,e},e.prototype.toString=function(){return"Reaction["+this.name+"]"},e}();n.Reaction=Le;var Be=100;n.transaction=Y;var Ge;!function(e){e[e.Recursive=0]="Recursive",e[e.Reference=1]="Reference",e[e.Structure=2]="Structure",e[e.Flat=3]="Flat"}(Ge||(Ge={})),n.asReference=Q,n.asStructure=W,n.asFlat=X;var ze=function(){function e(e){this.value=e,ne(e,"Modifiers are not allowed to be nested")}return e}(),Ke=function(){function e(e){this.value=e,ne(e,"Modifiers are not allowed to be nested")}return e}(),Ne=function(){function e(e){this.value=e,ne(e,"Modifiers are not allowed to be nested")}return e}(),qe=0,He=function(){function e(){}return e}();He.prototype=[];var Je=function(e){function t(t,n,r){e.call(this);var o=this.$mobx={atom:new Fe(r||"ObservableArray"),values:void 0,changeEvent:void 0,lastKnownLength:0,mode:n,array:this,makeChildReactive:function(e){return se.call(o,e)}};Object.defineProperty(this,"$mobx",{enumerable:!1,configurable:!1,writable:!1}),t&&t.length?(ie(o,0,t.length),o.values=t.map(o.makeChildReactive)):o.values=[]}return Pe(t,e),t.prototype.observe=function(e,t){return void 0===t&&(t=!1),void 0===this.$mobx.changeEvent&&(this.$mobx.changeEvent=new Ze),t&&e({object:this,type:"splice",index:0,addedCount:this.$mobx.values.length,removed:[]}),this.$mobx.changeEvent.on(e)},t.prototype.clear=function(){return this.splice(0)},t.prototype.replace=function(e){return ae(this.$mobx,0,this.$mobx.values.length,e)},t.prototype.toJSON=function(){return this.$mobx.atom.reportObserved(),this.$mobx.values.slice()},t.prototype.peek=function(){return this.$mobx.values},t.prototype.find=function(e,t,n){void 0===n&&(n=0),this.$mobx.atom.reportObserved();for(var r=this.$mobx.values,o=r.length,i=n;o>i;i++)if(e.call(t,r[i],i,this))return r[i];return null},t.prototype.splice=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];switch(arguments.length){case 0:return[];case 1:return ae(this.$mobx,e);case 2:return ae(this.$mobx,e,t)}return ae(this.$mobx,e,t,n)},t.prototype.push=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];return ae(this.$mobx,this.$mobx.values.length,0,e),this.$mobx.values.length},t.prototype.pop=function(){return this.splice(Math.max(this.$mobx.values.length-1,0),1)[0]},t.prototype.shift=function(){return this.splice(0,1)[0]},t.prototype.unshift=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];return ae(this.$mobx,0,0,e),this.$mobx.values.length},t.prototype.reverse=function(){this.$mobx.atom.reportObserved();var e=this.slice();return e.reverse.apply(e,arguments)},t.prototype.sort=function(e){this.$mobx.atom.reportObserved();var t=this.slice();return t.sort.apply(t,arguments)},t.prototype.remove=function(e){var t=this.$mobx.values.indexOf(e);return t>-1?(this.splice(t,1),!0):!1},t.prototype.toString=function(){return"[mobx.array] "+Array.prototype.toString.apply(this.$mobx.values,arguments)},t.prototype.toLocaleString=function(){return"[mobx.array] "+Array.prototype.toLocaleString.apply(this.$mobx.values,arguments)},t}(He);ke(Je.prototype,["constructor","clear","find","observe","pop","peek","push","remove","replace","reverse","shift","sort","splice","split","toJSON","toLocaleString","toString","unshift"]),Object.defineProperty(Je.prototype,"length",{enumerable:!1,configurable:!0,get:function(){return re(this.$mobx)},set:function(e){oe(this.$mobx,e)}}),["concat","every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some"].forEach(function(e){var t=Array.prototype[e];Object.defineProperty(Je.prototype,e,{configurable:!1,writable:!0,enumerable:!1,value:function(){return this.$mobx.atom.reportObserved(),t.apply(this.$mobx.values,arguments)}})}),fe(1e3),n.fastArray=pe,n.isObservableArray=ve;var Ye={},Qe=function(){function e(e,t){var n=this;this.$mobx=Ye,this._data={},this._hasMap={},this._events=void 0,this.name="ObservableMap",this.id=U(),this._keys=new Je(null,Ge.Reference,this.name+"@"+this.id+" / keys()"),this._valueMode=ee(t),Re(e)?this.merge(e):Array.isArray(e)&&e.forEach(function(e){var t=e[0],r=e[1];return n.set(t,r)})}return e.prototype._has=function(e){return"undefined"!=typeof this._data[e]},e.prototype.has=function(e){return this.isValidKey(e)?this._hasMap[e]?this._hasMap[e].get():this._updateHasMapEntry(e,!1).get():!1},e.prototype.set=function(e,t){var n=this;if(this.assertValidKey(e),ne(t,"[mobx.map.set] Expected unwrapped value to be inserted to key '"+e+"'. If you need to use modifiers pass them as second argument to the constructor"),this._has(e)){var r=this._data[e].value,o=this._data[e].set(t);o&&this._events&&this._events.emit({type:"update",object:this,name:e,oldValue:r})}else Y(function(){n._data[e]=new Xe(t,n._valueMode,n.name+"@"+n.id+' / Entry "'+e+'"'),n._updateHasMapEntry(e,!0),n._keys.push(e)}),this._events&&this._events.emit({type:"add",object:this,name:e})},e.prototype["delete"]=function(e){var t=this;if(this._has(e)){var n=this._data[e].value;Y(function(){t._keys.remove(e),t._updateHasMapEntry(e,!1);var n=t._data[e];n.set(void 0),t._data[e]=void 0}),this._events&&this._events.emit({type:"delete",object:this,name:e,oldValue:n})}},e.prototype._updateHasMapEntry=function(e,t){var n=this._hasMap[e];return n?n.set(t):n=this._hasMap[e]=new Xe(t,Ge.Reference,this.name+"@"+this.id+' / Contains "'+e+'"'),n},e.prototype.get=function(e){return this.has(e)?this._data[e].get():void 0},e.prototype.keys=function(){return this._keys.slice()},e.prototype.values=function(){return this.keys().map(this.get,this)},e.prototype.entries=function(){var e=this;return this.keys().map(function(t){return[t,e.get(t)]})},e.prototype.forEach=function(e,t){var n=this;this.keys().forEach(function(r){return e.call(t,n.get(r),r)})},e.prototype.merge=function(t){var n=this;return Y(function(){t instanceof e?t.keys().forEach(function(e){return n.set(e,t.get(e))}):Object.keys(t).forEach(function(e){return n.set(e,t[e])})}),this},e.prototype.clear=function(){var e=this;Y(function(){e.keys().forEach(e["delete"],e)})},Object.defineProperty(e.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),e.prototype.toJs=function(){var e=this,t={};return this.keys().forEach(function(n){return t[n]=e.get(n)}),t},e.prototype.isValidKey=function(e){return null===e||void 0===e?!1:"string"==typeof e||"number"==typeof e},e.prototype.assertValidKey=function(e){if(!this.isValidKey(e))throw new Error("[mobx.map] Invalid key: '"+e+"'")},e.prototype.toString=function(){var e=this;return"[mobx.map { "+this.keys().map(function(t){return t+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e){return this._events||(this._events=new Ze),this._events.on(e)},e}();n.ObservableMap=Qe,n.map=de,n.isObservableMap=be;var We={};n.isObservableObject=we;var Xe=function(e){function t(t,n,r){void 0===r&&(r="ObservableValue"),e.call(this,r),this.mode=n,this.hasUnreportedChange=!1,this.events=null,this.value=void 0;var o=Z(t,Ge.Recursive),i=o[0],a=o[1];this.mode===Ge.Recursive&&(this.mode=i),this.value=te(a,this.mode,this.name)}return Pe(t,e),t.prototype.set=function(e){ne(e,"Modifiers cannot be used on non-initial values."),P();var t=this.value,n=_e(this.mode===Ge.Structure,t,e);return n&&(this.value=te(e,this.mode,this.name),this.reportChanged(),this.events&&this.events.emit(e,t)),n},t.prototype.get=function(){return this.reportObserved(),this.value},t.prototype.observe=function(e,t){return this.events||(this.events=new Ze),t&&e(this.value,void 0),this.events.on(e)},t.prototype.toString=function(){return this.name+"@"+this.id+"["+this.value+"]"},t}(Fe),Ze=function(){function e(){this.listeners=[]}return e.prototype.emit=function(){for(var e=this.listeners.slice(),t=0,n=e.length;n>t;t++)e[t].apply(null,arguments)},e.prototype.on=function(e){var t=this;return this.listeners.push(e),Ce(function(){var n=t.listeners.indexOf(e);-1!==n&&t.listeners.splice(n,1)})},e.prototype.once=function(e){var t=this.on(function(){t(),e.apply(this,arguments)});return t},e}();n.SimpleEventEmitter=Ze;var et=[];Object.freeze(et);var tt=[],nt=function(){}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)});
//# sourceMappingURL=./mobx.umd.min.js.map |
engine/Library/ExtJs/components/Ext.ux.form.field.BoxSelect.js | giginos/shopware | /**
* Copyright (c) 2011 Kevin Vaughan, http://www.sencha.com/forum/showthread.php?134751-Ext.ux.form.field.BoxSelect-Intuitive-Multi-Select-ComboBox
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//{literal}
/**
* @class Ext.ux.form.field.BoxSelect
* @extends Ext.form.field.ComboBox
*
* BoxSelect for ExtJS 4, a combo box improved for multiple value querying, selection and management.
*
* A friendlier combo box for multiple selections that creates easily individually
* removable labels for each selection, as seen on facebook and other sites. Querying
* and type-ahead support are also improved for multiple selections.
*
* Options and usage mostly remain consistent with the {@link Ext.form.field.ComboBox}
* control. Some default configuration options have changed, but should still
* work properly if overridden.
*
* Inspired by the SuperBoxSelect component for ExtJS 3 (http://technomedia.co.uk/SuperBoxSelect/examples3.html),
* which in turn was inspired by the BoxSelect component for ExtJS 2 (http://efattal.fr/en/extjs/extuxboxselect/).
*
* Various contributions and suggestions made by many members of the ExtJS community which can be seen
* in the user extension posting: http://www.sencha.com/forum/showthread.php?134751-Ext.ux.form.field.BoxSelect
*
* Many thanks go out to all of those who have contributed, this extension would not be
* possible without your help.
*
* @author kvee_iv http://www.sencha.com/forum/member.php?29437-kveeiv
* @version 1.3.1
* @requires BoxSelect.css
* @xtype boxselect
*/
Ext.define('Ext.ux.form.field.BoxSelect', {
extend:'Ext.form.field.ComboBox',
alias: ['widget.comboboxselect', 'widget.boxselect'],
requires: ['Ext.selection.Model', 'Ext.data.Store'],
/**
* @cfg [Boolean] multiSelect
* If set to <code>true</code>, allows the combo field to hold more than one value at a time, and allows selecting
* multiple items from the dropdown list. (Defaults to <code>true</code>, the default usage for BoxSelect)
*/
multiSelect: true,
/**
* @cfg [Boolean] forceSelection
* <code>true</code> to restrict the selected value to one of the values in the list,
* <code>false</code> to allow the user to set arbitrary text into the field (defaults to <code>true</code>, the default usage for BoxSelect)
*/
forceSelection: true,
/**
* @cfg [Boolean] selectOnFocus <code>true</code> to automatically select any existing field text when the field
* receives input focus (defaults to <code>true</code> for best multi-select usability during querying)
*/
selectOnFocus: true,
/**
* @cfg [Boolean] triggerOnClick <code>true</code> to activate the trigger when clicking in empty space
* in the field. Note that the subsequent behavior of this is controlled by the field's {@link #triggerAction}.
* This behavior is similar to that of a basic ComboBox with {@link #editable} <code>false</code>.
* (defaults to <code>true</code>).
*/
triggerOnClick: true,
/**
* @cfg [Boolean] createNewOnEnter
* When forceSelection is false, new records can be created by the user. These records are not added to the
* combo's store. By default, this creation is triggered by typing the configured 'delimiter'. With
* createNewOnEnter set to true, this creation can also be triggered by the 'enter' key. This configuration
* option has no effect if forceSelection is true. (defaults to <code>false</code>)
* <code>true</code> to allow the user to press 'enter' to create a new record
* <code>false</code> to only allow the user to type the configured 'delimiter' to create a new record
*/
createNewOnEnter: false,
/**
* @cfg [Boolean] createNewOnBlur
* Similar to {@link #createNewOnEnter}, createNewOnBlur will create a new record when the field loses focus.
* This configuration option has no effect if forceSelection is true. Please note that this behavior is also
* affected by the configuration options {@link #autoSelect} and {@link #selectOnTab}. If those are true
* and an existing item would have been selected as a result, the partial text the user has entered will
* be discarded.
* <code>true</code> to create a new record when the field loses focus
* <code>false</code> to not create a new record on blur
*/
createNewOnBlur: false,
/**
* @cfg [Boolean] encodeSubmitValue
* Controls the formatting of the form submit value of the field. (defaults to <code>false</code>). This
* is not applicable of {@link #multiSelect} is false.
* <code>true</code> for the field value to submit as a json encoded array in a single POST variable
* <code>false</code> for the field to submit as an array of POST variables
*/
encodeSubmitValue: false,
/**
* @cfg [Boolean] stacked
* When stacked is true, each labelled item will fill to the width of the form field
* <code>true</code> to have each labelled item fill the width of the form field
* <code>false</code> to have each labelled item size to its displayed contents (defaults to <code>false</code>)
*/
stacked: false,
/**
* @cfg [Boolean] pinList
* When multiSelect is true, the pick list used for the combo will stay open after each selection is made. This
* config option has no effect if multiSelect is false.
* <code>true</code> to keep the pick list expanded after each multiSelect selection
* <code>false</code> to collapse the pick list after each multiSelect selection (defaults to <code>true</code>)
*/
pinList: true,
/**
* @cfg [Boolean] grow <tt>true</tt> if this field should automatically grow and shrink to its content
* (defaults to <tt>true</tt>)
*/
grow: true,
/**
* @cfg [Number] growMin The minimum height to allow when <tt>{@link Ext.form.field.Text#grow grow}=true</tt>
* (defaults to <tt>false</tt>, which allows for natural growth based on selections)
*/
growMin: false,
/**
* @cfg [Number] growMax The maximum height to allow when <tt>{@link Ext.form.field.Text#grow grow}=true</tt>
* (defaults to <tt>false</tt>, which allows for natural growth based on selections)
*/
growMax: false,
//private
componentLayout: 'boxselectfield',
/**
* Initialize additional settings and enable simultaneous typeAhead and multiSelect support
*/
initComponent: function() {
var me = this,
typeAhead = me.typeAhead;
if (typeAhead && !me.editable) {
Ext.Error.raise('If typeAhead is enabled the combo must be editable: true -- please change one of those settings.');
}
Ext.apply(me, {
typeAhead: false
});
me.callParent(arguments);
me.typeAhead = typeAhead;
me.selectionModel = new Ext.selection.Model({
store: me.valueStore,
mode: 'MULTI',
onSelectChange: function(record, isSelected, suppressEvent, commitFn) {
commitFn();
}
});
if (!Ext.isEmpty(me.delimiter) && me.multiSelect) {
me.delimiterEndingRegexp = new RegExp(String(me.delimiter).replace(/[$%()*+.?\[\\\]{|}]/g, "\\$&") + "$");
}
},
/**
* Register events for management controls of labelled items
*/
initEvents: function() {
var me = this;
me.callParent(arguments);
if (!me.enableKeyEvents) {
me.mon(me.inputEl, 'keydown', me.onKeyDown, me);
}
me.mon(me.itemList, 'click', me.onItemListClick, me);
me.mon(me.selectionModel, 'selectionchange', me.applyMultiselectItemMarkup, me);
},
/**
* Create a store for the records of our current value based on the main store's model
*/
bindStore: function(store, initial) {
var me = this;
if (me.oldStore) {
me.mun(me.store, 'beforeload', me.onBeforeLoad, me);
if (me.valueStore) {
me.mun(me.valueStore, 'datachanged', me.applyMultiselectItemMarkup, me);
me.valueStore = null;
}
me.oldStore = null;
}
me.oldStore = true;
me.callParent(arguments);
if (me.store) {
if(me.valueStore) {
me.valueStore = Ext.StoreManager.get(me.valueStore);
} else {
me.valueStore = new Ext.data.Store({
model: me.store.model,
proxy: {
type: 'memory'
}
});
}
me.mon(me.valueStore, 'datachanged', me.applyMultiselectItemMarkup, me);
me.mon(me.store, 'beforeload', me.onBeforeLoad, me);
}
},
/**
* Add refresh tracking to the picker for selection management
*/
createPicker: function() {
var me = this,
picker = me.callParent(arguments);
me.mon(picker, {
'beforerefresh': me.onBeforeListRefresh,
'show': function(pick) {
/**
* Temporary fix for reapplying maxHeight after shorter list was previously shown
*/
var listEl = picker.listEl,
ch = listEl.getHeight();
if (ch > picker.maxHeight) {
listEl.setHeight(picker.maxHeight);
}
},
scope: me
});
return picker;
},
/**
* Clean up labelled items management controls
*/
onDestroy: function() {
var me = this;
Ext.destroyMembers(me, 'selectionModel', 'valueStore');
me.callParent(arguments);
},
/**
* Overridden to avoid use of placeholder, as our main input field is often empty
*/
afterRender: function() {
var me = this;
if (Ext.supports.Placeholder && me.inputEl && me.emptyText) {
delete me.inputEl.dom.placeholder;
}
if (me.stacked === true) {
me.itemList.addCls('x-boxselect-stacked');
}
if (me.grow) {
if (Ext.isNumber(me.growMin) && (me.growMin > 0)) {
me.itemList.applyStyles('min-height:'+me.growMin+'px');
}
if (Ext.isNumber(me.growMax) && (me.growMax > 0)) {
me.itemList.applyStyles('max-height:'+me.growMax+'px');
}
}
me.applyMultiselectItemMarkup();
me.callParent(arguments);
},
/**
* Overridden to search store snapshot instead of data (if available)
*/
findRecord: function(field, value) {
var ds = this.store,
rec = false,
idx;
if (ds.snapshot) {
idx = ds.snapshot.findIndexBy(function(rec) {
return rec.get(field) === value;
});
rec = (idx !== -1) ? ds.snapshot.getAt(idx) : false;
} else {
idx = ds.findExact(field, value);
rec = (idx !== -1) ? ds.getAt(idx) : false;
}
return rec;
},
/**
* When the picker is refreshing, we should ignore selection changes. Otherwise
* the value of our field will be changing just because our view of the choices is.
*/
onBeforeLoad: function() {
this.ignoreSelection++;
},
/**
* Overridden to map previously selected records to the "new" versions of the records
* based on value field, if they are part of the new store load
*/
onLoad: function() {
var me = this,
valueField = me.valueField,
valueStore = me.valueStore,
changed = false;
if (valueStore) {
if (!Ext.isEmpty(me.value) && (valueStore.getCount() == 0)) {
me.setValue(me.value, false, true);
}
valueStore.suspendEvents();
valueStore.each(function(rec) {
var r = me.findRecord(valueField, rec.get(valueField)),
i = r ? valueStore.indexOf(rec) : -1;
if (i >= 0) {
valueStore.removeAt(i);
valueStore.insert(i, r);
changed = true;
}
});
valueStore.resumeEvents();
if (changed) {
valueStore.fireEvent('datachanged', valueStore);
}
}
me.callParent(arguments);
me.ignoreSelection = Ext.Number.constrain(me.ignoreSelection - 1, 0);
me.alignPicker();
},
/**
* @private
* Used to determine if a record is filtered (for retaining as a multiSelect value)
*/
isFilteredRecord: function(record) {
var me = this,
store = me.store,
valueField = me.valueField,
storeRecord,
filtered = false;
storeRecord = store.findExact(valueField, record.get(valueField));
filtered = ((storeRecord === -1) && (!store.snapshot || (me.findRecord(valueField, record.get(valueField)) !== false)));
filtered = filtered || (!filtered && (storeRecord === -1) && (me.forceSelection !== true) &&
(me.valueStore.findExact(valueField, record.get(valueField)) >= 0));
return filtered;
},
/**
* Overridden to allow for continued querying with multiSelect selections already made
*/
doRawQuery: function() {
var me = this,
rawValue = me.inputEl.dom.value;
if (me.multiSelect) {
rawValue = rawValue.split(me.delimiter).pop();
}
this.doQuery(rawValue, false, true);
},
/**
* When the picker is refreshing, we should ignore selection changes. Otherwise
* the value of our field will be changing just because our view of the choices is.
*/
onBeforeListRefresh: function() {
this.ignoreSelection++;
},
/**
* When the picker is refreshing, we should ignore selection changes. Otherwise
* the value of our field will be changing just because our view of the choices is.
*/
onListRefresh: function() {
this.callParent(arguments);
this.ignoreSelection = Ext.Number.constrain(this.ignoreSelection - 1, 0);
},
/**
* Overridden to preserve current labelled items when list is filtered/paged/loaded
* and does not include our current value.
*/
onListSelectionChange: function(list, selectedRecords) {
var me = this,
valueStore = me.valueStore,
mergedRecords = [],
i;
// Only react to selection if it is not called from setValue, and if our list is
// expanded (ignores changes to the selection model triggered elsewhere)
if ((me.ignoreSelection <= 0) && me.isExpanded) {
// Pull forward records that were already selected or are now filtered out of the store
valueStore.each(function(rec) {
if (Ext.Array.contains(selectedRecords, rec) || me.isFilteredRecord(rec)) {
mergedRecords.push(rec);
}
});
mergedRecords = Ext.Array.merge(mergedRecords, selectedRecords);
i = Ext.Array.intersect(mergedRecords, valueStore.getRange()).length;
if ((i != mergedRecords.length) || (i != me.valueStore.getCount())) {
me.setValue(mergedRecords, false);
if (!me.multiSelect || !me.pinList) {
Ext.defer(me.collapse, 1, me);
}
if (valueStore.getCount() > 0) {
me.fireEvent('select', me, valueStore.getRange());
}
}
me.inputEl.focus();
if (!me.pinList) {
me.inputEl.dom.value = '';
}
if (me.selectOnFocus) {
me.inputEl.dom.select();
}
}
},
/**
* Overridden to use valueStore instead of valueModels, for inclusion of filtered records
*/
syncSelection: function() {
var me = this,
picker = me.picker,
valueField = me.valueField,
pickStore, selection, selModel;
if (picker) {
pickStore = picker.store;
// From the value, find the Models that are in the store's current data
selection = [];
if (me.valueStore) {
me.valueStore.each(function(rec) {
var i = pickStore.findExact(valueField, rec.get(valueField));
if (i >= 0) {
selection.push(pickStore.getAt(i));
}
});
}
// Update the selection to match
me.ignoreSelection++;
selModel = picker.getSelectionModel();
selModel.deselectAll();
if (selection.length > 0) {
selModel.select(selection);
}
me.ignoreSelection = Ext.Number.constrain(me.ignoreSelection - 1, 0);
}
},
/**
* Overridden to align to itemList size instead of inputEl
*/
alignPicker: function() {
var me = this,
picker, isAbove,
aboveSfx = '-above';
if(me.itemList) {
var itemBox = me.itemList.getBox(false, true);
}
if (this.isExpanded) {
picker = me.getPicker();
var pickerScrollPos = picker.getTargetEl().dom.scrollTop;
if (me.matchFieldWidth) {
// Auto the height (it will be constrained by min and max width) unless there are no records to display.
picker.setSize(itemBox.width, picker.store && picker.store.getCount() ? null : 0);
}
if (picker.isFloating()) {
picker.alignTo(me.itemList, me.pickerAlign, me.pickerOffset);
// add the {openCls}-above class if the picker was aligned above
// the field due to hitting the bottom of the viewport
isAbove = picker.el.getY() < me.inputEl.getY();
me.bodyEl[isAbove ? 'addCls' : 'removeCls'](me.openCls + aboveSfx);
picker.el[isAbove ? 'addCls' : 'removeCls'](picker.baseCls + aboveSfx);
}
}
},
/**
* @private
* Get the current cursor position in the input field
*/
getCursorPosition: function() {
var cursorPos;
if (Ext.isIE) {
cursorPos = document.selection.createRange();
cursorPos.collapse(true);
cursorPos.moveStart("character", -this.inputEl.dom.value.length);
cursorPos = cursorPos.text.length;
} else {
cursorPos = this.inputEl.dom.selectionStart;
}
return cursorPos;
},
/**
* @private
* Check to see if the input field has selected text
*/
hasSelectedText: function() {
var sel, range;
if (Ext.isIE) {
sel = document.selection;
range = sel.createRange();
return (range.parentElement() == this.inputEl.dom);
} else {
return this.inputEl.dom.selectionStart != this.inputEl.dom.selectionEnd;
}
},
/**
* Handles keyDown processing of key-based selection of labelled items
*/
onKeyDown: function(e, t) {
var me = this,
key = e.getKey(),
rawValue = me.inputEl.dom.value,
valueStore = me.valueStore,
selModel = me.selectionModel,
stopEvent = false,
rec, i;
if (me.readOnly || me.disabled || !me.editable) {
return;
}
// Handle keyboard based navigation of selected labelled items
if ((valueStore.getCount() > 0) &&
((rawValue == '') || ((me.getCursorPosition() === 0) && !me.hasSelectedText()))) {
if ((key == e.BACKSPACE) || (key == e.DELETE)) {
if (selModel.getCount() > 0) {
me.valueStore.remove(selModel.getSelection());
} else {
me.valueStore.remove(me.valueStore.last());
}
me.setValue(me.valueStore.getRange());
selModel.deselectAll();
stopEvent = true;
} else if ((key == e.RIGHT) || (key == e.LEFT)) {
if ((selModel.getCount() === 0) && (key == e.LEFT)) {
selModel.select(valueStore.last());
stopEvent = true;
} else if (selModel.getCount() > 0) {
rec = selModel.getLastFocused() || selModel.getLastSelected();
if (rec) {
i = valueStore.indexOf(rec);
if (key == e.RIGHT) {
if (i < (valueStore.getCount() - 1)) {
selModel.select(i + 1, e.shiftKey);
stopEvent = true;
} else if (!e.shiftKey) {
selModel.deselect(rec);
stopEvent = true;
}
} else if ((key == e.LEFT) && (i > 0)) {
selModel.select(i - 1, e.shiftKey);
stopEvent = true;
}
}
}
} else if (key == e.A && e.ctrlKey) {
selModel.selectAll();
stopEvent = e.A;
}
me.inputEl.focus();
}
if (stopEvent) {
me.preventKeyUpEvent = stopEvent;
e.stopEvent();
return;
}
// Prevent key up processing for enter if it is being handled by the picker
if (me.isExpanded && (key == e.ENTER) && me.picker.highlightedItem) {
me.preventKeyUpEvent = true;
}
if (me.enableKeyEvents) {
me.callParent(arguments);
}
if (!e.isSpecialKey() && !e.hasModifier()) {
me.selectionModel.deselectAll();
me.inputEl.focus();
}
},
/**
* Handles auto-selection of labelled items based on this field's delimiter, as well
* as the keyUp processing of key-based selection of labelled items.
*/
onKeyUp: function(e, t) {
var me = this,
rawValue = me.inputEl.dom.value,
rec;
if (me.preventKeyUpEvent) {
e.stopEvent();
if ((me.preventKeyUpEvent === true) || (e.getKey() === me.preventKeyUpEvent)) {
delete me.preventKeyUpEvent;
}
return;
}
if (me.multiSelect && (me.delimiterEndingRegexp && me.delimiterEndingRegexp.test(rawValue)) ||
((me.createNewOnEnter === true) && e.getKey() == e.ENTER)) {
rawValue = rawValue.replace(me.delimiterEndingRegexp, '');
if (!Ext.isEmpty(rawValue)) {
rec = me.valueStore.findExact(me.valueField, rawValue);
if (rec >= 0) {
rec = me.valueStore.getAt(rec);
} else {
rec = me.store.findExact(me.valueField, rawValue);
if (rec >= 0) {
rec = me.store.getAt(rec);
} else {
rec = false;
}
}
if (!rec && !me.forceSelection) {
rec = {};
rec[me.valueField] = rawValue;
rec[me.displayField] = rawValue;
rec = new me.valueStore.model(rec);
}
if (rec) {
me.collapse();
me.setValue(me.valueStore.getRange().concat(rec));
me.inputEl.dom.value = '';
me.inputEl.focus();
}
}
}
me.callParent([e,t]);
Ext.Function.defer(me.alignPicker, 10, me);
},
/**
* Overridden to get and set the dom value directly for type-ahead suggestion (bypassing get/setRawValue)
*/
onTypeAhead: function() {
var me = this,
displayField = me.displayField,
inputElDom = me.inputEl.dom,
record = me.store.findRecord(displayField, inputElDom.value),
boundList = me.getPicker(),
newValue, len, selStart;
if (record) {
newValue = record.get(displayField);
len = newValue.length;
selStart = inputElDom.value.length;
boundList.highlightItem(boundList.getNode(record));
if (selStart !== 0 && selStart !== len) {
inputElDom.value = newValue;
me.selectText(selStart, newValue.length);
}
}
},
/**
* Delegation control for selecting and removing labelled items or triggering list collapse/expansion
*/
onItemListClick: function(evt, el, o) {
var me = this,
itemEl = evt.getTarget('.x-boxselect-item'),
closeEl = itemEl ? evt.getTarget('.x-boxselect-item-close') : false;
if (me.readOnly || me.disabled) {
return;
}
evt.stopPropagation();
if (itemEl) {
if (closeEl) {
me.removeByListItemNode(itemEl);
} else {
me.toggleSelectionByListItemNode(itemEl, evt.shiftKey);
}
me.inputEl.focus();
} else if (me.triggerOnClick) {
me.onTriggerClick();
}
},
/**
* Build the markup for the labelled items. Template must be built on demand due to ComboBox initComponent
* lifecycle for the creation of on-demand stores (to account for automatic valueField/displayField setting)
*/
getMultiSelectItemMarkup: function() {
var me = this;
if (!me.multiSelectItemTpl) {
if (!me.labelTpl) {
me.labelTpl = Ext.create('Ext.XTemplate',
'{[values.' + me.displayField + ']}'
);
} else if (Ext.isString(me.labelTpl)) {
me.labelTpl = Ext.create('Ext.XTemplate', me.labelTpl);
}
me.multiSelectItemTpl = [
'<tpl for=".">',
'<li class="x-boxselect-item ',
'<tpl if="this.isSelected(values.'+ me.valueField + ')">',
' selected',
'</tpl>',
'" qtip="{[typeof values === "string" ? values : values.' + me.displayField + ']}">' ,
'<div class="x-boxselect-item-text">{[typeof values === "string" ? values : this.getItemLabel(values)]}</div>',
'<div class="x-tab-close-btn x-boxselect-item-close"></div>' ,
'</li>' ,
'</tpl>',
{
compile: true,
disableFormats: true,
isSelected: function(value) {
var i = me.valueStore.findExact(me.valueField, value);
if (i >= 0) {
return me.selectionModel.isSelected(me.valueStore.getAt(i));
}
},
getItemLabel: function(values) {
return me.getTpl('labelTpl').apply(values);
}
}
];
}
return this.getTpl('multiSelectItemTpl').apply(Ext.Array.pluck(this.valueStore.getRange(), 'data'));
},
/**
* Update the labelled items rendering
*/
applyMultiselectItemMarkup: function() {
var me = this,
itemList = me.itemList,
item;
if (itemList) {
while ((item = me.inputElCt.prev()) != null) {
item.remove();
}
me.inputElCt.insertHtml('beforeBegin', me.getMultiSelectItemMarkup());
}
},
/**
* Returns the record from valueStore for the labelled item node
*/
getRecordByListItemNode: function(itemEl) {
var me = this,
itemIdx = 0,
searchEl = me.itemList.dom.firstChild;
while (searchEl && searchEl.nextSibling) {
if (searchEl == itemEl) {
break;
}
itemIdx++;
searchEl = searchEl.nextSibling;
}
itemIdx = (searchEl == itemEl) ? itemIdx : false;
if (itemIdx === false) {
return false;
}
return me.valueStore.getAt(itemIdx);
},
/**
* Toggle of labelled item selection by node reference
*/
toggleSelectionByListItemNode: function(itemEl, keepExisting) {
var me = this,
rec = me.getRecordByListItemNode(itemEl);
if (rec) {
if (me.selectionModel.isSelected(rec)) {
me.selectionModel.deselect(rec);
} else {
me.selectionModel.select(rec, keepExisting);
}
}
},
/**
* Removal of labelled item by node reference
*/
removeByListItemNode: function(itemEl) {
var me = this,
rec = me.getRecordByListItemNode(itemEl);
if (rec) {
me.valueStore.remove(rec);
me.setValue(me.valueStore.getRange());
}
},
/**
* Intercept calls to getRawValue to pretend there is no inputEl for rawValue handling,
* so that we can use inputEl for just the user input.
*
* **Note that in general, raw values are the rendered value for the input field,
* and therefore should not be used for comboboxes or most programmatic logic.**
*/
getRawValue: function() {
var me = this,
inputEl = me.inputEl,
result;
me.inputEl = false;
result = me.callParent(arguments);
me.inputEl = inputEl;
return result;
},
/**
* Intercept calls to setRawValue to pretend there is no inputEl for rawValue handling,
* so that we can use inputEl for just the user input.
*
* **Note that in general, raw values are the rendered value for the input field,
* and therefore should not be used for comboboxes or most programmatic logic.**
*/
setRawValue: function(value) {
var me = this,
inputEl = me.inputEl,
result;
me.inputEl = false;
result = me.callParent([value]);
me.inputEl = inputEl;
return result;
},
/**
* Adds a value or values to the current value of the field
* @param {mixed} valueMixed The value or values to add to the current value
*/
addValue: function(valueMixed) {
var me = this;
if (valueMixed) {
me.setValue(Ext.Array.merge(me.value, Ext.Array.from(valueMixed)));
}
},
/**
* Removes a value or values from the current value of the field
* @param {mixed} valueMixed The value or values to remove from the current value
*/
removeValue: function(valueMixed) {
var me = this;
if (valueMixed) {
me.setValue(Ext.Array.difference(me.value, Ext.Array.from(valueMixed)));
}
},
/**
* Intercept calls to setValue to use records from the valueStore when available.
* Unknown values (if forceSelection is true) will trigger a call to store.load
* once to try to retrieve those records. The list of unknown values will be
* submitted as the name of the valueField with values separated by the configured
* delimiter. This process will cause setValue to asynchronously process.
*/
setValue: function(value, doSelect, skipLoad) {
var me = this,
valueStore = me.valueStore,
valueField = me.valueField,
record, len, i, valueRecord, h,
unknownValues = [];
if (Ext.isEmpty(value)) {
value = null;
}
if (Ext.isString(value) && me.multiSelect) {
value = value.split(me.delimiter);
}
value = Ext.Array.from(value);
for (i = 0, len = value.length; i < len; i++) {
record = value[i];
if (!record || !record.isModel) {
valueRecord = valueStore.findExact(valueField, record);
if (valueRecord >= 0) {
value[i] = valueStore.getAt(valueRecord);
} else {
valueRecord = me.findRecord(valueField, record);
if (!valueRecord) {
if (me.forceSelection) {
unknownValues.push(record);
} else {
valueRecord = {};
valueRecord[me.valueField] = record;
valueRecord[me.displayField] = record;
valueRecord = new me.valueStore.model(valueRecord);
}
}
if (valueRecord) {
value[i] = valueRecord;
}
}
}
}
if ((skipLoad !== true) && (unknownValues.length > 0) && (me.queryMode === 'remote')) {
var params = {};
params[me.valueField] = unknownValues.join(me.delimiter);
me.store.load({
params: params,
callback: function() {
if(me.itemList) {
me.itemList.unmask();
}
me.setValue(value, doSelect, true);
me.autoSize();
}
});
return false;
}
/**
* For single-select boxes, use the last value
*/
if (!me.multiSelect && (value.length > 0)) {
value = value[value.length - 1];
}
me.callParent([value, doSelect]);
},
/**
* Returns the records for the field's current value
* @return {Array} The records for the field's current value
*/
getValueRecords: function() {
return this.valueStore.getRange();
},
/**
* Overridden to optionally allow for submitting the field as a json encoded array.
*/
getSubmitData: function() {
var me = this,
val = me.callParent(arguments);
if (me.multiSelect && me.encodeSubmitValue && val && val[me.name]) {
val[me.name] = Ext.encode(val[me.name]);
}
return val;
},
/**
* Overridden to handle creation of new value for unforced selections
*/
beforeBlur: function() {
var me = this;
me.doQueryTask.cancel();
me.assertValue();
me.collapse();
},
/**
* Overridden to clear the input field if we are auto-setting a value as we blur.
*/
mimicBlur: function() {
var me = this;
if (me.selectOnTab && me.picker && me.picker.highlightedItem) {
me.inputEl.dom.value = '';
}
me.callParent(arguments);
},
/**
* Overridden to handle partial-input selections more directly
*/
assertValue: function() {
var me = this,
rawValue = me.inputEl.dom.value,
rec = !Ext.isEmpty(rawValue) ? me.findRecordByDisplay(rawValue) : false,
value = false;
if (!rec && !me.forceSelection && me.createNewOnBlur && !Ext.isEmpty(rawValue)) {
value = rawValue;
} else if (rec) {
value = rec;
}
if (value) {
me.addValue(value);
}
me.inputEl.dom.value = '';
me.collapse();
},
/**
* Update the valueStore from the new value and fire change events for UI to respond to
*/
checkChange: function() {
if (!this.suspendCheckChange && !this.isDestroyed) {
var me = this,
valueStore = me.valueStore,
lastValue = me.lastValue,
valueField = me.valueField,
newValue = Ext.Array.map(Ext.Array.from(me.value), function(val) {
if (val.isModel) {
return val.get(valueField);
}
return val;
}, this).join(this.delimiter);
if (!me.isEqual(newValue, lastValue)) {
valueStore.suspendEvents();
valueStore.removeAll();
if (Ext.isArray(me.valueModels)) {
valueStore.add(me.valueModels);
}
valueStore.resumeEvents();
valueStore.fireEvent('datachanged', valueStore);
me.lastValue = newValue;
me.fireEvent('change', me, newValue, lastValue);
me.onChange(newValue, lastValue)
}
}
},
/**
* Overridden to use value (selection) instead of raw value and to avoid the use of placeholder
*/
applyEmptyText : function() {
var me = this,
emptyText = me.emptyText,
inputEl, isEmpty;
if (me.rendered && emptyText) {
isEmpty = Ext.isEmpty(me.value) && !me.hasFocus;
inputEl = me.inputEl;
if (isEmpty) {
inputEl.dom.value = emptyText;
inputEl.addCls(me.emptyCls);
} else {
if (inputEl.dom.value === emptyText) {
inputEl.dom.value = '';
}
inputEl.removeCls(me.emptyCls);
}
}
},
/**
* Overridden to use inputEl instead of raw value and to avoid the use of placeholder
*/
preFocus : function(){
var me = this,
inputEl = me.inputEl,
emptyText = me.emptyText,
isEmpty;
if (emptyText && inputEl.dom.value === emptyText) {
inputEl.dom.value = '';
isEmpty = true;
inputEl.removeCls(me.emptyCls);
}
if (me.selectOnFocus || isEmpty) {
inputEl.dom.select();
}
},
/**
* Intercept calls to onFocus to add focusCls, because the base field classes assume this should be applied to inputEl
*/
onFocus: function() {
var me = this,
focusCls = me.focusCls,
itemList = me.itemList;
if (focusCls && itemList) {
itemList.addCls(focusCls);
}
me.callParent(arguments);
},
/**
* Intercept calls to onBlur to remove focusCls, because the base field classes assume this should be applied to inputEl
*/
onBlur: function() {
var me = this,
focusCls = me.focusCls,
itemList = me.itemList;
if (focusCls && itemList) {
itemList.removeCls(focusCls);
}
me.callParent(arguments);
},
/**
* Intercept calls to renderActiveError to add invalidCls, because the base field classes assume this should be applied to inputEl
*/
renderActiveError: function() {
var me = this,
invalidCls = me.invalidCls,
itemList = me.itemList,
hasError = me.hasActiveError();
if (invalidCls && itemList) {
itemList[hasError ? 'addCls' : 'removeCls'](me.invalidCls + '-field');
}
me.callParent(arguments);
},
/**
* Ensure inputEl is sized well for user input using the remaining
* horizontal space available in the list element
*
* Automatically grows the field to accomodate the height of the selections up to the
* maximum field height allowed. This only takes effect if <tt>{@link #grow} = true</tt>,
* and fires the {@link #autosize} event if the height changes.
*/
autoSize: function() {
var me = this,
height;
if (me.rendered) {
me.doComponentLayout();
if (me.grow) {
height = me.getHeight();
if (height !== me.lastInputHeight) {
me.alignPicker();
me.fireEvent('autosize', height);
me.lastInputHeight = height;
}
}
}
return me;
}
}, function() {
/**
* ExtJS 4.0.5 introduced more optimized ways of referencing child elements. As this is
* currently a subscriber only release, these registrations are performed here for
* backwards compatibility with the currently available public version 4.0.2a
*/
var useNewSelectors = !Ext.getVersion('extjs').isLessThan('4.0.5'),
overrides = {};
if (useNewSelectors) {
Ext.apply(overrides, {
fieldSubTpl: [
'<div class="x-boxselect">',
'<ul id="{cmpId}-itemList" class="x-boxselect-list {fieldCls} {typeCls}">',
'<li id="{cmpId}-inputElCt" class="x-boxselect-input">',
'<input id="{cmpId}-inputEl" type="{type}" ',
'<tpl if="name">name="{name}" </tpl>',
'<tpl if="size">size="{size}" </tpl>',
'<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
'class="x-boxselect-input-field" autocomplete="off" />',
'</li>',
'</ul>',
'<div id="{cmpId}-triggerWrap" class="{triggerWrapCls}" role="presentation">',
'{triggerEl}',
'<div class="{clearCls}" role="presentation"></div>',
'</div>',
'<div class="{clearCls}" role="presentation"></div>',
'</div>',
{
compiled: true,
disableFormats: true
}
],
childEls: ['itemList', 'inputEl', 'inputElCt']
});
} else {
Ext.apply(overrides, {
fieldSubTpl: [
'<div class="x-boxselect">',
'<ul class="x-boxselect-list {fieldCls} {typeCls}">',
'<li class="x-boxselect-input">',
'<input id="{id}" type="{type}" ',
'<tpl if="name">name="{name}" </tpl>',
'<tpl if="size">size="{size}" </tpl>',
'<tpl if="tabIdx">tabIndex="{tabIdx}" </tpl>',
'class="x-boxselect-input-field" autocomplete="off" />',
'</li>',
'</ul>',
'<div class="{triggerWrapCls}" role="presentation">',
'{triggerEl}',
'<div class="{clearCls}" role="presentation"></div>',
'</div>',
'</div>',
{
compiled: true,
disableFormats: true
}
],
renderSelectors: {
itemList: 'ul.x-boxselect-list',
inputEl: 'input.x-boxselect-input-field',
inputElCt: 'li.x-boxselect-input'
}
});
}
Ext.override(this, overrides);
});
/**
* This is an amalgamation of the TextArea field layout and the Trigger field layout,
* with overrides to manage the layout of the field on the itemList wrap instead
* of the inputEl and to grow based on inputEl wrap positioning instead of
* raw text value.
*/
Ext.define('Ext.ux.layout.component.field.BoxSelectField', {
/* Begin Definitions */
alias: ['layout.boxselectfield'],
extend: 'Ext.layout.component.field.Field',
/* End Definitions */
type: 'boxselectfield',
/**
* Overridden to use an encoded value instead of raw value
*/
beforeLayout: function(width, height) {
var me = this,
owner = me.owner,
lastValue = this.lastValue,
value = Ext.encode(owner.value);
this.lastValue = value;
return me.callParent(arguments) || (owner.grow && value !== lastValue);
},
/**
* Overridden to use itemList instead of inputEl, and to merge trigger field
* sizing with text field growability.
*/
sizeBodyContents: function(width, height) {
var me = this,
owner = me.owner,
triggerWrap = owner.triggerWrap,
triggerWidth = owner.getTriggerWidth(),
itemList, inputEl, inputElCt, lastEntry,
listBox, listWidth, inputWidth;
// If we or our ancestor is hidden, we can get a triggerWidth calculation
// of 0. We don't want to resize in this case.
if (owner.hideTrigger || owner.readOnly || triggerWidth > 0) {
itemList = owner.itemList;
// Decrease the field's width by the width of the triggers. Both the field and the triggerWrap
// are floated left in CSS so they'll stack up side by side.
me.setElementSize(itemList, Ext.isNumber(width) ? width - triggerWidth : width, height);
// Explicitly set the triggerWrap's width, to prevent wrapping
triggerWrap.setWidth(triggerWidth);
// Size the input el to take up the maximum amount of remaining list width,
// or the entirety of list width to cause wrapping if too little space remains.
inputEl = owner.inputEl;
inputElCt = owner.inputElCt;
listBox = itemList.getBox(true, true);
listWidth = listBox.width;
if ((owner.grow && owner.growMax && (itemList.dom.scrollHeight > (owner.growMax - 25))) ||
(owner.isFixedHeight() && (itemList.dom.scrollHeight > itemList.dom.clientHeight))) {
listWidth = listWidth - Ext.getScrollbarSize().width;
}
inputWidth = listWidth - 10;
lastEntry = inputElCt.dom.previousSibling;
if (lastEntry) {
inputWidth = inputWidth - (lastEntry.offsetLeft + Ext.fly(lastEntry).getWidth() + Ext.fly(lastEntry).getPadding('lr'));
}
if (inputWidth < 35) {
inputWidth = listWidth - 10;
}
if (inputWidth >= 0) {
me.setElementSize(inputEl, inputWidth);
if (owner.hasFocus) {
inputElCt.scrollIntoView(itemList);
}
}
}
}
});
//{/literal} |
ajax/libs/jquery-mobile/1.3.1/jquery.mobile.js | hanbyul-here/cdnjs | /*
* jQuery Mobile 1.3.1
* Git HEAD hash: 74b4bec049fd93e4fe40205e6157de16eb64eb46 <> Date: Wed Apr 10 2013 21:57:23 UTC
* http://jquerymobile.com
*
* Copyright 2010, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function ( root, doc, factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], function ( $ ) {
factory( $, root, doc );
return $.mobile;
});
} else {
// Browser globals
factory( root.jQuery, root, doc );
}
}( this, document, function ( jQuery, window, document, undefined ) {
(function( $ ) {
$.mobile = {};
}( jQuery ));
(function( $, window, undefined ) {
var nsNormalizeDict = {};
// jQuery.mobile configurable options
$.mobile = $.extend($.mobile, {
// Version of the jQuery Mobile Framework
version: "1.3.1",
// Namespace used framework-wide for data-attrs. Default is no namespace
ns: "",
// Define the url parameter used for referencing widget-generated sub-pages.
// Translates to to example.html&ui-page=subpageIdentifier
// hash segment before &ui-page= is used to make Ajax request
subPageUrlKey: "ui-page",
// Class assigned to page currently in view, and during transitions
activePageClass: "ui-page-active",
// Class used for "active" button state, from CSS framework
activeBtnClass: "ui-btn-active",
// Class used for "focus" form element state, from CSS framework
focusClass: "ui-focus",
// Automatically handle clicks and form submissions through Ajax, when same-domain
ajaxEnabled: true,
// Automatically load and show pages based on location.hash
hashListeningEnabled: true,
// disable to prevent jquery from bothering with links
linkBindingEnabled: true,
// Set default page transition - 'none' for no transitions
defaultPageTransition: "fade",
// Set maximum window width for transitions to apply - 'false' for no limit
maxTransitionWidth: false,
// Minimum scroll distance that will be remembered when returning to a page
minScrollBack: 250,
// DEPRECATED: the following property is no longer in use, but defined until 2.0 to prevent conflicts
touchOverflowEnabled: false,
// Set default dialog transition - 'none' for no transitions
defaultDialogTransition: "pop",
// Error response message - appears when an Ajax page request fails
pageLoadErrorMessage: "Error Loading Page",
// For error messages, which theme does the box uses?
pageLoadErrorMessageTheme: "e",
// replace calls to window.history.back with phonegaps navigation helper
// where it is provided on the window object
phonegapNavigationEnabled: false,
//automatically initialize the DOM when it's ready
autoInitializePage: true,
pushStateEnabled: true,
// allows users to opt in to ignoring content by marking a parent element as
// data-ignored
ignoreContentEnabled: false,
// turn of binding to the native orientationchange due to android orientation behavior
orientationChangeEnabled: true,
buttonMarkup: {
hoverDelay: 200
},
// define the window and the document objects
window: $( window ),
document: $( document ),
// TODO might be useful upstream in jquery itself ?
keyCode: {
ALT: 18,
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
COMMAND: 91,
COMMAND_LEFT: 91, // COMMAND
COMMAND_RIGHT: 93,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
MENU: 93, // COMMAND_RIGHT
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38,
WINDOWS: 91 // COMMAND
},
// Place to store various widget extensions
behaviors: {},
// Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value
silentScroll: function( ypos ) {
if ( $.type( ypos ) !== "number" ) {
ypos = $.mobile.defaultHomeScroll;
}
// prevent scrollstart and scrollstop events
$.event.special.scrollstart.enabled = false;
setTimeout( function() {
window.scrollTo( 0, ypos );
$.mobile.document.trigger( "silentscroll", { x: 0, y: ypos });
}, 20 );
setTimeout( function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
// Expose our cache for testing purposes.
nsNormalizeDict: nsNormalizeDict,
// Take a data attribute property, prepend the namespace
// and then camel case the attribute string. Add the result
// to our nsNormalizeDict so we don't have to do this again.
nsNormalize: function( prop ) {
if ( !prop ) {
return;
}
return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) );
},
// Find the closest parent with a theme class on it. Note that
// we are not using $.fn.closest() on purpose here because this
// method gets called quite a bit and we need it to be as fast
// as possible.
getInheritedTheme: function( el, defaultTheme ) {
var e = el[ 0 ],
ltr = "",
re = /ui-(bar|body|overlay)-([a-z])\b/,
c, m;
while ( e ) {
c = e.className || "";
if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) {
// We found a parent with a theme class
// on it so bail from this loop.
break;
}
e = e.parentNode;
}
// Return the theme letter we found, if none, return the
// specified default.
return ltr || defaultTheme || "a";
},
// TODO the following $ and $.fn extensions can/probably should be moved into jquery.mobile.core.helpers
//
// Find the closest javascript page element to gather settings data jsperf test
// http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit
// possibly naive, but it shows that the parsing overhead for *just* the page selector vs
// the page and dialog selector is negligable. This could probably be speed up by
// doing a similar parent node traversal to the one found in the inherited theme code above
closestPageData: function( $target ) {
return $target
.closest( ':jqmData(role="page"), :jqmData(role="dialog")' )
.data( "mobile-page" );
},
enhanceable: function( $set ) {
return this.haveParents( $set, "enhance" );
},
hijackable: function( $set ) {
return this.haveParents( $set, "ajax" );
},
haveParents: function( $set, attr ) {
if ( !$.mobile.ignoreContentEnabled ) {
return $set;
}
var count = $set.length,
$newSet = $(),
e, $element, excluded;
for ( var i = 0; i < count; i++ ) {
$element = $set.eq( i );
excluded = false;
e = $set[ i ];
while ( e ) {
var c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : "";
if ( c === "false" ) {
excluded = true;
break;
}
e = e.parentNode;
}
if ( !excluded ) {
$newSet = $newSet.add( $element );
}
}
return $newSet;
},
getScreenHeight: function() {
// Native innerHeight returns more accurate value for this across platforms,
// jQuery version is here as a normalized fallback for platforms like Symbian
return window.innerHeight || $.mobile.window.height();
}
}, $.mobile );
// Mobile version of data and removeData and hasData methods
// ensures all data is set and retrieved using jQuery Mobile's data namespace
$.fn.jqmData = function( prop, value ) {
var result;
if ( typeof prop !== "undefined" ) {
if ( prop ) {
prop = $.mobile.nsNormalize( prop );
}
// undefined is permitted as an explicit input for the second param
// in this case it returns the value and does not set it to undefined
if( arguments.length < 2 || value === undefined ){
result = this.data( prop );
} else {
result = this.data( prop, value );
}
}
return result;
};
$.jqmData = function( elem, prop, value ) {
var result;
if ( typeof prop !== "undefined" ) {
result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value );
}
return result;
};
$.fn.jqmRemoveData = function( prop ) {
return this.removeData( $.mobile.nsNormalize( prop ) );
};
$.jqmRemoveData = function( elem, prop ) {
return $.removeData( elem, $.mobile.nsNormalize( prop ) );
};
$.fn.removeWithDependents = function() {
$.removeWithDependents( this );
};
$.removeWithDependents = function( elem ) {
var $elem = $( elem );
( $elem.jqmData( 'dependents' ) || $() ).remove();
$elem.remove();
};
$.fn.addDependents = function( newDependents ) {
$.addDependents( $( this ), newDependents );
};
$.addDependents = function( elem, newDependents ) {
var dependents = $( elem ).jqmData( 'dependents' ) || $();
$( elem ).jqmData( 'dependents', $.merge( dependents, newDependents ) );
};
// note that this helper doesn't attempt to handle the callback
// or setting of an html element's text, its only purpose is
// to return the html encoded version of the text in all cases. (thus the name)
$.fn.getEncodedText = function() {
return $( "<div/>" ).text( $( this ).text() ).html();
};
// fluent helper function for the mobile namespaced equivalent
$.fn.jqmEnhanceable = function() {
return $.mobile.enhanceable( this );
};
$.fn.jqmHijackable = function() {
return $.mobile.hijackable( this );
};
// Monkey-patching Sizzle to filter the :jqmData selector
var oldFind = $.find,
jqmDataRE = /:jqmData\(([^)]*)\)/g;
$.find = function( selector, context, ret, extra ) {
selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" );
return oldFind.call( this, selector, context, ret, extra );
};
$.extend( $.find, oldFind );
$.find.matches = function( expr, set ) {
return $.find( expr, null, null, set );
};
$.find.matchesSelector = function( node, expr ) {
return $.find( expr, null, null, [ node ] ).length > 0;
};
})( jQuery, this );
/*!
* jQuery UI Widget v1.10.0pre - 2012-11-13 (ff055a0c353c3c8ce6e5bfa07ad7cb03e8885bc5)
* http://jqueryui.com
*
* Copyright 2010, 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/jQuery.widget/
*/
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
}
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, prototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.widget", {
// decorate the parent _createWidget to trigger `widgetinit` for users
// who wish to do post post `widgetcreate` alterations/additions
//
// TODO create a pull request for jquery ui to trigger this event
// in the original _createWidget
_createWidget: function() {
$.Widget.prototype._createWidget.apply( this, arguments );
this._trigger( 'init' );
},
_getCreateOptions: function() {
var elem = this.element,
options = {};
$.each( this.options, function( option ) {
var value = elem.jqmData( option.replace( /[A-Z]/g, function( c ) {
return "-" + c.toLowerCase();
})
);
if ( value !== undefined ) {
options[ option ] = value;
}
});
return options;
},
enhanceWithin: function( target, useKeepNative ) {
this.enhance( $( this.options.initSelector, $( target )), useKeepNative );
},
enhance: function( targets, useKeepNative ) {
var page, keepNative, $widgetElements = $( targets ), self = this;
// if ignoreContentEnabled is set to true the framework should
// only enhance the selected elements when they do NOT have a
// parent with the data-namespace-ignore attribute
$widgetElements = $.mobile.enhanceable( $widgetElements );
if ( useKeepNative && $widgetElements.length ) {
// TODO remove dependency on the page widget for the keepNative.
// Currently the keepNative value is defined on the page prototype so
// the method is as well
page = $.mobile.closestPageData( $widgetElements );
keepNative = ( page && page.keepNativeSelector()) || "";
$widgetElements = $widgetElements.not( keepNative );
}
$widgetElements[ this.widgetName ]();
},
raise: function( msg ) {
throw "Widget [" + this.widgetName + "]: " + msg;
}
});
})( jQuery );
(function( $, window ) {
// DEPRECATED
// NOTE global mobile object settings
$.extend( $.mobile, {
// DEPRECATED Should the text be visble in the loading message?
loadingMessageTextVisible: undefined,
// DEPRECATED When the text is visible, what theme does the loading box use?
loadingMessageTheme: undefined,
// DEPRECATED default message setting
loadingMessage: undefined,
// DEPRECATED
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
showPageLoadingMsg: function( theme, msgText, textonly ) {
$.mobile.loading( 'show', theme, msgText, textonly );
},
// DEPRECATED
hidePageLoadingMsg: function() {
$.mobile.loading( 'hide' );
},
loading: function() {
this.loaderWidget.loader.apply( this.loaderWidget, arguments );
}
});
// TODO move loader class down into the widget settings
var loaderClass = "ui-loader", $html = $( "html" ), $window = $.mobile.window;
$.widget( "mobile.loader", {
// NOTE if the global config settings are defined they will override these
// options
options: {
// the theme for the loading message
theme: "a",
// whether the text in the loading message is shown
textVisible: false,
// custom html for the inner content of the loading message
html: "",
// the text to be displayed when the popup is shown
text: "loading"
},
defaultHtml: "<div class='" + loaderClass + "'>" +
"<span class='ui-icon ui-icon-loading'></span>" +
"<h1></h1>" +
"</div>",
// For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top
fakeFixLoader: function() {
var activeBtn = $( "." + $.mobile.activeBtnClass ).first();
this.element
.css({
top: $.support.scrollTop && $window.scrollTop() + $window.height() / 2 ||
activeBtn.length && activeBtn.offset().top || 100
});
},
// check position of loader to see if it appears to be "fixed" to center
// if not, use abs positioning
checkLoaderPosition: function() {
var offset = this.element.offset(),
scrollTop = $window.scrollTop(),
screenHeight = $.mobile.getScreenHeight();
if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) {
this.element.addClass( "ui-loader-fakefix" );
this.fakeFixLoader();
$window
.unbind( "scroll", this.checkLoaderPosition )
.bind( "scroll", $.proxy( this.fakeFixLoader, this ) );
}
},
resetHtml: function() {
this.element.html( $( this.defaultHtml ).html() );
},
// Turn on/off page loading message. Theme doubles as an object argument
// with the following shape: { theme: '', text: '', html: '', textVisible: '' }
// NOTE that the $.mobile.loading* settings and params past the first are deprecated
// TODO sweet jesus we need to break some of this out
show: function( theme, msgText, textonly ) {
var textVisible, message, $header, loadSettings;
this.resetHtml();
// use the prototype options so that people can set them globally at
// mobile init. Consistency, it's what's for dinner
if ( $.type(theme) === "object" ) {
loadSettings = $.extend( {}, this.options, theme );
// prefer object property from the param then the old theme setting
theme = loadSettings.theme || $.mobile.loadingMessageTheme;
} else {
loadSettings = this.options;
// here we prefer the them value passed as a string argument, then
// we prefer the global option because we can't use undefined default
// prototype options, then the prototype option
theme = theme || $.mobile.loadingMessageTheme || loadSettings.theme;
}
// set the message text, prefer the param, then the settings object
// then loading message
message = msgText || $.mobile.loadingMessage || loadSettings.text;
// prepare the dom
$html.addClass( "ui-loading" );
if ( $.mobile.loadingMessage !== false || loadSettings.html ) {
// boolean values require a bit more work :P, supports object properties
// and old settings
if ( $.mobile.loadingMessageTextVisible !== undefined ) {
textVisible = $.mobile.loadingMessageTextVisible;
} else {
textVisible = loadSettings.textVisible;
}
// add the proper css given the options (theme, text, etc)
// Force text visibility if the second argument was supplied, or
// if the text was explicitly set in the object args
this.element.attr("class", loaderClass +
" ui-corner-all ui-body-" + theme +
" ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) +
( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) );
// TODO verify that jquery.fn.html is ok to use in both cases here
// this might be overly defensive in preventing unknowing xss
// if the html attribute is defined on the loading settings, use that
// otherwise use the fallbacks from above
if ( loadSettings.html ) {
this.element.html( loadSettings.html );
} else {
this.element.find( "h1" ).text( message );
}
// attach the loader to the DOM
this.element.appendTo( $.mobile.pageContainer );
// check that the loader is visible
this.checkLoaderPosition();
// on scroll check the loader position
$window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) );
}
},
hide: function() {
$html.removeClass( "ui-loading" );
if ( $.mobile.loadingMessage ) {
this.element.removeClass( "ui-loader-fakefix" );
}
$.mobile.window.unbind( "scroll", this.fakeFixLoader );
$.mobile.window.unbind( "scroll", this.checkLoaderPosition );
}
});
$window.bind( 'pagecontainercreate', function() {
$.mobile.loaderWidget = $.mobile.loaderWidget || $( $.mobile.loader.prototype.defaultHtml ).loader();
});
})(jQuery, this);
// Script: jQuery hashchange event
//
// *Version: 1.3, Last updated: 7/21/2010*
//
// Project Home - http://benalman.com/projects/jquery-hashchange-plugin/
// GitHub - http://github.com/cowboy/jquery-hashchange/
// Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js
// (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
// document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5,
// Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5.
// Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/
//
// About: Known issues
//
// While this jQuery hashchange event implementation is quite stable and
// robust, there are a few unfortunate browser bugs surrounding expected
// hashchange event-based behaviors, independent of any JavaScript
// window.onhashchange abstraction. See the following examples for more
// information:
//
// Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/
// Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/
// WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/
// Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/
//
// Also note that should a browser natively support the window.onhashchange
// event, but not report that it does, the fallback polling loop will be used.
//
// About: Release History
//
// 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more
// "removable" for mobile-only development. Added IE6/7 document.title
// support. Attempted to make Iframe as hidden as possible by using
// techniques from http://www.paciellogroup.com/blog/?p=604. Added
// support for the "shortcut" format $(window).hashchange( fn ) and
// $(window).hashchange() like jQuery provides for built-in events.
// Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and
// lowered its default value to 50. Added <jQuery.fn.hashchange.domain>
// and <jQuery.fn.hashchange.src> properties plus document-domain.html
// file to address access denied issues when setting document.domain in
// IE6/7.
// 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin
// from a page on another domain would cause an error in Safari 4. Also,
// IE6/7 Iframe is now inserted after the body (this actually works),
// which prevents the page from scrolling when the event is first bound.
// Event can also now be bound before DOM ready, but it won't be usable
// before then in IE6/7.
// 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug
// where browser version is incorrectly reported as 8.0, despite
// inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag.
// 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special
// window.onhashchange functionality into a separate plugin for users
// who want just the basic event & back button support, without all the
// extra awesomeness that BBQ provides. This plugin will be included as
// part of jQuery BBQ, but also be available separately.
(function( $, window, undefined ) {
// Reused string.
var str_hashchange = 'hashchange',
// Method / object references.
doc = document,
fake_onhashchange,
special = $.event.special,
// Does the browser support window.onhashchange? Note that IE8 running in
// IE7 compatibility mode reports true for 'onhashchange' in window, even
// though the event isn't supported, so also test document.documentMode.
doc_mode = doc.documentMode,
supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 );
// Get location.hash (or what you'd expect location.hash to be) sans any
// leading #. Thanks for making this necessary, Firefox!
function get_fragment( url ) {
url = url || location.href;
return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
};
// Method: jQuery.fn.hashchange
//
// Bind a handler to the window.onhashchange event or trigger all bound
// window.onhashchange event handlers. This behavior is consistent with
// jQuery's built-in event handlers.
//
// Usage:
//
// > jQuery(window).hashchange( [ handler ] );
//
// Arguments:
//
// handler - (Function) Optional handler to be bound to the hashchange
// event. This is a "shortcut" for the more verbose form:
// jQuery(window).bind( 'hashchange', handler ). If handler is omitted,
// all bound window.onhashchange event handlers will be triggered. This
// is a shortcut for the more verbose
// jQuery(window).trigger( 'hashchange' ). These forms are described in
// the <hashchange event> section.
//
// Returns:
//
// (jQuery) The initial jQuery collection of elements.
// Allow the "shortcut" format $(elem).hashchange( fn ) for binding and
// $(elem).hashchange() for triggering, like jQuery does for built-in events.
$.fn[ str_hashchange ] = function( fn ) {
return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange );
};
// Property: jQuery.fn.hashchange.delay
//
// The numeric interval (in milliseconds) at which the <hashchange event>
// polling loop executes. Defaults to 50.
// Property: jQuery.fn.hashchange.domain
//
// If you're setting document.domain in your JavaScript, and you want hash
// history to work in IE6/7, not only must this property be set, but you must
// also set document.domain BEFORE jQuery is loaded into the page. This
// property is only applicable if you are supporting IE6/7 (or IE8 operating
// in "IE7 compatibility" mode).
//
// In addition, the <jQuery.fn.hashchange.src> property must be set to the
// path of the included "document-domain.html" file, which can be renamed or
// modified if necessary (note that the document.domain specified must be the
// same in both your main JavaScript as well as in this file).
//
// Usage:
//
// jQuery.fn.hashchange.domain = document.domain;
// Property: jQuery.fn.hashchange.src
//
// If, for some reason, you need to specify an Iframe src file (for example,
// when setting document.domain as in <jQuery.fn.hashchange.domain>), you can
// do so using this property. Note that when using this property, history
// won't be recorded in IE6/7 until the Iframe src file loads. This property
// is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7
// compatibility" mode).
//
// Usage:
//
// jQuery.fn.hashchange.src = 'path/to/file.html';
$.fn[ str_hashchange ].delay = 50;
/*
$.fn[ str_hashchange ].domain = null;
$.fn[ str_hashchange ].src = null;
*/
// Event: hashchange event
//
// Fired when location.hash changes. In browsers that support it, the native
// HTML5 window.onhashchange event is used, otherwise a polling loop is
// initialized, running every <jQuery.fn.hashchange.delay> milliseconds to
// see if the hash has changed. In IE6/7 (and IE8 operating in "IE7
// compatibility" mode), a hidden Iframe is created to allow the back button
// and hash-based history to work.
//
// Usage as described in <jQuery.fn.hashchange>:
//
// > // Bind an event handler.
// > jQuery(window).hashchange( function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).hashchange();
//
// A more verbose usage that allows for event namespacing:
//
// > // Bind an event handler.
// > jQuery(window).bind( 'hashchange', function(e) {
// > var hash = location.hash;
// > ...
// > });
// >
// > // Manually trigger the event handler.
// > jQuery(window).trigger( 'hashchange' );
//
// Additional Notes:
//
// * The polling loop and Iframe are not created until at least one handler
// is actually bound to the 'hashchange' event.
// * If you need the bound handler(s) to execute immediately, in cases where
// a location.hash exists on page load, via bookmark or page refresh for
// example, use jQuery(window).hashchange() or the more verbose
// jQuery(window).trigger( 'hashchange' ).
// * The event can be bound before DOM ready, but since it won't be usable
// before then in IE6/7 (due to the necessary Iframe), recommended usage is
// to bind it inside a DOM ready handler.
// Override existing $.event.special.hashchange methods (allowing this plugin
// to be defined after jQuery BBQ in BBQ's source code).
special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
// Called only when the first 'hashchange' event is bound to window.
setup: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to create our own. And we don't want to call this
// until the user binds to the event, just in case they never do, since it
// will create a polling loop and possibly even a hidden Iframe.
$( fake_onhashchange.start );
},
// Called only when the last 'hashchange' event is unbound from window.
teardown: function() {
// If window.onhashchange is supported natively, there's nothing to do..
if ( supports_onhashchange ) { return false; }
// Otherwise, we need to stop ours (if possible).
$( fake_onhashchange.stop );
}
});
// fake_onhashchange does all the work of triggering the window.onhashchange
// event for browsers that don't natively support it, including creating a
// polling loop to watch for hash changes and in IE 6/7 creating a hidden
// Iframe to enable back and forward.
fake_onhashchange = (function() {
var self = {},
timeout_id,
// Remember the initial hash so it doesn't get triggered immediately.
last_hash = get_fragment(),
fn_retval = function( val ) { return val; },
history_set = fn_retval,
history_get = fn_retval;
// Start the polling loop.
self.start = function() {
timeout_id || poll();
};
// Stop the polling loop.
self.stop = function() {
timeout_id && clearTimeout( timeout_id );
timeout_id = undefined;
};
// This polling loop checks every $.fn.hashchange.delay milliseconds to see
// if location.hash has changed, and triggers the 'hashchange' event on
// window when necessary.
function poll() {
var hash = get_fragment(),
history_hash = history_get( last_hash );
if ( hash !== last_hash ) {
history_set( last_hash = hash, history_hash );
$(window).trigger( str_hashchange );
} else if ( history_hash !== last_hash ) {
location.href = location.href.replace( /#.*/, '' ) + history_hash;
}
timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
};
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
// vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
window.attachEvent && !window.addEventListener && !supports_onhashchange && (function() {
// Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
// when running in "IE7 compatibility" mode.
var iframe,
iframe_src;
// When the event is bound and polling starts in IE 6/7, create a hidden
// Iframe for history handling.
self.start = function() {
if ( !iframe ) {
iframe_src = $.fn[ str_hashchange ].src;
iframe_src = iframe_src && iframe_src + get_fragment();
// Create hidden Iframe. Attempt to make Iframe as hidden as possible
// by using techniques from http://www.paciellogroup.com/blog/?p=604.
iframe = $('<iframe tabindex="-1" title="empty"/>').hide()
// When Iframe has completely loaded, initialize the history and
// start polling.
.one( 'load', function() {
iframe_src || history_set( get_fragment() );
poll();
})
// Load Iframe src if specified, otherwise nothing.
.attr( 'src', iframe_src || 'javascript:0' )
// Append Iframe after the end of the body to prevent unnecessary
// initial page scrolling (yes, this works).
.insertAfter( 'body' )[0].contentWindow;
// Whenever `document.title` changes, update the Iframe's title to
// prettify the back/next history menu entries. Since IE sometimes
// errors with "Unspecified error" the very first time this is set
// (yes, very useful) wrap this with a try/catch block.
doc.onpropertychange = function() {
try {
if ( event.propertyName === 'title' ) {
iframe.document.title = doc.title;
}
} catch(e) {}
};
}
};
// Override the "stop" method since an IE6/7 Iframe was created. Even
// if there are no longer any bound event handlers, the polling loop
// is still necessary for back/next to work at all!
self.stop = fn_retval;
// Get history by looking at the hidden Iframe's location.hash.
history_get = function() {
return get_fragment( iframe.location.href );
};
// Set a new history item by opening and then closing the Iframe
// document, *then* setting its location.hash. If document.domain has
// been set, update that as well.
history_set = function( hash, history_hash ) {
var iframe_doc = iframe.document,
domain = $.fn[ str_hashchange ].domain;
if ( hash !== history_hash ) {
// Update Iframe with any initial `document.title` that might be set.
iframe_doc.title = doc.title;
// Opening the Iframe's document after it has been closed is what
// actually adds a history entry.
iframe_doc.open();
// Set document.domain for the Iframe document as well, if necessary.
domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' );
iframe_doc.close();
// Update the Iframe's hash, for great justice.
iframe.location.hash = hash;
}
};
})();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return self;
})();
})(jQuery,this);
(function( $, undefined ) {
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
window.matchMedia = window.matchMedia || (function( doc, undefined ) {
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement( "body" ),
div = doc.createElement( "div" );
div.id = "mq-test-1";
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = "­<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";
docElem.insertBefore( fakeBody, refNode );
bool = div.offsetWidth === 42;
docElem.removeChild( fakeBody );
return {
matches: bool,
media: q
};
};
}( document ));
// $.mobile.media uses matchMedia to return a boolean.
$.mobile.media = function( q ) {
return window.matchMedia( q ).matches;
};
})(jQuery);
(function( $, undefined ) {
var support = {
touch: "ontouchend" in document
};
$.mobile.support = $.mobile.support || {};
$.extend( $.support, support );
$.extend( $.mobile.support, support );
}( jQuery ));
(function( $, undefined ) {
$.extend( $.support, {
orientation: "orientation" in window && "onorientationchange" in window
});
}( jQuery ));
(function( $, undefined ) {
// thx Modernizr
function propExists( prop ) {
var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " );
for ( var v in props ) {
if ( fbCSS[ props[ v ] ] !== undefined ) {
return true;
}
}
}
var fakeBody = $( "<body>" ).prependTo( "html" ),
fbCSS = fakeBody[ 0 ].style,
vendors = [ "Webkit", "Moz", "O" ],
webos = "palmGetResource" in window, //only used to rule out scrollTop
opera = window.opera,
operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]",
bb = window.blackberry && !propExists( "-webkit-transform" ); //only used to rule out box shadow, as it's filled opaque on BB 5 and lower
function validStyle( prop, value, check_vend ) {
var div = document.createElement( 'div' ),
uc = function( txt ) {
return txt.charAt( 0 ).toUpperCase() + txt.substr( 1 );
},
vend_pref = function( vend ) {
if( vend === "" ) {
return "";
} else {
return "-" + vend.charAt( 0 ).toLowerCase() + vend.substr( 1 ) + "-";
}
},
check_style = function( vend ) {
var vend_prop = vend_pref( vend ) + prop + ": " + value + ";",
uc_vend = uc( vend ),
propStyle = uc_vend + ( uc_vend === "" ? prop : uc( prop ) );
div.setAttribute( "style", vend_prop );
if ( !!div.style[ propStyle ] ) {
ret = true;
}
},
check_vends = check_vend ? check_vend : vendors,
ret;
for( var i = 0; i < check_vends.length; i++ ) {
check_style( check_vends[i] );
}
return !!ret;
}
function transform3dTest() {
var mqProp = "transform-3d",
// Because the `translate3d` test below throws false positives in Android:
ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" );
if( ret ) {
return !!ret;
}
var el = document.createElement( "div" ),
transforms = {
// We’re omitting Opera for the time being; MS uses unprefixed.
'MozTransform':'-moz-transform',
'transform':'transform'
};
fakeBody.append( el );
for ( var t in transforms ) {
if( el.style[ t ] !== undefined ){
el.style[ t ] = 'translate3d( 100px, 1px, 1px )';
ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] );
}
}
return ( !!ret && ret !== "none" );
}
// Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting )
function baseTagTest() {
var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/",
base = $( "head base" ),
fauxEle = null,
href = "",
link, rebase;
if ( !base.length ) {
base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" );
} else {
href = base.attr( "href" );
}
link = $( "<a href='testurl' />" ).prependTo( fakeBody );
rebase = link[ 0 ].href;
base[ 0 ].href = href || location.pathname;
if ( fauxEle ) {
fauxEle.remove();
}
return rebase.indexOf( fauxBase ) === 0;
}
// Thanks Modernizr
function cssPointerEventsTest() {
var element = document.createElement( 'x' ),
documentElement = document.documentElement,
getComputedStyle = window.getComputedStyle,
supports;
if ( !( 'pointerEvents' in element.style ) ) {
return false;
}
element.style.pointerEvents = 'auto';
element.style.pointerEvents = 'x';
documentElement.appendChild( element );
supports = getComputedStyle &&
getComputedStyle( element, '' ).pointerEvents === 'auto';
documentElement.removeChild( element );
return !!supports;
}
function boundingRect() {
var div = document.createElement( "div" );
return typeof div.getBoundingClientRect !== "undefined";
}
// non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683
// allows for inclusion of IE 6+, including Windows Mobile 7
$.extend( $.mobile, { browser: {} } );
$.mobile.browser.oldIE = (function() {
var v = 3,
div = document.createElement( "div" ),
a = div.all || [];
do {
div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->";
} while( a[0] );
return v > 4 ? v : !v;
})();
function fixedPosition() {
var w = window,
ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
ffmatch = ua.match( /Fennec\/([0-9]+)/ ),
ffversion = !!ffmatch && ffmatch[ 1 ],
operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ),
omversion = !!operammobilematch && operammobilematch[ 1 ];
if(
// iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) ||
// Opera Mini
( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) ||
( operammobilematch && omversion < 7458 ) ||
//Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) ||
// Firefox Mobile before 6.0 -
( ffversion && ffversion < 6 ) ||
// WebOS less than 3
( "palmGetResource" in window && wkversion && wkversion < 534 ) ||
// MeeGo
( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) {
return false;
}
return true;
}
$.extend( $.support, {
cssTransitions: "WebKitTransitionEvent" in window ||
validStyle( 'transition', 'height 100ms linear', [ "Webkit", "Moz", "" ] ) &&
!$.mobile.browser.oldIE && !opera,
// Note, Chrome for iOS has an extremely quirky implementation of popstate.
// We've chosen to take the shortest path to a bug fix here for issue #5426
// See the following link for information about the regex chosen
// https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent
pushState: "pushState" in history &&
"replaceState" in history &&
// When running inside a FF iframe, calling replaceState causes an error
!( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) &&
( window.navigator.userAgent.search(/CriOS/) === -1 ),
mediaquery: $.mobile.media( "only all" ),
cssPseudoElement: !!propExists( "content" ),
touchOverflow: !!propExists( "overflowScrolling" ),
cssTransform3d: transform3dTest(),
boxShadow: !!propExists( "boxShadow" ) && !bb,
fixedPosition: fixedPosition(),
scrollTop: ("pageXOffset" in window ||
"scrollTop" in document.documentElement ||
"scrollTop" in fakeBody[ 0 ]) && !webos && !operamini,
dynamicBaseTag: baseTagTest(),
cssPointerEvents: cssPointerEventsTest(),
boundingRect: boundingRect()
});
fakeBody.remove();
// $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian)
// or that generally work better browsing in regular http for full page refreshes (Opera Mini)
// Note: This detection below is used as a last resort.
// We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible
var nokiaLTE7_3 = (function() {
var ua = window.navigator.userAgent;
//The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older
return ua.indexOf( "Nokia" ) > -1 &&
( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) &&
ua.indexOf( "AppleWebKit" ) > -1 &&
ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ );
})();
// Support conditions that must be met in order to proceed
// default enhanced qualifications are media query support OR IE 7+
$.mobile.gradeA = function() {
return ( $.support.mediaquery || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 7 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null );
};
$.mobile.ajaxBlacklist =
// BlackBerry browsers, pre-webkit
window.blackberry && !window.WebKitPoint ||
// Opera Mini
operamini ||
// Symbian webkits pre 7.3
nokiaLTE7_3;
// Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices
// to render the stylesheets when they're referenced before this script, as we'd recommend doing.
// This simply reappends the CSS in place, which for some reason makes it apply
if ( nokiaLTE7_3 ) {
$(function() {
$( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" );
});
}
// For ruling out shadows via css
if ( !$.support.boxShadow ) {
$( "html" ).addClass( "ui-mobile-nosupport-boxshadow" );
}
})( jQuery );
(function( $, undefined ) {
var $win = $.mobile.window, self, history;
$.event.special.navigate = self = {
bound: false,
pushStateEnabled: true,
originalEventName: undefined,
// If pushstate support is present and push state support is defined to
// be true on the mobile namespace.
isPushStateEnabled: function() {
return $.support.pushState &&
$.mobile.pushStateEnabled === true &&
this.isHashChangeEnabled();
},
// !! assumes mobile namespace is present
isHashChangeEnabled: function() {
return $.mobile.hashListeningEnabled === true;
},
// TODO a lot of duplication between popstate and hashchange
popstate: function( event ) {
var newEvent = new $.Event( "navigate" ),
beforeNavigate = new $.Event( "beforenavigate" ),
state = event.originalEvent.state || {},
href = location.href;
$win.trigger( beforeNavigate );
if( beforeNavigate.isDefaultPrevented() ){
return;
}
if( event.historyState ){
$.extend(state, event.historyState);
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// NOTE we let the current stack unwind because any assignment to
// location.hash will stop the world and run this event handler. By
// doing this we create a similar behavior to hashchange on hash
// assignment
setTimeout(function() {
$win.trigger( newEvent, {
state: state
});
}, 0);
},
hashchange: function( event, data ) {
var newEvent = new $.Event( "navigate" ),
beforeNavigate = new $.Event( "beforenavigate" );
$win.trigger( beforeNavigate );
if( beforeNavigate.isDefaultPrevented() ){
return;
}
// Make sure the original event is tracked for the end
// user to inspect incase they want to do something special
newEvent.originalEvent = event;
// Trigger the hashchange with state provided by the user
// that altered the hash
$win.trigger( newEvent, {
// Users that want to fully normalize the two events
// will need to do history management down the stack and
// add the state to the event before this binding is fired
// TODO consider allowing for the explicit addition of callbacks
// to be fired before this value is set to avoid event timing issues
state: event.hashchangeState || {}
});
},
// TODO We really only want to set this up once
// but I'm not clear if there's a beter way to achieve
// this with the jQuery special event structure
setup: function( data, namespaces ) {
if( self.bound ) {
return;
}
self.bound = true;
if( self.isPushStateEnabled() ) {
self.originalEventName = "popstate";
$win.bind( "popstate.navigate", self.popstate );
} else if ( self.isHashChangeEnabled() ){
self.originalEventName = "hashchange";
$win.bind( "hashchange.navigate", self.hashchange );
}
}
};
})( jQuery );
(function( $, undefined ) {
var path, documentBase, $base, dialogHashKey = "&ui-state=dialog";
$.mobile.path = path = {
uiStateKey: "&ui-state",
// This scary looking regular expression parses an absolute URL or its relative
// variants (protocol, site, document, query, and hash), into the various
// components (protocol, host, path, query, fragment, etc that make up the
// URL as well as some other commonly used sub-parts. When used with RegExp.exec()
// or String.match, it parses the URL into a results array that looks like this:
//
// [0]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread#msg-content
// [1]: http://jblas:[email protected]:8080/mail/inbox?msg=1234&type=unread
// [2]: http://jblas:[email protected]:8080/mail/inbox
// [3]: http://jblas:[email protected]:8080
// [4]: http:
// [5]: //
// [6]: jblas:[email protected]:8080
// [7]: jblas:password
// [8]: jblas
// [9]: password
// [10]: mycompany.com:8080
// [11]: mycompany.com
// [12]: 8080
// [13]: /mail/inbox
// [14]: /mail/
// [15]: inbox
// [16]: ?msg=1234&type=unread
// [17]: #msg-content
//
urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
// Abstraction to address xss (Issue #4787) by removing the authority in
// browsers that auto decode it. All references to location.href should be
// replaced with a call to this method so that it can be dealt with properly here
getLocation: function( url ) {
var uri = url ? this.parseUrl( url ) : location,
hash = this.parseUrl( url || location.href ).hash;
// mimic the browser with an empty string when the hash is empty
hash = hash === "#" ? "" : hash;
// Make sure to parse the url or the location object for the hash because using location.hash
// is autodecoded in firefox, the rest of the url should be from the object (location unless
// we're testing) to avoid the inclusion of the authority
return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash;
},
parseLocation: function() {
return this.parseUrl( this.getLocation() );
},
//Parse a URL into a structure that allows easy access to
//all of the URL components by name.
parseUrl: function( url ) {
// If we're passed an object, we'll assume that it is
// a parsed url object and just return it back to the caller.
if ( $.type( url ) === "object" ) {
return url;
}
var matches = path.urlParseRE.exec( url || "" ) || [];
// Create an object that allows the caller to access the sub-matches
// by name. Note that IE returns an empty string instead of undefined,
// like all other browsers do, so we normalize everything so its consistent
// no matter what browser we're running on.
return {
href: matches[ 0 ] || "",
hrefNoHash: matches[ 1 ] || "",
hrefNoSearch: matches[ 2 ] || "",
domain: matches[ 3 ] || "",
protocol: matches[ 4 ] || "",
doubleSlash: matches[ 5 ] || "",
authority: matches[ 6 ] || "",
username: matches[ 8 ] || "",
password: matches[ 9 ] || "",
host: matches[ 10 ] || "",
hostname: matches[ 11 ] || "",
port: matches[ 12 ] || "",
pathname: matches[ 13 ] || "",
directory: matches[ 14 ] || "",
filename: matches[ 15 ] || "",
search: matches[ 16 ] || "",
hash: matches[ 17 ] || ""
};
},
//Turn relPath into an asbolute path. absPath is
//an optional absolute path which describes what
//relPath is relative to.
makePathAbsolute: function( relPath, absPath ) {
if ( relPath && relPath.charAt( 0 ) === "/" ) {
return relPath;
}
relPath = relPath || "";
absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : "";
var absStack = absPath ? absPath.split( "/" ) : [],
relStack = relPath.split( "/" );
for ( var i = 0; i < relStack.length; i++ ) {
var d = relStack[ i ];
switch ( d ) {
case ".":
break;
case "..":
if ( absStack.length ) {
absStack.pop();
}
break;
default:
absStack.push( d );
break;
}
}
return "/" + absStack.join( "/" );
},
//Returns true if both urls have the same domain.
isSameDomain: function( absUrl1, absUrl2 ) {
return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain;
},
//Returns true for any relative variant.
isRelativeUrl: function( url ) {
// All relative Url variants have one thing in common, no protocol.
return path.parseUrl( url ).protocol === "";
},
//Returns true for an absolute url.
isAbsoluteUrl: function( url ) {
return path.parseUrl( url ).protocol !== "";
},
//Turn the specified realtive URL into an absolute one. This function
//can handle all relative variants (protocol, site, document, query, fragment).
makeUrlAbsolute: function( relUrl, absUrl ) {
if ( !path.isRelativeUrl( relUrl ) ) {
return relUrl;
}
if ( absUrl === undefined ) {
absUrl = this.documentBase;
}
var relObj = path.parseUrl( relUrl ),
absObj = path.parseUrl( absUrl ),
protocol = relObj.protocol || absObj.protocol,
doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ),
authority = relObj.authority || absObj.authority,
hasPath = relObj.pathname !== "",
pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ),
search = relObj.search || ( !hasPath && absObj.search ) || "",
hash = relObj.hash;
return protocol + doubleSlash + authority + pathname + search + hash;
},
//Add search (aka query) params to the specified url.
addSearchParams: function( url, params ) {
var u = path.parseUrl( url ),
p = ( typeof params === "object" ) ? $.param( params ) : params,
s = u.search || "?";
return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" );
},
convertUrlToDataUrl: function( absUrl ) {
var u = path.parseUrl( absUrl );
if ( path.isEmbeddedPage( u ) ) {
// For embedded pages, remove the dialog hash key as in getFilePath(),
// and remove otherwise the Data Url won't match the id of the embedded Page.
return u.hash
.split( dialogHashKey )[0]
.replace( /^#/, "" )
.replace( /\?.*$/, "" );
} else if ( path.isSameDomain( u, this.documentBase ) ) {
return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0];
}
return window.decodeURIComponent(absUrl);
},
//get path from current hash, or from a file path
get: function( newPath ) {
if ( newPath === undefined ) {
newPath = path.parseLocation().hash;
}
return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, '' );
},
//set location hash to path
set: function( path ) {
location.hash = path;
},
//test if a given url (string) is a path
//NOTE might be exceptionally naive
isPath: function( url ) {
return ( /\// ).test( url );
},
//return a url path with the window's location protocol/hostname/pathname removed
clean: function( url ) {
return url.replace( this.documentBase.domain, "" );
},
//just return the url without an initial #
stripHash: function( url ) {
return url.replace( /^#/, "" );
},
stripQueryParams: function( url ) {
return url.replace( /\?.*$/, "" );
},
//remove the preceding hash, any query params, and dialog notations
cleanHash: function( hash ) {
return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) );
},
isHashValid: function( hash ) {
return ( /^#[^#]+$/ ).test( hash );
},
//check whether a url is referencing the same domain, or an external domain or different protocol
//could be mailto, etc
isExternal: function( url ) {
var u = path.parseUrl( url );
return u.protocol && u.domain !== this.documentUrl.domain ? true : false;
},
hasProtocol: function( url ) {
return ( /^(:?\w+:)/ ).test( url );
},
isEmbeddedPage: function( url ) {
var u = path.parseUrl( url );
//if the path is absolute, then we need to compare the url against
//both the this.documentUrl and the documentBase. The main reason for this
//is that links embedded within external documents will refer to the
//application document, whereas links embedded within the application
//document will be resolved against the document base.
if ( u.protocol !== "" ) {
return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) );
}
return ( /^#/ ).test( u.href );
},
squash: function( url, resolutionUrl ) {
var state, href, cleanedUrl, search, stateIndex,
isPath = this.isPath( url ),
uri = this.parseUrl( url ),
preservedHash = uri.hash,
uiState = "";
// produce a url against which we can resole the provided path
resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl());
// If the url is anything but a simple string, remove any preceding hash
// eg #foo/bar -> foo/bar
// #foo -> #foo
cleanedUrl = isPath ? path.stripHash( url ) : url;
// If the url is a full url with a hash check if the parsed hash is a path
// if it is, strip the #, and use it otherwise continue without change
cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl;
// Split the UI State keys off the href
stateIndex = cleanedUrl.indexOf( this.uiStateKey );
// store the ui state keys for use
if( stateIndex > -1 ){
uiState = cleanedUrl.slice( stateIndex );
cleanedUrl = cleanedUrl.slice( 0, stateIndex );
}
// make the cleanedUrl absolute relative to the resolution url
href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl );
// grab the search from the resolved url since parsing from
// the passed url may not yield the correct result
search = this.parseUrl( href ).search;
// TODO all this crap is terrible, clean it up
if ( isPath ) {
// reject the hash if it's a path or it's just a dialog key
if( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) {
preservedHash = "";
}
// Append the UI State keys where it exists and it's been removed
// from the url
if( uiState && preservedHash.indexOf( this.uiStateKey ) === -1){
preservedHash += uiState;
}
// make sure that pound is on the front of the hash
if( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ){
preservedHash = "#" + preservedHash;
}
// reconstruct each of the pieces with the new search string and hash
href = path.parseUrl( href );
href = href.protocol + "//" + href.host + href.pathname + search + preservedHash;
} else {
href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState;
}
return href;
},
isPreservableHash: function( hash ) {
return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0;
}
};
path.documentUrl = path.parseLocation();
$base = $( "head" ).find( "base" );
path.documentBase = $base.length ?
path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) :
path.documentUrl;
path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash);
//return the original document url
path.getDocumentUrl = function( asParsedObject ) {
return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href;
};
//return the original document base url
path.getDocumentBase = function( asParsedObject ) {
return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href;
};
})( jQuery );
(function( $, undefined ) {
var path = $.mobile.path;
$.mobile.History = function( stack, index ) {
this.stack = stack || [];
this.activeIndex = index || 0;
};
$.extend($.mobile.History.prototype, {
getActive: function() {
return this.stack[ this.activeIndex ];
},
getLast: function() {
return this.stack[ this.previousIndex ];
},
getNext: function() {
return this.stack[ this.activeIndex + 1 ];
},
getPrev: function() {
return this.stack[ this.activeIndex - 1 ];
},
// addNew is used whenever a new page is added
add: function( url, data ){
data = data || {};
//if there's forward history, wipe it
if ( this.getNext() ) {
this.clearForward();
}
// if the hash is included in the data make sure the shape
// is consistent for comparison
if( data.hash && data.hash.indexOf( "#" ) === -1) {
data.hash = "#" + data.hash;
}
data.url = url;
this.stack.push( data );
this.activeIndex = this.stack.length - 1;
},
//wipe urls ahead of active index
clearForward: function() {
this.stack = this.stack.slice( 0, this.activeIndex + 1 );
},
find: function( url, stack, earlyReturn ) {
stack = stack || this.stack;
var entry, i, length = stack.length, index;
for ( i = 0; i < length; i++ ) {
entry = stack[i];
if ( decodeURIComponent(url) === decodeURIComponent(entry.url) ||
decodeURIComponent(url) === decodeURIComponent(entry.hash) ) {
index = i;
if( earlyReturn ) {
return index;
}
}
}
return index;
},
closest: function( url ) {
var closest, a = this.activeIndex;
// First, take the slice of the history stack before the current index and search
// for a url match. If one is found, we'll avoid avoid looking through forward history
// NOTE the preference for backward history movement is driven by the fact that
// most mobile browsers only have a dedicated back button, and users rarely use
// the forward button in desktop browser anyhow
closest = this.find( url, this.stack.slice(0, a) );
// If nothing was found in backward history check forward. The `true`
// value passed as the third parameter causes the find method to break
// on the first match in the forward history slice. The starting index
// of the slice must then be added to the result to get the element index
// in the original history stack :( :(
//
// TODO this is hyper confusing and should be cleaned up (ugh so bad)
if( closest === undefined ) {
closest = this.find( url, this.stack.slice(a), true );
closest = closest === undefined ? closest : closest + a;
}
return closest;
},
direct: function( opts ) {
var newActiveIndex = this.closest( opts.url ), a = this.activeIndex;
// save new page index, null check to prevent falsey 0 result
// record the previous index for reference
if( newActiveIndex !== undefined ) {
this.activeIndex = newActiveIndex;
this.previousIndex = a;
}
// invoke callbacks where appropriate
//
// TODO this is also convoluted and confusing
if ( newActiveIndex < a ) {
( opts.present || opts.back || $.noop )( this.getActive(), 'back' );
} else if ( newActiveIndex > a ) {
( opts.present || opts.forward || $.noop )( this.getActive(), 'forward' );
} else if ( newActiveIndex === undefined && opts.missing ){
opts.missing( this.getActive() );
}
}
});
})( jQuery );
(function( $, undefined ) {
var path = $.mobile.path,
initialHref = location.href;
$.mobile.Navigator = function( history ) {
this.history = history;
this.ignoreInitialHashChange = true;
$.mobile.window.bind({
"popstate.history": $.proxy( this.popstate, this ),
"hashchange.history": $.proxy( this.hashchange, this )
});
};
$.extend($.mobile.Navigator.prototype, {
squash: function( url, data ) {
var state, href, hash = path.isPath(url) ? path.stripHash(url) : url;
href = path.squash( url );
// make sure to provide this information when it isn't explicitly set in the
// data object that was passed to the squash method
state = $.extend({
hash: hash,
url: href
}, data);
// replace the current url with the new href and store the state
// Note that in some cases we might be replacing an url with the
// same url. We do this anyways because we need to make sure that
// all of our history entries have a state object associated with
// them. This allows us to work around the case where $.mobile.back()
// is called to transition from an external page to an embedded page.
// In that particular case, a hashchange event is *NOT* generated by the browser.
// Ensuring each history entry has a state object means that onPopState()
// will always trigger our hashchange callback even when a hashchange event
// is not fired.
window.history.replaceState( state, state.title || document.title, href );
return state;
},
hash: function( url, href ) {
var parsed, loc, hash;
// Grab the hash for recording. If the passed url is a path
// we used the parsed version of the squashed url to reconstruct,
// otherwise we assume it's a hash and store it directly
parsed = path.parseUrl( url );
loc = path.parseLocation();
if( loc.pathname + loc.search === parsed.pathname + parsed.search ) {
// If the pathname and search of the passed url is identical to the current loc
// then we must use the hash. Otherwise there will be no event
// eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz"
hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search;
} else if ( path.isPath(url) ) {
var resolved = path.parseUrl( href );
// If the passed url is a path, make it domain relative and remove any trailing hash
hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : "");
} else {
hash = url;
}
return hash;
},
// TODO reconsider name
go: function( url, data, noEvents ) {
var state, href, hash, popstateEvent,
isPopStateEvent = $.event.special.navigate.isPushStateEnabled();
// Get the url as it would look squashed on to the current resolution url
href = path.squash( url );
// sort out what the hash sould be from the url
hash = this.hash( url, href );
// Here we prevent the next hash change or popstate event from doing any
// history management. In the case of hashchange we don't swallow it
// if there will be no hashchange fired (since that won't reset the value)
// and will swallow the following hashchange
if( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) {
this.preventNextHashChange = noEvents;
}
// IMPORTANT in the case where popstate is supported the event will be triggered
// directly, stopping further execution - ie, interupting the flow of this
// method call to fire bindings at this expression. Below the navigate method
// there is a binding to catch this event and stop its propagation.
//
// We then trigger a new popstate event on the window with a null state
// so that the navigate events can conclude their work properly
//
// if the url is a path we want to preserve the query params that are available on
// the current url.
this.preventHashAssignPopState = true;
window.location.hash = hash;
// If popstate is enabled and the browser triggers `popstate` events when the hash
// is set (this often happens immediately in browsers like Chrome), then the
// this flag will be set to false already. If it's a browser that does not trigger
// a `popstate` on hash assignement or `replaceState` then we need avoid the branch
// that swallows the event created by the popstate generated by the hash assignment
// At the time of this writing this happens with Opera 12 and some version of IE
this.preventHashAssignPopState = false;
state = $.extend({
url: href,
hash: hash,
title: document.title
}, data);
if( isPopStateEvent ) {
popstateEvent = new $.Event( "popstate" );
popstateEvent.originalEvent = {
type: "popstate",
state: null
};
this.squash( url, state );
// Trigger a new faux popstate event to replace the one that we
// caught that was triggered by the hash setting above.
if( !noEvents ) {
this.ignorePopState = true;
$.mobile.window.trigger( popstateEvent );
}
}
// record the history entry so that the information can be included
// in hashchange event driven navigate events in a similar fashion to
// the state that's provided by popstate
this.history.add( state.url, state );
},
// This binding is intended to catch the popstate events that are fired
// when execution of the `$.navigate` method stops at window.location.hash = url;
// and completely prevent them from propagating. The popstate event will then be
// retriggered after execution resumes
//
// TODO grab the original event here and use it for the synthetic event in the
// second half of the navigate execution that will follow this binding
popstate: function( event ) {
var active, hash, state, closestIndex;
// Partly to support our test suite which manually alters the support
// value to test hashchange. Partly to prevent all around weirdness
if( !$.event.special.navigate.isPushStateEnabled() ){
return;
}
// If this is the popstate triggered by the actual alteration of the hash
// prevent it completely. History is tracked manually
if( this.preventHashAssignPopState ) {
this.preventHashAssignPopState = false;
event.stopImmediatePropagation();
return;
}
// if this is the popstate triggered after the `replaceState` call in the go
// method, then simply ignore it. The history entry has already been captured
if( this.ignorePopState ) {
this.ignorePopState = false;
return;
}
// If there is no state, and the history stack length is one were
// probably getting the page load popstate fired by browsers like chrome
// avoid it and set the one time flag to false.
// TODO: Do we really need all these conditions? Comparing location hrefs
// should be sufficient.
if( !event.originalEvent.state &&
this.history.stack.length === 1 &&
this.ignoreInitialHashChange ) {
this.ignoreInitialHashChange = false;
if ( location.href === initialHref ) {
event.preventDefault();
return;
}
}
// account for direct manipulation of the hash. That is, we will receive a popstate
// when the hash is changed by assignment, and it won't have a state associated. We
// then need to squash the hash. See below for handling of hash assignment that
// matches an existing history entry
// TODO it might be better to only add to the history stack
// when the hash is adjacent to the active history entry
hash = path.parseLocation().hash;
if( !event.originalEvent.state && hash ) {
// squash the hash that's been assigned on the URL with replaceState
// also grab the resulting state object for storage
state = this.squash( hash );
// record the new hash as an additional history entry
// to match the browser's treatment of hash assignment
this.history.add( state.url, state );
// pass the newly created state information
// along with the event
event.historyState = state;
// do not alter history, we've added a new history entry
// so we know where we are
return;
}
// If all else fails this is a popstate that comes from the back or forward buttons
// make sure to set the state of our history stack properly, and record the directionality
this.history.direct({
url: (event.originalEvent.state || {}).url || hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.historyState = $.extend({}, historyEntry);
event.historyState.direction = direction;
}
});
},
// NOTE must bind before `navigate` special event hashchange binding otherwise the
// navigation data won't be attached to the hashchange event in time for those
// bindings to attach it to the `navigate` special event
// TODO add a check here that `hashchange.navigate` is bound already otherwise it's
// broken (exception?)
hashchange: function( event ) {
var history, hash;
// If hashchange listening is explicitly disabled or pushstate is supported
// avoid making use of the hashchange handler.
if(!$.event.special.navigate.isHashChangeEnabled() ||
$.event.special.navigate.isPushStateEnabled() ) {
return;
}
// On occasion explicitly want to prevent the next hash from propogating because we only
// with to alter the url to represent the new state do so here
if( this.preventNextHashChange ){
this.preventNextHashChange = false;
event.stopImmediatePropagation();
return;
}
history = this.history;
hash = path.parseLocation().hash;
// If this is a hashchange caused by the back or forward button
// make sure to set the state of our history stack properly
this.history.direct({
url: hash,
// When the url is either forward or backward in history include the entry
// as data on the event object for merging as data in the navigate event
present: function( historyEntry, direction ) {
// make sure to create a new object to pass down as the navigate event data
event.hashchangeState = $.extend({}, historyEntry);
event.hashchangeState.direction = direction;
},
// When we don't find a hash in our history clearly we're aiming to go there
// record the entry as new for future traversal
//
// NOTE it's not entirely clear that this is the right thing to do given that we
// can't know the users intention. It might be better to explicitly _not_
// support location.hash assignment in preference to $.navigate calls
// TODO first arg to add should be the href, but it causes issues in identifying
// embeded pages
missing: function() {
history.add( hash, {
hash: hash,
title: document.title
});
}
});
}
});
})( jQuery );
(function( $, undefined ) {
// TODO consider queueing navigation activity until previous activities have completed
// so that end users don't have to think about it. Punting for now
// TODO !! move the event bindings into callbacks on the navigate event
$.mobile.navigate = function( url, data, noEvents ) {
$.mobile.navigate.navigator.go( url, data, noEvents );
};
// expose the history on the navigate method in anticipation of full integration with
// existing navigation functionalty that is tightly coupled to the history information
$.mobile.navigate.history = new $.mobile.History();
// instantiate an instance of the navigator for use within the $.navigate method
$.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history );
var loc = $.mobile.path.parseLocation();
$.mobile.navigate.history.add( loc.href, {hash: loc.hash} );
})( jQuery );
// This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
//
// The idea here is to allow the developer to register listeners for the
// basic mouse events, such as mousedown, mousemove, mouseup, and click,
// and the plugin will take care of registering the correct listeners
// behind the scenes to invoke the listener at the fastest possible time
// for that device, while still retaining the order of event firing in
// the traditional mouse environment, should multiple handlers be registered
// on the same element for different events.
//
// The current version exposes the following virtual events to jQuery bind methods:
// "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel"
(function( $, window, document, undefined ) {
var dataPropertyName = "virtualMouseBindings",
touchTargetPropertyName = "virtualTouchID",
virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ),
touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ),
mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [],
mouseEventProps = $.event.props.concat( mouseHookProps ),
activeDocHandlers = {},
resetTimerID = 0,
startX = 0,
startY = 0,
didScroll = false,
clickBlockList = [],
blockMouseTriggers = false,
blockTouchTriggers = false,
eventCaptureSupported = "addEventListener" in document,
$document = $( document ),
nextTouchID = 1,
lastTouchID = 0, threshold;
$.vmouse = {
moveDistanceThreshold: 10,
clickDistanceThreshold: 10,
resetTimerDuration: 1500
};
function getNativeEvent( event ) {
while ( event && typeof event.originalEvent !== "undefined" ) {
event = event.originalEvent;
}
return event;
}
function createVirtualEvent( event, eventType ) {
var t = event.type,
oe, props, ne, prop, ct, touch, i, j, len;
event = $.Event( event );
event.type = eventType;
oe = event.originalEvent;
props = $.event.props;
// addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280
// https://github.com/jquery/jquery-mobile/issues/3280
if ( t.search( /^(mouse|click)/ ) > -1 ) {
props = mouseEventProps;
}
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if ( oe ) {
for ( i = props.length, prop; i; ) {
prop = props[ --i ];
event[ prop ] = oe[ prop ];
}
}
// make sure that if the mouse and click virtual events are generated
// without a .which one is defined
if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) {
event.which = 1;
}
if ( t.search(/^touch/) !== -1 ) {
ne = getNativeEvent( oe );
t = ne.touches;
ct = ne.changedTouches;
touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined );
if ( touch ) {
for ( j = 0, len = touchEventProps.length; j < len; j++) {
prop = touchEventProps[ j ];
event[ prop ] = touch[ prop ];
}
}
}
return event;
}
function getVirtualBindingFlags( element ) {
var flags = {},
b, k;
while ( element ) {
b = $.data( element, dataPropertyName );
for ( k in b ) {
if ( b[ k ] ) {
flags[ k ] = flags.hasVirtualBinding = true;
}
}
element = element.parentNode;
}
return flags;
}
function getClosestElementWithVirtualBinding( element, eventType ) {
var b;
while ( element ) {
b = $.data( element, dataPropertyName );
if ( b && ( !eventType || b[ eventType ] ) ) {
return element;
}
element = element.parentNode;
}
return null;
}
function enableTouchBindings() {
blockTouchTriggers = false;
}
function disableTouchBindings() {
blockTouchTriggers = true;
}
function enableMouseBindings() {
lastTouchID = 0;
clickBlockList.length = 0;
blockMouseTriggers = false;
// When mouse bindings are enabled, our
// touch bindings are disabled.
disableTouchBindings();
}
function disableMouseBindings() {
// When mouse bindings are disabled, our
// touch bindings are enabled.
enableTouchBindings();
}
function startResetTimer() {
clearResetTimer();
resetTimerID = setTimeout( function() {
resetTimerID = 0;
enableMouseBindings();
}, $.vmouse.resetTimerDuration );
}
function clearResetTimer() {
if ( resetTimerID ) {
clearTimeout( resetTimerID );
resetTimerID = 0;
}
}
function triggerVirtualEvent( eventType, event, flags ) {
var ve;
if ( ( flags && flags[ eventType ] ) ||
( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) {
ve = createVirtualEvent( event, eventType );
$( event.target).trigger( ve );
}
return ve;
}
function mouseEventCallback( event ) {
var touchID = $.data( event.target, touchTargetPropertyName );
if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) {
var ve = triggerVirtualEvent( "v" + event.type, event );
if ( ve ) {
if ( ve.isDefaultPrevented() ) {
event.preventDefault();
}
if ( ve.isPropagationStopped() ) {
event.stopPropagation();
}
if ( ve.isImmediatePropagationStopped() ) {
event.stopImmediatePropagation();
}
}
}
}
function handleTouchStart( event ) {
var touches = getNativeEvent( event ).touches,
target, flags;
if ( touches && touches.length === 1 ) {
target = event.target;
flags = getVirtualBindingFlags( target );
if ( flags.hasVirtualBinding ) {
lastTouchID = nextTouchID++;
$.data( target, touchTargetPropertyName, lastTouchID );
clearResetTimer();
disableMouseBindings();
didScroll = false;
var t = getNativeEvent( event ).touches[ 0 ];
startX = t.pageX;
startY = t.pageY;
triggerVirtualEvent( "vmouseover", event, flags );
triggerVirtualEvent( "vmousedown", event, flags );
}
}
}
function handleScroll( event ) {
if ( blockTouchTriggers ) {
return;
}
if ( !didScroll ) {
triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) );
}
didScroll = true;
startResetTimer();
}
function handleTouchMove( event ) {
if ( blockTouchTriggers ) {
return;
}
var t = getNativeEvent( event ).touches[ 0 ],
didCancel = didScroll,
moveThreshold = $.vmouse.moveDistanceThreshold,
flags = getVirtualBindingFlags( event.target );
didScroll = didScroll ||
( Math.abs( t.pageX - startX ) > moveThreshold ||
Math.abs( t.pageY - startY ) > moveThreshold );
if ( didScroll && !didCancel ) {
triggerVirtualEvent( "vmousecancel", event, flags );
}
triggerVirtualEvent( "vmousemove", event, flags );
startResetTimer();
}
function handleTouchEnd( event ) {
if ( blockTouchTriggers ) {
return;
}
disableTouchBindings();
var flags = getVirtualBindingFlags( event.target ),
t;
triggerVirtualEvent( "vmouseup", event, flags );
if ( !didScroll ) {
var ve = triggerVirtualEvent( "vclick", event, flags );
if ( ve && ve.isDefaultPrevented() ) {
// The target of the mouse events that follow the touchend
// event don't necessarily match the target used during the
// touch. This means we need to rely on coordinates for blocking
// any click that is generated.
t = getNativeEvent( event ).changedTouches[ 0 ];
clickBlockList.push({
touchID: lastTouchID,
x: t.clientX,
y: t.clientY
});
// Prevent any mouse events that follow from triggering
// virtual event notifications.
blockMouseTriggers = true;
}
}
triggerVirtualEvent( "vmouseout", event, flags);
didScroll = false;
startResetTimer();
}
function hasVirtualBindings( ele ) {
var bindings = $.data( ele, dataPropertyName ),
k;
if ( bindings ) {
for ( k in bindings ) {
if ( bindings[ k ] ) {
return true;
}
}
}
return false;
}
function dummyMouseHandler() {}
function getSpecialEventObject( eventType ) {
var realType = eventType.substr( 1 );
return {
setup: function( data, namespace ) {
// If this is the first virtual mouse binding for this element,
// add a bindings object to its data.
if ( !hasVirtualBindings( this ) ) {
$.data( this, dataPropertyName, {} );
}
// If setup is called, we know it is the first binding for this
// eventType, so initialize the count for the eventType to zero.
var bindings = $.data( this, dataPropertyName );
bindings[ eventType ] = true;
// If this is the first virtual mouse event for this type,
// register a global handler on the document.
activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1;
if ( activeDocHandlers[ eventType ] === 1 ) {
$document.bind( realType, mouseEventCallback );
}
// Some browsers, like Opera Mini, won't dispatch mouse/click events
// for elements unless they actually have handlers registered on them.
// To get around this, we register dummy handlers on the elements.
$( this ).bind( realType, dummyMouseHandler );
// For now, if event capture is not supported, we rely on mouse handlers.
if ( eventCaptureSupported ) {
// If this is the first virtual mouse binding for the document,
// register our touchstart handler on the document.
activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1;
if ( activeDocHandlers[ "touchstart" ] === 1 ) {
$document.bind( "touchstart", handleTouchStart )
.bind( "touchend", handleTouchEnd )
// On touch platforms, touching the screen and then dragging your finger
// causes the window content to scroll after some distance threshold is
// exceeded. On these platforms, a scroll prevents a click event from being
// dispatched, and on some platforms, even the touchend is suppressed. To
// mimic the suppression of the click event, we need to watch for a scroll
// event. Unfortunately, some platforms like iOS don't dispatch scroll
// events until *AFTER* the user lifts their finger (touchend). This means
// we need to watch both scroll and touchmove events to figure out whether
// or not a scroll happenens before the touchend event is fired.
.bind( "touchmove", handleTouchMove )
.bind( "scroll", handleScroll );
}
}
},
teardown: function( data, namespace ) {
// If this is the last virtual binding for this eventType,
// remove its global handler from the document.
--activeDocHandlers[ eventType ];
if ( !activeDocHandlers[ eventType ] ) {
$document.unbind( realType, mouseEventCallback );
}
if ( eventCaptureSupported ) {
// If this is the last virtual mouse binding in existence,
// remove our document touchstart listener.
--activeDocHandlers[ "touchstart" ];
if ( !activeDocHandlers[ "touchstart" ] ) {
$document.unbind( "touchstart", handleTouchStart )
.unbind( "touchmove", handleTouchMove )
.unbind( "touchend", handleTouchEnd )
.unbind( "scroll", handleScroll );
}
}
var $this = $( this ),
bindings = $.data( this, dataPropertyName );
// teardown may be called when an element was
// removed from the DOM. If this is the case,
// jQuery core may have already stripped the element
// of any data bindings so we need to check it before
// using it.
if ( bindings ) {
bindings[ eventType ] = false;
}
// Unregister the dummy event handler.
$this.unbind( realType, dummyMouseHandler );
// If this is the last virtual mouse binding on the
// element, remove the binding data from the element.
if ( !hasVirtualBindings( this ) ) {
$this.removeData( dataPropertyName );
}
}
};
}
// Expose our custom events to the jQuery bind/unbind mechanism.
for ( var i = 0; i < virtualEventNames.length; i++ ) {
$.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] );
}
// Add a capture click handler to block clicks.
// Note that we require event capture support for this so if the device
// doesn't support it, we punt for now and rely solely on mouse events.
if ( eventCaptureSupported ) {
document.addEventListener( "click", function( e ) {
var cnt = clickBlockList.length,
target = e.target,
x, y, ele, i, o, touchID;
if ( cnt ) {
x = e.clientX;
y = e.clientY;
threshold = $.vmouse.clickDistanceThreshold;
// The idea here is to run through the clickBlockList to see if
// the current click event is in the proximity of one of our
// vclick events that had preventDefault() called on it. If we find
// one, then we block the click.
//
// Why do we have to rely on proximity?
//
// Because the target of the touch event that triggered the vclick
// can be different from the target of the click event synthesized
// by the browser. The target of a mouse/click event that is syntehsized
// from a touch event seems to be implementation specific. For example,
// some browsers will fire mouse/click events for a link that is near
// a touch event, even though the target of the touchstart/touchend event
// says the user touched outside the link. Also, it seems that with most
// browsers, the target of the mouse/click event is not calculated until the
// time it is dispatched, so if you replace an element that you touched
// with another element, the target of the mouse/click will be the new
// element underneath that point.
//
// Aside from proximity, we also check to see if the target and any
// of its ancestors were the ones that blocked a click. This is necessary
// because of the strange mouse/click target calculation done in the
// Android 2.1 browser, where if you click on an element, and there is a
// mouse/click handler on one of its ancestors, the target will be the
// innermost child of the touched element, even if that child is no where
// near the point of touch.
ele = target;
while ( ele ) {
for ( i = 0; i < cnt; i++ ) {
o = clickBlockList[ i ];
touchID = 0;
if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) ||
$.data( ele, touchTargetPropertyName ) === o.touchID ) {
// XXX: We may want to consider removing matches from the block list
// instead of waiting for the reset timer to fire.
e.preventDefault();
e.stopPropagation();
return;
}
}
ele = ele.parentNode;
}
}
}, true);
}
})( jQuery, window, document );
(function( $, window, undefined ) {
var $document = $( document );
// add new event shortcuts
$.each( ( "touchstart touchmove touchend " +
"tap taphold " +
"swipe swipeleft swiperight " +
"scrollstart scrollstop" ).split( " " ), function( i, name ) {
$.fn[ name ] = function( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
// jQuery < 1.8
if ( $.attrFn ) {
$.attrFn[ name ] = true;
}
});
var supportTouch = $.mobile.support.touch,
scrollEvent = "touchmove scroll",
touchStartEvent = supportTouch ? "touchstart" : "mousedown",
touchStopEvent = supportTouch ? "touchend" : "mouseup",
touchMoveEvent = supportTouch ? "touchmove" : "mousemove";
function triggerCustomEvent( obj, eventType, event ) {
var originalType = event.type;
event.type = eventType;
$.event.dispatch.call( obj, event );
event.type = originalType;
}
// also handles scrollstop
$.event.special.scrollstart = {
enabled: true,
setup: function() {
var thisObject = this,
$this = $( thisObject ),
scrolling,
timer;
function trigger( event, state ) {
scrolling = state;
triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event );
}
// iPhone triggers scroll after a small delay; use touchmove instead
$this.bind( scrollEvent, function( event ) {
if ( !$.event.special.scrollstart.enabled ) {
return;
}
if ( !scrolling ) {
trigger( event, true );
}
clearTimeout( timer );
timer = setTimeout( function() {
trigger( event, false );
}, 50 );
});
}
};
// also handles taphold
$.event.special.tap = {
tapholdThreshold: 750,
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( "vmousedown", function( event ) {
if ( event.which && event.which !== 1 ) {
return false;
}
var origTarget = event.target,
origEvent = event.originalEvent,
timer;
function clearTapTimer() {
clearTimeout( timer );
}
function clearTapHandlers() {
clearTapTimer();
$this.unbind( "vclick", clickHandler )
.unbind( "vmouseup", clearTapTimer );
$document.unbind( "vmousecancel", clearTapHandlers );
}
function clickHandler( event ) {
clearTapHandlers();
// ONLY trigger a 'tap' event if the start target is
// the same as the stop target.
if ( origTarget === event.target ) {
triggerCustomEvent( thisObject, "tap", event );
}
}
$this.bind( "vmouseup", clearTapTimer )
.bind( "vclick", clickHandler );
$document.bind( "vmousecancel", clearTapHandlers );
timer = setTimeout( function() {
triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) );
}, $.event.special.tap.tapholdThreshold );
});
}
};
// also handles swipeleft, swiperight
$.event.special.swipe = {
scrollSupressionThreshold: 30, // More than this horizontal displacement, and we will suppress scrolling.
durationThreshold: 1000, // More time than this, and it isn't a swipe.
horizontalDistanceThreshold: 30, // Swipe horizontal displacement must be more than this.
verticalDistanceThreshold: 75, // Swipe vertical displacement must be less than this.
start: function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ],
origin: $( event.target )
};
},
stop: function( event ) {
var data = event.originalEvent.touches ?
event.originalEvent.touches[ 0 ] : event;
return {
time: ( new Date() ).getTime(),
coords: [ data.pageX, data.pageY ]
};
},
handleSwipe: function( start, stop ) {
if ( stop.time - start.time < $.event.special.swipe.durationThreshold &&
Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold &&
Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) {
start.origin.trigger( "swipe" )
.trigger( start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight" );
}
},
setup: function() {
var thisObject = this,
$this = $( thisObject );
$this.bind( touchStartEvent, function( event ) {
var start = $.event.special.swipe.start( event ),
stop;
function moveHandler( event ) {
if ( !start ) {
return;
}
stop = $.event.special.swipe.stop( event );
// prevent scrolling
if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) {
event.preventDefault();
}
}
$this.bind( touchMoveEvent, moveHandler )
.one( touchStopEvent, function() {
$this.unbind( touchMoveEvent, moveHandler );
if ( start && stop ) {
$.event.special.swipe.handleSwipe( start, stop );
}
start = stop = undefined;
});
});
}
};
$.each({
scrollstop: "scrollstart",
taphold: "tap",
swipeleft: "swipe",
swiperight: "swipe"
}, function( event, sourceEvent ) {
$.event.special[ event ] = {
setup: function() {
$( this ).bind( sourceEvent, $.noop );
}
};
});
})( jQuery, this );
// throttled resize event
(function( $ ) {
$.event.special.throttledresize = {
setup: function() {
$( this ).bind( "resize", handler );
},
teardown: function() {
$( this ).unbind( "resize", handler );
}
};
var throttle = 250,
handler = function() {
curr = ( new Date() ).getTime();
diff = curr - lastCall;
if ( diff >= throttle ) {
lastCall = curr;
$( this ).trigger( "throttledresize" );
} else {
if ( heldCall ) {
clearTimeout( heldCall );
}
// Promise a held call will still execute
heldCall = setTimeout( handler, throttle - diff );
}
},
lastCall = 0,
heldCall,
curr,
diff;
})( jQuery );
(function( $, window ) {
var win = $( window ),
event_name = "orientationchange",
special_event,
get_orientation,
last_orientation,
initial_orientation_is_landscape,
initial_orientation_is_default,
portrait_map = { "0": true, "180": true };
// It seems that some device/browser vendors use window.orientation values 0 and 180 to
// denote the "default" orientation. For iOS devices, and most other smart-phones tested,
// the default orientation is always "portrait", but in some Android and RIM based tablets,
// the default orientation is "landscape". The following code attempts to use the window
// dimensions to figure out what the current orientation is, and then makes adjustments
// to the to the portrait_map if necessary, so that we can properly decode the
// window.orientation value whenever get_orientation() is called.
//
// Note that we used to use a media query to figure out what the orientation the browser
// thinks it is in:
//
// initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)");
//
// but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1,
// where the browser *ALWAYS* applied the landscape media query. This bug does not
// happen on iPad.
if ( $.support.orientation ) {
// Check the window width and height to figure out what the current orientation
// of the device is at this moment. Note that we've initialized the portrait map
// values to 0 and 180, *AND* we purposely check for landscape so that if we guess
// wrong, , we default to the assumption that portrait is the default orientation.
// We use a threshold check below because on some platforms like iOS, the iPhone
// form-factor can report a larger width than height if the user turns on the
// developer console. The actual threshold value is somewhat arbitrary, we just
// need to make sure it is large enough to exclude the developer console case.
var ww = window.innerWidth || win.width(),
wh = window.innerHeight || win.height(),
landscape_threshold = 50;
initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold;
// Now check to see if the current window.orientation is 0 or 180.
initial_orientation_is_default = portrait_map[ window.orientation ];
// If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR*
// if the initial orientation is portrait, but window.orientation reports 90 or -90, we
// need to flip our portrait_map values because landscape is the default orientation for
// this device/browser.
if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) {
portrait_map = { "-90": true, "90": true };
}
}
$.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, {
setup: function() {
// If the event is supported natively, return false so that jQuery
// will bind to the event using DOM methods.
if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
return false;
}
// Get the current orientation to avoid initial double-triggering.
last_orientation = get_orientation();
// Because the orientationchange event doesn't exist, simulate the
// event by testing window dimensions on resize.
win.bind( "throttledresize", handler );
},
teardown: function() {
// If the event is not supported natively, return false so that
// jQuery will unbind the event using DOM methods.
if ( $.support.orientation && !$.event.special.orientationchange.disabled ) {
return false;
}
// Because the orientationchange event doesn't exist, unbind the
// resize event handler.
win.unbind( "throttledresize", handler );
},
add: function( handleObj ) {
// Save a reference to the bound event handler.
var old_handler = handleObj.handler;
handleObj.handler = function( event ) {
// Modify event object, adding the .orientation property.
event.orientation = get_orientation();
// Call the originally-bound event handler and return its result.
return old_handler.apply( this, arguments );
};
}
});
// If the event is not supported natively, this handler will be bound to
// the window resize event to simulate the orientationchange event.
function handler() {
// Get the current orientation.
var orientation = get_orientation();
if ( orientation !== last_orientation ) {
// The orientation has changed, so trigger the orientationchange event.
last_orientation = orientation;
win.trigger( event_name );
}
}
// Get the current page orientation. This method is exposed publicly, should it
// be needed, as jQuery.event.special.orientationchange.orientation()
$.event.special.orientationchange.orientation = get_orientation = function() {
var isPortrait = true, elem = document.documentElement;
// prefer window orientation to the calculation based on screensize as
// the actual screen resize takes place before or after the orientation change event
// has been fired depending on implementation (eg android 2.3 is before, iphone after).
// More testing is required to determine if a more reliable method of determining the new screensize
// is possible when orientationchange is fired. (eg, use media queries + element + opacity)
if ( $.support.orientation ) {
// if the window orientation registers as 0 or 180 degrees report
// portrait, otherwise landscape
isPortrait = portrait_map[ window.orientation ];
} else {
isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1;
}
return isPortrait ? "portrait" : "landscape";
};
$.fn[ event_name ] = function( fn ) {
return fn ? this.bind( event_name, fn ) : this.trigger( event_name );
};
// jQuery < 1.8
if ( $.attrFn ) {
$.attrFn[ event_name ] = true;
}
}( jQuery, this ));
(function( $, undefined ) {
$.widget( "mobile.page", $.mobile.widget, {
options: {
theme: "c",
domCache: false,
keepNativeDefault: ":jqmData(role='none'), :jqmData(role='nojs')"
},
_create: function() {
// if false is returned by the callbacks do not create the page
if ( this._trigger( "beforecreate" ) === false ) {
return false;
}
this.element
.attr( "tabindex", "0" )
.addClass( "ui-page ui-body-" + this.options.theme );
this._on( this.element, {
pagebeforehide: "removeContainerBackground",
pagebeforeshow: "_handlePageBeforeShow"
});
},
_handlePageBeforeShow: function( e ) {
this.setContainerBackground();
},
removeContainerBackground: function() {
$.mobile.pageContainer.removeClass( "ui-overlay-" + $.mobile.getInheritedTheme( this.element.parent() ) );
},
// set the page container background to the page theme
setContainerBackground: function( theme ) {
if ( this.options.theme ) {
$.mobile.pageContainer.addClass( "ui-overlay-" + ( theme || this.options.theme ) );
}
},
keepNativeSelector: function() {
var options = this.options,
keepNativeDefined = options.keepNative && $.trim( options.keepNative );
if ( keepNativeDefined && options.keepNative !== options.keepNativeDefault ) {
return [options.keepNative, options.keepNativeDefault].join( ", " );
}
return options.keepNativeDefault;
}
});
})( jQuery );
(function( $, window, undefined ) {
var createHandler = function( sequential ) {
// Default to sequential
if ( sequential === undefined ) {
sequential = true;
}
return function( name, reverse, $to, $from ) {
var deferred = new $.Deferred(),
reverseClass = reverse ? " reverse" : "",
active = $.mobile.urlHistory.getActive(),
toScroll = active.lastScroll || $.mobile.defaultHomeScroll,
screenHeight = $.mobile.getScreenHeight(),
maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth,
none = !$.support.cssTransitions || maxTransitionOverride || !name || name === "none" || Math.max( $.mobile.window.scrollTop(), toScroll ) > $.mobile.getMaxScrollForTransition(),
toPreClass = " ui-page-pre-in",
toggleViewportClass = function() {
$.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + name );
},
scrollPage = function() {
// By using scrollTo instead of silentScroll, we can keep things better in order
// Just to be precautios, disable scrollstart listening like silentScroll would
$.event.special.scrollstart.enabled = false;
window.scrollTo( 0, toScroll );
// reenable scrollstart listening like silentScroll would
setTimeout( function() {
$.event.special.scrollstart.enabled = true;
}, 150 );
},
cleanFrom = function() {
$from
.removeClass( $.mobile.activePageClass + " out in reverse " + name )
.height( "" );
},
startOut = function() {
// if it's not sequential, call the doneOut transition to start the TO page animating in simultaneously
if ( !sequential ) {
doneOut();
}
else {
$from.animationComplete( doneOut );
}
// Set the from page's height and start it transitioning out
// Note: setting an explicit height helps eliminate tiling in the transitions
$from
.height( screenHeight + $.mobile.window.scrollTop() )
.addClass( name + " out" + reverseClass );
},
doneOut = function() {
if ( $from && sequential ) {
cleanFrom();
}
startIn();
},
startIn = function() {
// Prevent flickering in phonegap container: see comments at #4024 regarding iOS
$to.css( "z-index", -10 );
$to.addClass( $.mobile.activePageClass + toPreClass );
// Send focus to page as it is now display: block
$.mobile.focusPage( $to );
// Set to page height
$to.height( screenHeight + toScroll );
scrollPage();
// Restores visibility of the new page: added together with $to.css( "z-index", -10 );
$to.css( "z-index", "" );
if ( !none ) {
$to.animationComplete( doneIn );
}
$to
.removeClass( toPreClass )
.addClass( name + " in" + reverseClass );
if ( none ) {
doneIn();
}
},
doneIn = function() {
if ( !sequential ) {
if ( $from ) {
cleanFrom();
}
}
$to
.removeClass( "out in reverse " + name )
.height( "" );
toggleViewportClass();
// In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition
// This ensures we jump to that spot after the fact, if we aren't there already.
if ( $.mobile.window.scrollTop() !== toScroll ) {
scrollPage();
}
deferred.resolve( name, reverse, $to, $from, true );
};
toggleViewportClass();
if ( $from && !none ) {
startOut();
}
else {
doneOut();
}
return deferred.promise();
};
};
// generate the handlers from the above
var sequentialHandler = createHandler(),
simultaneousHandler = createHandler( false ),
defaultGetMaxScrollForTransition = function() {
return $.mobile.getScreenHeight() * 3;
};
// Make our transition handler the public default.
$.mobile.defaultTransitionHandler = sequentialHandler;
//transition handler dictionary for 3rd party transitions
$.mobile.transitionHandlers = {
"default": $.mobile.defaultTransitionHandler,
"sequential": sequentialHandler,
"simultaneous": simultaneousHandler
};
$.mobile.transitionFallbacks = {};
// If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified
$.mobile._maybeDegradeTransition = function( transition ) {
if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) {
transition = $.mobile.transitionFallbacks[ transition ];
}
return transition;
};
// Set the getMaxScrollForTransition to default if no implementation was set by user
$.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition;
})( jQuery, this );
(function( $, undefined ) {
//define vars for interal use
var $window = $.mobile.window,
$html = $( 'html' ),
$head = $( 'head' ),
// NOTE: path extensions dependent on core attributes. Moved here to remove deps from
// $.mobile.path definition
path = $.extend($.mobile.path, {
//return the substring of a filepath before the sub-page key, for making a server request
getFilePath: function( path ) {
var splitkey = '&' + $.mobile.subPageUrlKey;
return path && path.split( splitkey )[0].split( dialogHashKey )[0];
},
//check if the specified url refers to the first page in the main application document.
isFirstPageUrl: function( url ) {
// We only deal with absolute paths.
var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ),
// Does the url have the same path as the document?
samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ),
// Get the first page element.
fp = $.mobile.firstPage,
// Get the id of the first page element if it has one.
fpId = fp && fp[0] ? fp[0].id : undefined;
// The url refers to the first page if the path matches the document and
// it either has no hash value, or the hash is exactly equal to the id of the
// first page element.
return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) );
},
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
isPermittedCrossDomainRequest: function( docUrl, reqUrl ) {
return $.mobile.allowCrossDomainPages &&
docUrl.protocol === "file:" &&
reqUrl.search( /^https?:/ ) !== -1;
}
}),
// used to track last vclicked element to make sure its value is added to form data
$lastVClicked = null,
//will be defined when a link is clicked and given an active class
$activeClickedLink = null,
// resolved on domready
domreadyDeferred = $.Deferred(),
//urlHistory is purely here to make guesses at whether the back or forward button was clicked
//and provide an appropriate transition
urlHistory = $.mobile.navigate.history,
//define first selector to receive focus when a page is shown
focusable = "[tabindex],a,button:visible,select:visible,input",
//queue to hold simultanious page transitions
pageTransitionQueue = [],
//indicates whether or not page is in process of transitioning
isPageTransitioning = false,
//nonsense hash change key for dialogs, so they create a history entry
dialogHashKey = "&ui-state=dialog",
//existing base tag?
$base = $head.children( "base" ),
//tuck away the original document URL minus any fragment.
documentUrl = path.documentUrl,
//if the document has an embedded base tag, documentBase is set to its
//initial value. If a base tag does not exist, then we default to the documentUrl.
documentBase = path.documentBase,
//cache the comparison once.
documentBaseDiffers = path.documentBaseDiffers,
getScreenHeight = $.mobile.getScreenHeight;
//base element management, defined depending on dynamic base tag support
var base = $.support.dynamicBaseTag ? {
//define base element, for use in routing asset urls that are referenced in Ajax-requested markup
element: ( $base.length ? $base : $( "<base>", { href: documentBase.hrefNoHash } ).prependTo( $head ) ),
//set the generated BASE element's href attribute to a new page's base path
set: function( href ) {
href = path.parseUrl(href).hrefNoHash;
base.element.attr( "href", path.makeUrlAbsolute( href, documentBase ) );
},
//set the generated BASE element's href attribute to a new page's base path
reset: function() {
base.element.attr( "href", documentBase.hrefNoSearch );
}
} : undefined;
//return the original document url
$.mobile.getDocumentUrl = path.getDocumentUrl;
//return the original document base url
$.mobile.getDocumentBase = path.getDocumentBase;
/* internal utility functions */
// NOTE Issue #4950 Android phonegap doesn't navigate back properly
// when a full page refresh has taken place. It appears that hashchange
// and replacestate history alterations work fine but we need to support
// both forms of history traversal in our code that uses backward history
// movement
$.mobile.back = function() {
var nav = window.navigator;
// if the setting is on and the navigator object is
// available use the phonegap navigation capability
if( this.phonegapNavigationEnabled &&
nav &&
nav.app &&
nav.app.backHistory ){
nav.app.backHistory();
} else {
window.history.back();
}
};
//direct focus to the page title, or otherwise first focusable element
$.mobile.focusPage = function ( page ) {
var autofocus = page.find( "[autofocus]" ),
pageTitle = page.find( ".ui-title:eq(0)" );
if ( autofocus.length ) {
autofocus.focus();
return;
}
if ( pageTitle.length ) {
pageTitle.focus();
} else{
page.focus();
}
};
//remove active classes after page transition or error
function removeActiveLinkClass( forceRemoval ) {
if ( !!$activeClickedLink && ( !$activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) {
$activeClickedLink.removeClass( $.mobile.activeBtnClass );
}
$activeClickedLink = null;
}
function releasePageTransitionLock() {
isPageTransitioning = false;
if ( pageTransitionQueue.length > 0 ) {
$.mobile.changePage.apply( null, pageTransitionQueue.pop() );
}
}
// Save the last scroll distance per page, before it is hidden
var setLastScrollEnabled = true,
setLastScroll, delayedSetLastScroll;
setLastScroll = function() {
// this barrier prevents setting the scroll value based on the browser
// scrolling the window based on a hashchange
if ( !setLastScrollEnabled ) {
return;
}
var active = $.mobile.urlHistory.getActive();
if ( active ) {
var lastScroll = $window.scrollTop();
// Set active page's lastScroll prop.
// If the location we're scrolling to is less than minScrollBack, let it go.
active.lastScroll = lastScroll < $.mobile.minScrollBack ? $.mobile.defaultHomeScroll : lastScroll;
}
};
// bind to scrollstop to gather scroll position. The delay allows for the hashchange
// event to fire and disable scroll recording in the case where the browser scrolls
// to the hash targets location (sometimes the top of the page). once pagechange fires
// getLastScroll is again permitted to operate
delayedSetLastScroll = function() {
setTimeout( setLastScroll, 100 );
};
// disable an scroll setting when a hashchange has been fired, this only works
// because the recording of the scroll position is delayed for 100ms after
// the browser might have changed the position because of the hashchange
$window.bind( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = false;
});
// handle initial hashchange from chrome :(
$window.one( $.support.pushState ? "popstate" : "hashchange", function() {
setLastScrollEnabled = true;
});
// wait until the mobile page container has been determined to bind to pagechange
$window.one( "pagecontainercreate", function() {
// once the page has changed, re-enable the scroll recording
$.mobile.pageContainer.bind( "pagechange", function() {
setLastScrollEnabled = true;
// remove any binding that previously existed on the get scroll
// which may or may not be different than the scroll element determined for
// this page previously
$window.unbind( "scrollstop", delayedSetLastScroll );
// determine and bind to the current scoll element which may be the window
// or in the case of touch overflow the element with touch overflow
$window.bind( "scrollstop", delayedSetLastScroll );
});
});
// bind to scrollstop for the first page as "pagechange" won't be fired in that case
$window.bind( "scrollstop", delayedSetLastScroll );
// No-op implementation of transition degradation
$.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) {
return transition;
};
//function for transitioning between two existing pages
function transitionPages( toPage, fromPage, transition, reverse ) {
if ( fromPage ) {
//trigger before show/hide events
fromPage.data( "mobile-page" )._trigger( "beforehide", null, { nextPage: toPage } );
}
toPage.data( "mobile-page" )._trigger( "beforeshow", null, { prevPage: fromPage || $( "" ) } );
//clear page loader
$.mobile.hidePageLoadingMsg();
transition = $.mobile._maybeDegradeTransition( transition );
//find the transition handler for the specified transition. If there
//isn't one in our transitionHandlers dictionary, use the default one.
//call the handler immediately to kick-off the transition.
var th = $.mobile.transitionHandlers[ transition || "default" ] || $.mobile.defaultTransitionHandler,
promise = th( transition, reverse, toPage, fromPage );
promise.done(function() {
//trigger show/hide events
if ( fromPage ) {
fromPage.data( "mobile-page" )._trigger( "hide", null, { nextPage: toPage } );
}
//trigger pageshow, define prevPage as either fromPage or empty jQuery obj
toPage.data( "mobile-page" )._trigger( "show", null, { prevPage: fromPage || $( "" ) } );
});
return promise;
}
//simply set the active page's minimum height to screen height, depending on orientation
$.mobile.resetActivePageHeight = function resetActivePageHeight( height ) {
var aPage = $( "." + $.mobile.activePageClass ),
aPagePadT = parseFloat( aPage.css( "padding-top" ) ),
aPagePadB = parseFloat( aPage.css( "padding-bottom" ) ),
aPageBorderT = parseFloat( aPage.css( "border-top-width" ) ),
aPageBorderB = parseFloat( aPage.css( "border-bottom-width" ) );
height = ( typeof height === "number" )? height : getScreenHeight();
aPage.css( "min-height", height - aPagePadT - aPagePadB - aPageBorderT - aPageBorderB );
};
//shared page enhancements
function enhancePage( $page, role ) {
// If a role was specified, make sure the data-role attribute
// on the page element is in sync.
if ( role ) {
$page.attr( "data-" + $.mobile.ns + "role", role );
}
//run page plugin
$page.page();
}
// determine the current base url
function findBaseWithDefault() {
var closestBase = ( $.mobile.activePage && getClosestBaseUrl( $.mobile.activePage ) );
return closestBase || documentBase.hrefNoHash;
}
/* exposed $.mobile methods */
//animation complete callback
$.fn.animationComplete = function( callback ) {
if ( $.support.cssTransitions ) {
return $( this ).one( 'webkitAnimationEnd animationend', callback );
}
else{
// defer execution for consistency between webkit/non webkit
setTimeout( callback, 0 );
return $( this );
}
};
//expose path object on $.mobile
$.mobile.path = path;
//expose base object on $.mobile
$.mobile.base = base;
//history stack
$.mobile.urlHistory = urlHistory;
$.mobile.dialogHashKey = dialogHashKey;
//enable cross-domain page support
$.mobile.allowCrossDomainPages = false;
$.mobile._bindPageRemove = function() {
var page = $( this );
// when dom caching is not enabled or the page is embedded bind to remove the page on hide
if ( !page.data( "mobile-page" ).options.domCache &&
page.is( ":jqmData(external-page='true')" ) ) {
page.bind( 'pagehide.remove', function( e ) {
var $this = $( this ),
prEvent = new $.Event( "pageremove" );
$this.trigger( prEvent );
if ( !prEvent.isDefaultPrevented() ) {
$this.removeWithDependents();
}
});
}
};
// Load a page into the DOM.
$.mobile.loadPage = function( url, options ) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend( {}, $.mobile.loadPage.defaults, options ),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute( url, findBaseWithDefault() );
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if ( settings.data && settings.type === "get" ) {
absUrl = path.addSearchParams( absUrl, settings.data );
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if ( settings.data && settings.type === "post" ) {
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath( absUrl ),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl( absUrl );
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
// NOTE do _not_ use the :jqmData psuedo selector because parenthesis
// are a valid url char and it breaks on the first occurence
page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if ( page.length === 0 && dataUrl && !path.isPath( dataUrl ) ) {
page = settings.pageContainer.children( "#" + dataUrl )
.attr( "data-" + $.mobile.ns + "url", dataUrl )
.jqmData( "url", dataUrl );
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if ( page.length === 0 ) {
if ( $.mobile.firstPage && path.isFirstPageUrl( fileUrl ) ) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ( $.mobile.firstPage.parent().length ) {
page = $( $.mobile.firstPage );
}
} else if ( path.isEmbeddedPage( fileUrl ) ) {
deferred.reject( absUrl, options );
return deferred.promise();
}
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if ( page.length ) {
if ( !settings.reloadPage ) {
enhancePage( page, settings.role );
deferred.resolve( absUrl, options, page );
//if we are reloading the page make sure we update the base if its not a prefetch
if( base && !options.prefetch ){
base.set(url);
}
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event( "pagebeforeload" ),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger( pblEvent, triggerData );
// If the default behavior is prevented, stop here!
if ( pblEvent.isDefaultPrevented() ) {
return deferred.promise();
}
if ( settings.showLoadMsg ) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function() {
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay ),
// Shared logic for clearing timeout and removing message.
hideMsg = function() {
// Stop message show timer
clearTimeout( loadMsgDelay );
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
// Reset base to the default document base.
// only reset if we are not prefetching
if ( base && typeof options.prefetch === "undefined" ) {
base.reset();
}
if ( !( $.mobile.allowCrossDomainPages || path.isSameDomain( documentUrl, absUrl ) ) ) {
deferred.reject( absUrl, options );
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
contentType: settings.contentType,
dataType: "html",
success: function( html, textStatus, xhr ) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $( "<div></div>" ),
//page title regexp
newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)" ),
dataUrlRegex = new RegExp( "\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?" );
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if ( pageElemRegex.test( html ) &&
RegExp.$1 &&
dataUrlRegex.test( RegExp.$1 ) &&
RegExp.$1 ) {
url = fileUrl = path.getFilePath( $( "<div>" + RegExp.$1 + "</div>" ).text() );
}
//dont update the base tag if we are prefetching
if ( base && typeof options.prefetch === "undefined") {
base.set( fileUrl );
}
//workaround to allow scripts to execute when included in page divs
all.get( 0 ).innerHTML = html;
page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first();
//if page elem couldn't be found, create one and insert the body element's contents
if ( !page.length ) {
page = $( "<div data-" + $.mobile.ns + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" );
}
if ( newPageTitle && !page.jqmData( "title" ) ) {
if ( ~newPageTitle.indexOf( "&" ) ) {
newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text();
}
page.jqmData( "title", newPageTitle );
}
//rewrite src and href attrs to use a base url
if ( !$.support.dynamicBaseTag ) {
var newPath = path.get( fileUrl );
page.find( "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]" ).each(function() {
var thisAttr = $( this ).is( '[href]' ) ? 'href' :
$( this ).is( '[src]' ) ? 'src' : 'action',
thisUrl = $( this ).attr( thisAttr );
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace( location.protocol + '//' + location.host + location.pathname, '' );
if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) {
$( this ).attr( thisAttr, newPath + thisUrl );
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr( "data-" + $.mobile.ns + "url", path.convertUrlToDataUrl( fileUrl ) )
.attr( "data-" + $.mobile.ns + "external-page", true )
.appendTo( settings.pageContainer );
// wait for page creation to leverage options defined on widget
page.one( 'pagecreate', $.mobile._bindPageRemove );
enhancePage( page, settings.role );
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) {
page = settings.pageContainer.children( "[data-" + $.mobile.ns +"url='" + dataUrl + "']" );
}
// Remove loading message.
if ( settings.showLoadMsg ) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger( "pageload", triggerData );
deferred.resolve( absUrl, options, page, dupCachedPage );
},
error: function( xhr, textStatus, errorThrown ) {
//set base back to current path
if ( base ) {
base.set( path.get() );
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event( "pageloadfailed" );
// Let listeners know the page load failed.
settings.pageContainer.trigger( plfEvent, triggerData );
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if ( plfEvent.isDefaultPrevented() ) {
return;
}
// Remove loading message.
if ( settings.showLoadMsg ) {
// Remove loading message.
hideMsg();
// show error message
$.mobile.showPageLoadingMsg( $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true );
// hide after delay
setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
}
deferred.reject( absUrl, options );
}
});
}
return deferred.promise();
};
$.mobile.loadPage.defaults = {
type: "get",
data: undefined,
reloadPage: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
showLoadMsg: false,
pageContainer: undefined,
loadMsgDelay: 50 // This delay allows loads that pull from browser cache to occur without showing the loading message.
};
// Show a specific page in the page container.
$.mobile.changePage = function( toPage, options ) {
// If we are in the midst of a transition, queue the current request.
// We'll call changePage() once we're done with the current transition to
// service the request.
if ( isPageTransitioning ) {
pageTransitionQueue.unshift( arguments );
return;
}
var settings = $.extend( {}, $.mobile.changePage.defaults, options ), isToPageString;
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Make sure we have a fromPage.
settings.fromPage = settings.fromPage || $.mobile.activePage;
isToPageString = (typeof toPage === "string");
var mpc = settings.pageContainer,
pbcEvent = new $.Event( "pagebeforechange" ),
triggerData = { toPage: toPage, options: settings };
// NOTE: preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
if ( isToPageString ) {
// if the toPage is a string simply convert it
triggerData.absUrl = path.makeUrlAbsolute( toPage, findBaseWithDefault() );
} else {
// if the toPage is a jQuery object grab the absolute url stored
// in the loadPage callback where it exists
triggerData.absUrl = toPage.data( 'absUrl' );
}
// Let listeners know we're about to change the current page.
mpc.trigger( pbcEvent, triggerData );
// If the default behavior is prevented, stop here!
if ( pbcEvent.isDefaultPrevented() ) {
return;
}
// We allow "pagebeforechange" observers to modify the toPage in the trigger
// data to allow for redirects. Make sure our toPage is updated.
//
// We also need to re-evaluate whether it is a string, because an object can
// also be replaced by a string
toPage = triggerData.toPage;
isToPageString = (typeof toPage === "string");
// Set the isPageTransitioning flag to prevent any requests from
// entering this method while we are in the midst of loading a page
// or transitioning.
isPageTransitioning = true;
// If the caller passed us a url, call loadPage()
// to make sure it is loaded into the DOM. We'll listen
// to the promise object it returns so we know when
// it is done loading or if an error ocurred.
if ( isToPageString ) {
// preserve the original target as the dataUrl value will be simplified
// eg, removing ui-state, and removing query params from the hash
// this is so that users who want to use query params have access to them
// in the event bindings for the page life cycle See issue #5085
settings.target = toPage;
$.mobile.loadPage( toPage, settings )
.done(function( url, options, newPage, dupCachedPage ) {
isPageTransitioning = false;
options.duplicateCachedPage = dupCachedPage;
// store the original absolute url so that it can be provided
// to events in the triggerData of the subsequent changePage call
newPage.data( 'absUrl', triggerData.absUrl );
$.mobile.changePage( newPage, options );
})
.fail(function( url, options ) {
//clear out the active button state
removeActiveLinkClass( true );
//release transition lock so navigation is free again
releasePageTransitionLock();
settings.pageContainer.trigger( "pagechangefailed", triggerData );
});
return;
}
// If we are going to the first-page of the application, we need to make
// sure settings.dataUrl is set to the application document url. This allows
// us to avoid generating a document url with an id hash in the case where the
// first-page of the document has an id attribute specified.
if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
settings.dataUrl = documentUrl.hrefNoHash;
}
// The caller passed us a real page DOM element. Update our
// internal state and then trigger a transition to the page.
var fromPage = settings.fromPage,
url = ( settings.dataUrl && path.convertUrlToDataUrl( settings.dataUrl ) ) || toPage.jqmData( "url" ),
// The pageUrl var is usually the same as url, except when url is obscured as a dialog url. pageUrl always contains the file path
pageUrl = url,
fileUrl = path.getFilePath( url ),
active = urlHistory.getActive(),
activeIsInitialPage = urlHistory.activeIndex === 0,
historyDir = 0,
pageTitle = document.title,
isDialog = settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog";
// By default, we prevent changePage requests when the fromPage and toPage
// are the same element, but folks that generate content manually/dynamically
// and reuse pages want to be able to transition to the same page. To allow
// this, they will need to change the default value of allowSamePageTransition
// to true, *OR*, pass it in as an option when they manually call changePage().
// It should be noted that our default transition animations assume that the
// formPage and toPage are different elements, so they may behave unexpectedly.
// It is up to the developer that turns on the allowSamePageTransitiona option
// to either turn off transition animations, or make sure that an appropriate
// animation transition is used.
if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) {
isPageTransitioning = false;
mpc.trigger( "pagechange", triggerData );
// Even if there is no page change to be done, we should keep the urlHistory in sync with the hash changes
if ( settings.fromHashChange ) {
urlHistory.direct({ url: url });
}
return;
}
// We need to make sure the page we are given has already been enhanced.
enhancePage( toPage, settings.role );
// If the changePage request was sent from a hashChange event, check to see if the
// page is already within the urlHistory stack. If so, we'll assume the user hit
// the forward/back button and will try to match the transition accordingly.
if ( settings.fromHashChange ) {
historyDir = options.direction === "back" ? -1 : 1;
}
// Kill the keyboard.
// XXX_jblas: We need to stop crawling the entire document to kill focus. Instead,
// we should be tracking focus with a delegate() handler so we already have
// the element in hand at this point.
// Wrap this in a try/catch block since IE9 throw "Unspecified error" if document.activeElement
// is undefined when we are in an IFrame.
try {
if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== 'body' ) {
$( document.activeElement ).blur();
} else {
$( "input:focus, textarea:focus, select:focus" ).blur();
}
} catch( e ) {}
// Record whether we are at a place in history where a dialog used to be - if so, do not add a new history entry and do not change the hash either
var alreadyThere = false;
// If we're displaying the page as a dialog, we don't want the url
// for the dialog content to be used in the hash. Instead, we want
// to append the dialogHashKey to the url of the current page.
if ( isDialog && active ) {
// on the initial page load active.url is undefined and in that case should
// be an empty string. Moving the undefined -> empty string back into
// urlHistory.addNew seemed imprudent given undefined better represents
// the url state
// If we are at a place in history that once belonged to a dialog, reuse
// this state without adding to urlHistory and without modifying the hash.
// However, if a dialog is already displayed at this point, and we're
// about to display another dialog, then we must add another hash and
// history entry on top so that one may navigate back to the original dialog
if ( active.url &&
active.url.indexOf( dialogHashKey ) > -1 &&
$.mobile.activePage &&
!$.mobile.activePage.is( ".ui-dialog" ) &&
urlHistory.activeIndex > 0 ) {
settings.changeHash = false;
alreadyThere = true;
}
// Normally, we tack on a dialog hash key, but if this is the location of a stale dialog,
// we reuse the URL from the entry
url = ( active.url || "" );
// account for absolute urls instead of just relative urls use as hashes
if( !alreadyThere && url.indexOf("#") > -1 ) {
url += dialogHashKey;
} else {
url += "#" + dialogHashKey;
}
// tack on another dialogHashKey if this is the same as the initial hash
// this makes sure that a history entry is created for this dialog
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += dialogHashKey;
}
}
// if title element wasn't found, try the page div data attr too
// If this is a deep-link or a reload ( active === undefined ) then just use pageTitle
var newPageTitle = ( !active )? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text();
if ( !!newPageTitle && pageTitle === document.title ) {
pageTitle = newPageTitle;
}
if ( !toPage.jqmData( "title" ) ) {
toPage.jqmData( "title", pageTitle );
}
// Make sure we have a transition defined.
settings.transition = settings.transition ||
( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) ||
( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition );
//add page to history stack if it's not back or forward
if ( !historyDir && alreadyThere ) {
urlHistory.getActive().pageUrl = pageUrl;
}
// Set the location hash.
if ( url && !settings.fromHashChange ) {
var params;
// rebuilding the hash here since we loose it earlier on
// TODO preserve the originally passed in path
if( !path.isPath( url ) && url.indexOf( "#" ) < 0 ) {
url = "#" + url;
}
// TODO the property names here are just silly
params = {
transition: settings.transition,
title: pageTitle,
pageUrl: pageUrl,
role: settings.role
};
if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) {
$.mobile.navigate( url, params, true);
} else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) {
$.mobile.navigate.history.add( url, params );
}
}
//set page title
document.title = pageTitle;
//set "toPage" as activePage
$.mobile.activePage = toPage;
// If we're navigating back in the URL history, set reverse accordingly.
settings.reverse = settings.reverse || historyDir < 0;
transitionPages( toPage, fromPage, settings.transition, settings.reverse )
.done(function( name, reverse, $to, $from, alreadyFocused ) {
removeActiveLinkClass();
//if there's a duplicateCachedPage, remove it from the DOM now that it's hidden
if ( settings.duplicateCachedPage ) {
settings.duplicateCachedPage.remove();
}
// Send focus to the newly shown page. Moved from promise .done binding in transitionPages
// itself to avoid ie bug that reports offsetWidth as > 0 (core check for visibility)
// despite visibility: hidden addresses issue #2965
// https://github.com/jquery/jquery-mobile/issues/2965
if ( !alreadyFocused ) {
$.mobile.focusPage( toPage );
}
releasePageTransitionLock();
mpc.trigger( "pagechange", triggerData );
});
};
$.mobile.changePage.defaults = {
transition: undefined,
reverse: false,
changeHash: true,
fromHashChange: false,
role: undefined, // By default we rely on the role defined by the @data-role attribute.
duplicateCachedPage: undefined,
pageContainer: undefined,
showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage
dataUrl: undefined,
fromPage: undefined,
allowSamePageTransition: false
};
/* Event Bindings - hashchange, submit, and click */
function findClosestLink( ele )
{
while ( ele ) {
// Look for the closest element with a nodeName of "a".
// Note that we are checking if we have a valid nodeName
// before attempting to access it. This is because the
// node we get called with could have originated from within
// an embedded SVG document where some symbol instance elements
// don't have nodeName defined on them, or strings are of type
// SVGAnimatedString.
if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) {
break;
}
ele = ele.parentNode;
}
return ele;
}
// The base URL for any given element depends on the page it resides in.
function getClosestBaseUrl( ele )
{
// Find the closest page and extract out its url.
var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ),
base = documentBase.hrefNoHash;
if ( !url || !path.isPath( url ) ) {
url = base;
}
return path.makeUrlAbsolute( url, base);
}
//The following event bindings should be bound after mobileinit has been triggered
//the following deferred is resolved in the init file
$.mobile.navreadyDeferred = $.Deferred();
$.mobile._registerInternalEvents = function() {
var getAjaxFormData = function( $form, calculateOnly ) {
var url, ret = true, formData, vclickedName, method;
if ( !$.mobile.ajaxEnabled ||
// test that the form is, itself, ajax false
$form.is( ":jqmData(ajax='false')" ) ||
// test that $.mobile.ignoreContentEnabled is set and
// the form or one of it's parents is ajax=false
!$form.jqmHijackable().length ||
$form.attr( "target" ) ) {
return false;
}
url = $form.attr( "action" );
method = ( $form.attr( "method" ) || "get" ).toLowerCase();
// If no action is specified, browsers default to using the
// URL of the document containing the form. Since we dynamically
// pull in pages from external documents, the form should submit
// to the URL for the source document of the page containing
// the form.
if ( !url ) {
// Get the @data-url for the page containing the form.
url = getClosestBaseUrl( $form );
// NOTE: If the method is "get", we need to strip off the query string
// because it will get replaced with the new form data. See issue #5710.
if ( method === "get" ) {
url = path.parseUrl( url ).hrefNoSearch;
}
if ( url === documentBase.hrefNoHash ) {
// The url we got back matches the document base,
// which means the page must be an internal/embedded page,
// so default to using the actual document url as a browser
// would.
url = documentUrl.hrefNoSearch;
}
}
url = path.makeUrlAbsolute( url, getClosestBaseUrl( $form ) );
if ( ( path.isExternal( url ) && !path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) {
return false;
}
if ( !calculateOnly ) {
formData = $form.serializeArray();
if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) {
vclickedName = $lastVClicked.attr( "name" );
if ( vclickedName ) {
// Make sure the last clicked element is included in the form
$.each( formData, function( key, value ) {
if ( value.name === vclickedName ) {
// Unset vclickedName - we've found it in the serialized data already
vclickedName = "";
return false;
}
});
if ( vclickedName ) {
formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } );
}
}
}
ret = {
url: url,
options: {
type: method,
data: $.param( formData ),
transition: $form.jqmData( "transition" ),
reverse: $form.jqmData( "direction" ) === "reverse",
reloadPage: true
}
};
}
return ret;
};
//bind to form submit events, handle with Ajax
$.mobile.document.delegate( "form", "submit", function( event ) {
var formData = getAjaxFormData( $( this ) );
if ( formData ) {
$.mobile.changePage( formData.url, formData.options );
event.preventDefault();
}
});
//add active state on vclick
$.mobile.document.bind( "vclick", function( event ) {
var $btn, btnEls, target = event.target, needClosest = false;
// if this isn't a left click we don't care. Its important to note
// that when the virtual event is generated it will create the which attr
if ( event.which > 1 || !$.mobile.linkBindingEnabled ) {
return;
}
// Record that this element was clicked, in case we need it for correct
// form submission during the "submit" handler above
$lastVClicked = $( target );
// Try to find a target element to which the active class will be applied
if ( $.data( target, "mobile-button" ) ) {
// If the form will not be submitted via AJAX, do not add active class
if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) {
return;
}
// We will apply the active state to this button widget - the parent
// of the input that was clicked will have the associated data
if ( target.parentNode ) {
target = target.parentNode;
}
} else {
target = findClosestLink( target );
if ( !( target && path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) {
return;
}
// TODO teach $.mobile.hijackable to operate on raw dom elements so the
// link wrapping can be avoided
if ( !$( target ).jqmHijackable().length ) {
return;
}
}
// Avoid calling .closest by using the data set during .buttonMarkup()
// List items have the button data in the parent of the element clicked
if ( !!~target.className.indexOf( "ui-link-inherit" ) ) {
if ( target.parentNode ) {
btnEls = $.data( target.parentNode, "buttonElements" );
}
// Otherwise, look for the data on the target itself
} else {
btnEls = $.data( target, "buttonElements" );
}
// If found, grab the button's outer element
if ( btnEls ) {
target = btnEls.outer;
} else {
needClosest = true;
}
$btn = $( target );
// If the outer element wasn't found by the our heuristics, use .closest()
if ( needClosest ) {
$btn = $btn.closest( ".ui-btn" );
}
if ( $btn.length > 0 && !$btn.hasClass( "ui-disabled" ) ) {
removeActiveLinkClass( true );
$activeClickedLink = $btn;
$activeClickedLink.addClass( $.mobile.activeBtnClass );
}
});
// click routing - direct to HTTP or Ajax, accordingly
$.mobile.document.bind( "click", function( event ) {
if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) {
return;
}
var link = findClosestLink( event.target ), $link = $( link ), httpCleanup;
// If there is no link associated with the click or its not a left
// click we want to ignore the click
// TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping
// can be avoided
if ( !link || event.which > 1 || !$link.jqmHijackable().length ) {
return;
}
//remove active link class if external (then it won't be there if you come back)
httpCleanup = function() {
window.setTimeout(function() { removeActiveLinkClass( true ); }, 200 );
};
//if there's a data-rel=back attr, go back in history
if ( $link.is( ":jqmData(rel='back')" ) ) {
$.mobile.back();
return false;
}
var baseUrl = getClosestBaseUrl( $link ),
//get href, if defined, otherwise default to empty hash
href = path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl );
//if ajax is disabled, exit early
if ( !$.mobile.ajaxEnabled && !path.isEmbeddedPage( href ) ) {
httpCleanup();
//use default click handling
return;
}
// XXX_jblas: Ideally links to application pages should be specified as
// an url to the application document with a hash that is either
// the site relative path or id to the page. But some of the
// internal code that dynamically generates sub-pages for nested
// lists and select dialogs, just write a hash in the link they
// create. This means the actual URL path is based on whatever
// the current value of the base tag is at the time this code
// is called. For now we are just assuming that any url with a
// hash in it is an application page reference.
if ( href.search( "#" ) !== -1 ) {
href = href.replace( /[^#]*#/, "" );
if ( !href ) {
//link was an empty hash meant purely
//for interaction, so we ignore it.
event.preventDefault();
return;
} else if ( path.isPath( href ) ) {
//we have apath so make it the href we want to load.
href = path.makeUrlAbsolute( href, baseUrl );
} else {
//we have a simple id so use the documentUrl as its base.
href = path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash );
}
}
// Should we handle this link, or let the browser deal with it?
var useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ),
// Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR
// requests if the document doing the request was loaded via the file:// protocol.
// This is usually to allow the application to "phone home" and fetch app specific
// data. We normally let the browser handle external/cross-domain urls, but if the
// allowCrossDomainPages option is true, we will allow cross-domain http/https
// requests to go through our page loading logic.
//check for protocol or rel and its not an embedded page
//TODO overlap in logic from isExternal, rel=external check should be
// moved into more comprehensive isExternalLink
isExternal = useDefaultUrlHandling || ( path.isExternal( href ) && !path.isPermittedCrossDomainRequest( documentUrl, href ) );
if ( isExternal ) {
httpCleanup();
//use default click handling
return;
}
//use ajax
var transition = $link.jqmData( "transition" ),
reverse = $link.jqmData( "direction" ) === "reverse" ||
// deprecated - remove by 1.0
$link.jqmData( "back" ),
//this may need to be more specific as we use data-rel more
role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined;
$.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } );
event.preventDefault();
});
//prefetch pages when anchors with data-prefetch are encountered
$.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() {
var urls = [];
$( this ).find( "a:jqmData(prefetch)" ).each(function() {
var $link = $( this ),
url = $link.attr( "href" );
if ( url && $.inArray( url, urls ) === -1 ) {
urls.push( url );
$.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } );
}
});
});
$.mobile._handleHashChange = function( url, data ) {
//find first page via hash
var to = path.stripHash(url),
//transition is false if it's the first page, undefined otherwise (and may be overridden by default)
transition = $.mobile.urlHistory.stack.length === 0 ? "none" : undefined,
// default options for the changPage calls made after examining the current state
// of the page and the hash, NOTE that the transition is derived from the previous
// history entry
changePageOptions = {
changeHash: false,
fromHashChange: true,
reverse: data.direction === "back"
};
$.extend( changePageOptions, data, {
transition: (urlHistory.getLast() || {}).transition || transition
});
// special case for dialogs
if ( urlHistory.activeIndex > 0 && to.indexOf( dialogHashKey ) > -1 && urlHistory.initialDst !== to ) {
// If current active page is not a dialog skip the dialog and continue
// in the same direction
if ( $.mobile.activePage && !$.mobile.activePage.is( ".ui-dialog" ) ) {
//determine if we're heading forward or backward and continue accordingly past
//the current dialog
if( data.direction === "back" ) {
$.mobile.back();
} else {
window.history.forward();
}
// prevent changePage call
return;
} else {
// if the current active page is a dialog and we're navigating
// to a dialog use the dialog objected saved in the stack
to = data.pageUrl;
var active = $.mobile.urlHistory.getActive();
// make sure to set the role, transition and reversal
// as most of this is lost by the domCache cleaning
$.extend( changePageOptions, {
role: active.role,
transition: active.transition,
reverse: data.direction === "back"
});
}
}
//if to is defined, load it
if ( to ) {
// At this point, 'to' can be one of 3 things, a cached page element from
// a history stack entry, an id, or site-relative/absolute URL. If 'to' is
// an id, we need to resolve it against the documentBase, not the location.href,
// since the hashchange could've been the result of a forward/backward navigation
// that crosses from an external page/dialog to an internal page/dialog.
to = !path.isPath( to ) ? ( path.makeUrlAbsolute( '#' + to, documentBase ) ) : to;
// If we're about to go to an initial URL that contains a reference to a non-existent
// internal page, go to the first page instead. We know that the initial hash refers to a
// non-existent page, because the initial hash did not end up in the initial urlHistory entry
if ( to === path.makeUrlAbsolute( '#' + urlHistory.initialDst, documentBase ) &&
urlHistory.stack.length && urlHistory.stack[0].url !== urlHistory.initialDst.replace( dialogHashKey, "" ) ) {
to = $.mobile.firstPage;
}
$.mobile.changePage( to, changePageOptions );
} else {
//there's no hash, go to the first page in the dom
$.mobile.changePage( $.mobile.firstPage, changePageOptions );
}
};
// TODO roll the logic here into the handleHashChange method
$window.bind( "navigate", function( e, data ) {
var url;
if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) {
return;
}
url = $.event.special.navigate.originalEventName.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url;
if( !url ) {
url = $.mobile.path.parseLocation().hash;
}
if( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ){
url = location.href;
}
$.mobile._handleHashChange( url, data.state );
});
//set page min-heights to be device specific
$.mobile.document.bind( "pageshow", $.mobile.resetActivePageHeight );
$.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight );
};//navreadyDeferred done callback
$( function() { domreadyDeferred.resolve(); } );
$.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } );
})( jQuery );
/*
* fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flip = "fade";
})( jQuery, this );
/*
* fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.flow = "fade";
})( jQuery, this );
/*
* fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.pop = "fade";
})( jQuery, this );
/*
* fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Use the simultaneous transitions handler for slide transitions
$.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous;
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slide = "fade";
})( jQuery, this );
/*
* fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slidedown = "fade";
})( jQuery, this );
/*
* fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
// Set the slide transitions's fallback to "fade"
$.mobile.transitionFallbacks.slidefade = "fade";
})( jQuery, this );
/*
* fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.slideup = "fade";
})( jQuery, this );
/*
* fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general
*/
(function( $, window, undefined ) {
$.mobile.transitionFallbacks.turn = "fade";
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.degradeInputs = {
color: false,
date: false,
datetime: false,
"datetime-local": false,
email: false,
month: false,
number: false,
range: "number",
search: "text",
tel: false,
time: false,
url: false,
week: false
};
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
var page = $.mobile.closestPageData( $( e.target ) ), options;
if ( !page ) {
return;
}
options = page.options;
// degrade inputs to avoid poorly implemented native functionality
$( e.target ).find( "input" ).not( page.keepNativeSelector() ).each(function() {
var $this = $( this ),
type = this.getAttribute( "type" ),
optType = options.degradeInputs[ type ] || "text";
if ( options.degradeInputs[ type ] ) {
var html = $( "<div>" ).html( $this.clone() ).html(),
// In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead
hasType = html.indexOf( " type=" ) > -1,
findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/,
repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" );
$this.replaceWith( html.replace( findstr, repstr ) );
}
});
});
})( jQuery );
(function( $, window, undefined ) {
$.widget( "mobile.dialog", $.mobile.widget, {
options: {
closeBtn: "left",
closeBtnText: "Close",
overlayTheme: "a",
corners: true,
initSelector: ":jqmData(role='dialog')"
},
// Override the theme set by the page plugin on pageshow
_handlePageBeforeShow: function() {
this._isCloseable = true;
if ( this.options.overlayTheme ) {
this.element
.page( "removeContainerBackground" )
.page( "setContainerBackground", this.options.overlayTheme );
}
},
_create: function() {
var self = this,
$el = this.element,
cornerClass = !!this.options.corners ? " ui-corner-all" : "",
dialogWrap = $( "<div/>", {
"role" : "dialog",
"class" : "ui-dialog-contain ui-overlay-shadow" + cornerClass
});
$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );
// Class the markup for dialog styling
// Set aria role
$el.wrapInner( dialogWrap );
/* bind events
- clicks and submits should use the closing transition that the dialog opened with
unless a data-transition is specified on the link/form
- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
*/
$el.bind( "vclick submit", function( event ) {
var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
active;
if ( $target.length && !$target.jqmData( "transition" ) ) {
active = $.mobile.urlHistory.getActive() || {};
$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
.attr( "data-" + $.mobile.ns + "direction", "reverse" );
}
});
this._on( $el, {
pagebeforeshow: "_handlePageBeforeShow"
});
$.extend( this, {
_createComplete: false
});
this._setCloseBtn( this.options.closeBtn );
},
_setCloseBtn: function( value ) {
var self = this, btn, location;
if ( this._headerCloseButton ) {
this._headerCloseButton.remove();
this._headerCloseButton = null;
}
if ( value !== "none" ) {
// Sanitize value
location = ( value === "left" ? "left" : "right" );
btn = $( "<a href='#' class='ui-btn-" + location + "' data-" + $.mobile.ns + "icon='delete' data-" + $.mobile.ns + "iconpos='notext'>"+ this.options.closeBtnText + "</a>" );
this.element.children().find( ":jqmData(role='header')" ).first().prepend( btn );
if ( this._createComplete && $.fn.buttonMarkup ) {
btn.buttonMarkup();
}
this._createComplete = true;
// this must be an anonymous function so that select menu dialogs can replace
// the close method. This is a change from previously just defining data-rel=back
// on the button and letting nav handle it
//
// Use click rather than vclick in order to prevent the possibility of unintentionally
// reopening the dialog if the dialog opening item was directly under the close button.
btn.bind( "click", function() {
self.close();
});
this._headerCloseButton = btn;
}
},
_setOption: function( key, value ) {
if ( key === "closeBtn" ) {
this._setCloseBtn( value );
}
this._super( key, value );
},
// Close method goes back in history
close: function() {
var idx, dst, hist = $.mobile.navigate.history;
if ( this._isCloseable ) {
this._isCloseable = false;
// If the hash listening is enabled and there is at least one preceding history
// entry it's ok to go back. Initial pages with the dialog hash state are an example
// where the stack check is necessary
if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) {
$.mobile.back();
} else {
idx = Math.max( 0, hist.activeIndex - 1 );
dst = hist.stack[ idx ].pageUrl || hist.stack[ idx ].url;
hist.previousIndex = hist.activeIndex;
hist.activeIndex = idx;
if ( !$.mobile.path.isPath( dst ) ) {
dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
}
$.mobile.changePage( dst, { direction: "back", changeHash: false, fromHashChange: true } );
}
}
}
});
//auto self-init widgets
$.mobile.document.delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
$.mobile.dialog.prototype.enhance( this );
});
})( jQuery, this );
(function( $, undefined ) {
$.mobile.page.prototype.options.backBtnText = "Back";
$.mobile.page.prototype.options.addBackBtn = false;
$.mobile.page.prototype.options.backBtnTheme = null;
$.mobile.page.prototype.options.headerTheme = "a";
$.mobile.page.prototype.options.footerTheme = "a";
$.mobile.page.prototype.options.contentTheme = null;
// NOTE bind used to force this binding to run before the buttonMarkup binding
// which expects .ui-footer top be applied in its gigantic selector
// TODO remove the buttonMarkup giant selector and move it to the various modules
// on which it depends
$.mobile.document.bind( "pagecreate", function( e ) {
var $page = $( e.target ),
o = $page.data( "mobile-page" ).options,
pageRole = $page.jqmData( "role" ),
pageTheme = o.theme;
$( ":jqmData(role='header'), :jqmData(role='footer'), :jqmData(role='content')", $page )
.jqmEnhanceable()
.each(function() {
var $this = $( this ),
role = $this.jqmData( "role" ),
theme = $this.jqmData( "theme" ),
contentTheme = theme || o.contentTheme || ( pageRole === "dialog" && pageTheme ),
$headeranchors,
leftbtn,
rightbtn,
backBtn;
$this.addClass( "ui-" + role );
//apply theming and markup modifications to page,header,content,footer
if ( role === "header" || role === "footer" ) {
var thisTheme = theme || ( role === "header" ? o.headerTheme : o.footerTheme ) || pageTheme;
$this
//add theme class
.addClass( "ui-bar-" + thisTheme )
// Add ARIA role
.attr( "role", role === "header" ? "banner" : "contentinfo" );
if ( role === "header") {
// Right,left buttons
$headeranchors = $this.children( "a, button" );
leftbtn = $headeranchors.hasClass( "ui-btn-left" );
rightbtn = $headeranchors.hasClass( "ui-btn-right" );
leftbtn = leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length;
rightbtn = rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length;
}
// Auto-add back btn on pages beyond first view
if ( o.addBackBtn &&
role === "header" &&
$( ".ui-page" ).length > 1 &&
$page.jqmData( "url" ) !== $.mobile.path.stripHash( location.hash ) &&
!leftbtn ) {
backBtn = $( "<a href='javascript:void(0);' class='ui-btn-left' data-"+ $.mobile.ns +"rel='back' data-"+ $.mobile.ns +"icon='arrow-l'>"+ o.backBtnText +"</a>" )
// If theme is provided, override default inheritance
.attr( "data-"+ $.mobile.ns +"theme", o.backBtnTheme || thisTheme )
.prependTo( $this );
}
// Page title
$this.children( "h1, h2, h3, h4, h5, h6" )
.addClass( "ui-title" )
// Regardless of h element number in src, it becomes h1 for the enhanced page
.attr({
"role": "heading",
"aria-level": "1"
});
} else if ( role === "content" ) {
if ( contentTheme ) {
$this.addClass( "ui-body-" + ( contentTheme ) );
}
// Add ARIA role
$this.attr( "role", "main" );
}
});
});
})( jQuery );
(function( $, undefined ) {
// This function calls getAttribute, which should be safe for data-* attributes
var getAttrFixed = function( e, key ) {
var value = e.getAttribute( key );
return value === "true" ? true :
value === "false" ? false :
value === null ? undefined : value;
};
$.fn.buttonMarkup = function( options ) {
var $workingSet = this,
nsKey = "data-" + $.mobile.ns,
key;
// Enforce options to be of type string
options = ( options && ( $.type( options ) === "object" ) )? options : {};
for ( var i = 0; i < $workingSet.length; i++ ) {
var el = $workingSet.eq( i ),
e = el[ 0 ],
o = $.extend( {}, $.fn.buttonMarkup.defaults, {
icon: options.icon !== undefined ? options.icon : getAttrFixed( e, nsKey + "icon" ),
iconpos: options.iconpos !== undefined ? options.iconpos : getAttrFixed( e, nsKey + "iconpos" ),
theme: options.theme !== undefined ? options.theme : getAttrFixed( e, nsKey + "theme" ) || $.mobile.getInheritedTheme( el, "c" ),
inline: options.inline !== undefined ? options.inline : getAttrFixed( e, nsKey + "inline" ),
shadow: options.shadow !== undefined ? options.shadow : getAttrFixed( e, nsKey + "shadow" ),
corners: options.corners !== undefined ? options.corners : getAttrFixed( e, nsKey + "corners" ),
iconshadow: options.iconshadow !== undefined ? options.iconshadow : getAttrFixed( e, nsKey + "iconshadow" ),
mini: options.mini !== undefined ? options.mini : getAttrFixed( e, nsKey + "mini" )
}, options ),
// Classes Defined
innerClass = "ui-btn-inner",
textClass = "ui-btn-text",
buttonClass, iconClass,
hover = false,
state = "up",
// Button inner markup
buttonInner,
buttonText,
buttonIcon,
buttonElements;
for ( key in o ) {
if ( o[ key ] === undefined || o[ key ] === null ) {
el.removeAttr( nsKey + key );
} else {
e.setAttribute( nsKey + key, o[ key ] );
}
}
if ( getAttrFixed( e, nsKey + "rel" ) === "popup" && el.attr( "href" ) ) {
e.setAttribute( "aria-haspopup", true );
e.setAttribute( "aria-owns", el.attr( "href" ) );
}
// Check if this element is already enhanced
buttonElements = $.data( ( ( e.tagName === "INPUT" || e.tagName === "BUTTON" ) ? e.parentNode : e ), "buttonElements" );
if ( buttonElements ) {
e = buttonElements.outer;
el = $( e );
buttonInner = buttonElements.inner;
buttonText = buttonElements.text;
// We will recreate this icon below
$( buttonElements.icon ).remove();
buttonElements.icon = null;
hover = buttonElements.hover;
state = buttonElements.state;
}
else {
buttonInner = document.createElement( o.wrapperEls );
buttonText = document.createElement( o.wrapperEls );
}
buttonIcon = o.icon ? document.createElement( "span" ) : null;
if ( attachEvents && !buttonElements ) {
attachEvents();
}
// if not, try to find closest theme container
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( el, "c" );
}
buttonClass = "ui-btn ";
buttonClass += ( hover ? "ui-btn-hover-" + o.theme : "" );
buttonClass += ( state ? " ui-btn-" + state + "-" + o.theme : "" );
buttonClass += o.shadow ? " ui-shadow" : "";
buttonClass += o.corners ? " ui-btn-corner-all" : "";
if ( o.mini !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `mini` style.
buttonClass += o.mini === true ? " ui-mini" : " ui-fullsize";
}
if ( o.inline !== undefined ) {
// Used to control styling in headers/footers, where buttons default to `inline` style.
buttonClass += o.inline === true ? " ui-btn-inline" : " ui-btn-block";
}
if ( o.icon ) {
o.icon = "ui-icon-" + o.icon;
o.iconpos = o.iconpos || "left";
iconClass = "ui-icon " + o.icon;
if ( o.iconshadow ) {
iconClass += " ui-icon-shadow";
}
}
if ( o.iconpos ) {
buttonClass += " ui-btn-icon-" + o.iconpos;
if ( o.iconpos === "notext" && !el.attr( "title" ) ) {
el.attr( "title", el.getEncodedText() );
}
}
if ( buttonElements ) {
el.removeClass( buttonElements.bcls || "" );
}
el.removeClass( "ui-link" ).addClass( buttonClass );
buttonInner.className = innerClass;
buttonText.className = textClass;
if ( !buttonElements ) {
buttonInner.appendChild( buttonText );
}
if ( buttonIcon ) {
buttonIcon.className = iconClass;
if ( !( buttonElements && buttonElements.icon ) ) {
buttonIcon.innerHTML = " ";
buttonInner.appendChild( buttonIcon );
}
}
while ( e.firstChild && !buttonElements ) {
buttonText.appendChild( e.firstChild );
}
if ( !buttonElements ) {
e.appendChild( buttonInner );
}
// Assign a structure containing the elements of this button to the elements of this button. This
// will allow us to recognize this as an already-enhanced button in future calls to buttonMarkup().
buttonElements = {
hover : hover,
state : state,
bcls : buttonClass,
outer : e,
inner : buttonInner,
text : buttonText,
icon : buttonIcon
};
$.data( e, 'buttonElements', buttonElements );
$.data( buttonInner, 'buttonElements', buttonElements );
$.data( buttonText, 'buttonElements', buttonElements );
if ( buttonIcon ) {
$.data( buttonIcon, 'buttonElements', buttonElements );
}
}
return this;
};
$.fn.buttonMarkup.defaults = {
corners: true,
shadow: true,
iconshadow: true,
wrapperEls: "span"
};
function closestEnabledButton( element ) {
var cname;
while ( element ) {
// Note that we check for typeof className below because the element we
// handed could be in an SVG DOM where className on SVG elements is defined to
// be of a different type (SVGAnimatedString). We only operate on HTML DOM
// elements, so we look for plain "string".
cname = ( typeof element.className === 'string' ) && ( element.className + ' ' );
if ( cname && cname.indexOf( "ui-btn " ) > -1 && cname.indexOf( "ui-disabled " ) < 0 ) {
break;
}
element = element.parentNode;
}
return element;
}
function updateButtonClass( $btn, classToRemove, classToAdd, hover, state ) {
var buttonElements = $.data( $btn[ 0 ], "buttonElements" );
$btn.removeClass( classToRemove ).addClass( classToAdd );
if ( buttonElements ) {
buttonElements.bcls = $( document.createElement( "div" ) )
.addClass( buttonElements.bcls + " " + classToAdd )
.removeClass( classToRemove )
.attr( "class" );
if ( hover !== undefined ) {
buttonElements.hover = hover;
}
buttonElements.state = state;
}
}
var attachEvents = function() {
var hoverDelay = $.mobile.buttonMarkup.hoverDelay, hov, foc;
$.mobile.document.bind( {
"vmousedown vmousecancel vmouseup vmouseover vmouseout focus blur scrollstart": function( event ) {
var theme,
$btn = $( closestEnabledButton( event.target ) ),
isTouchEvent = event.originalEvent && /^touch/.test( event.originalEvent.type ),
evt = event.type;
if ( $btn.length ) {
theme = $btn.attr( "data-" + $.mobile.ns + "theme" );
if ( evt === "vmousedown" ) {
if ( isTouchEvent ) {
// Use a short delay to determine if the user is scrolling before highlighting
hov = setTimeout( function() {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
}, hoverDelay );
} else {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-down-" + theme, undefined, "down" );
}
} else if ( evt === "vmousecancel" || evt === "vmouseup" ) {
updateButtonClass( $btn, "ui-btn-down-" + theme, "ui-btn-up-" + theme, undefined, "up" );
} else if ( evt === "vmouseover" || evt === "focus" ) {
if ( isTouchEvent ) {
// Use a short delay to determine if the user is scrolling before highlighting
foc = setTimeout( function() {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
}, hoverDelay );
} else {
updateButtonClass( $btn, "ui-btn-up-" + theme, "ui-btn-hover-" + theme, true, "" );
}
} else if ( evt === "vmouseout" || evt === "blur" || evt === "scrollstart" ) {
updateButtonClass( $btn, "ui-btn-hover-" + theme + " ui-btn-down-" + theme, "ui-btn-up-" + theme, false, "up" );
if ( hov ) {
clearTimeout( hov );
}
if ( foc ) {
clearTimeout( foc );
}
}
}
},
"focusin focus": function( event ) {
$( closestEnabledButton( event.target ) ).addClass( $.mobile.focusClass );
},
"focusout blur": function( event ) {
$( closestEnabledButton( event.target ) ).removeClass( $.mobile.focusClass );
}
});
attachEvents = null;
};
//links in bars, or those with data-role become buttons
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$( ":jqmData(role='button'), .ui-bar > a, .ui-header > a, .ui-footer > a, .ui-bar > :jqmData(role='controlgroup') > a", e.target )
.jqmEnhanceable()
.not( "button, input, .ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" )
.buttonMarkup();
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsible", $.mobile.widget, {
options: {
expandCueText: " click to expand contents",
collapseCueText: " click to collapse contents",
collapsed: true,
heading: "h1,h2,h3,h4,h5,h6,legend",
collapsedIcon: "plus",
expandedIcon: "minus",
iconpos: "left",
theme: null,
contentTheme: null,
inset: true,
corners: true,
mini: false,
initSelector: ":jqmData(role='collapsible')"
},
_create: function() {
var $el = this.element,
o = this.options,
collapsible = $el.addClass( "ui-collapsible" ),
collapsibleHeading = $el.children( o.heading ).first(),
collapsibleContent = collapsible.wrapInner( "<div class='ui-collapsible-content'></div>" ).children( ".ui-collapsible-content" ),
collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" ).addClass( "ui-collapsible-set" ),
collapsibleClasses = "";
// Replace collapsibleHeading if it's a legend
if ( collapsibleHeading.is( "legend" ) ) {
collapsibleHeading = $( "<div role='heading'>"+ collapsibleHeading.html() +"</div>" ).insertBefore( collapsibleHeading );
collapsibleHeading.next().remove();
}
// If we are in a collapsible set
if ( collapsibleSet.length ) {
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = collapsibleSet.jqmData( "theme" ) || $.mobile.getInheritedTheme( collapsibleSet, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = collapsibleSet.jqmData( "content-theme" );
}
// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
o.collapsedIcon = $el.jqmData( "collapsed-icon" ) || collapsibleSet.jqmData( "collapsed-icon" ) || o.collapsedIcon;
// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
o.expandedIcon = $el.jqmData( "expanded-icon" ) || collapsibleSet.jqmData( "expanded-icon" ) || o.expandedIcon;
// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
o.iconpos = $el.jqmData( "iconpos" ) || collapsibleSet.jqmData( "iconpos" ) || o.iconpos;
// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
if ( collapsibleSet.jqmData( "inset" ) !== undefined ) {
o.inset = collapsibleSet.jqmData( "inset" );
} else {
o.inset = true;
}
// Set corners for individual collapsibles to false when in a collapsible-set
o.corners = false;
// Gets the preference for mini in the set
if ( !o.mini ) {
o.mini = collapsibleSet.jqmData( "mini" );
}
} else {
// get inherited theme if not a set and no theme has been set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
}
if ( !!o.inset ) {
collapsibleClasses += " ui-collapsible-inset";
if ( !!o.corners ) {
collapsibleClasses += " ui-corner-all" ;
}
}
if ( o.contentTheme ) {
collapsibleClasses += " ui-collapsible-themed-content";
collapsibleContent.addClass( "ui-body-" + o.contentTheme );
}
if ( collapsibleClasses !== "" ) {
collapsible.addClass( collapsibleClasses );
}
collapsibleHeading
//drop heading in before content
.insertBefore( collapsibleContent )
//modify markup & attributes
.addClass( "ui-collapsible-heading" )
.append( "<span class='ui-collapsible-heading-status'></span>" )
.wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" )
.find( "a" )
.first()
.buttonMarkup({
shadow: false,
corners: false,
iconpos: o.iconpos,
icon: o.collapsedIcon,
mini: o.mini,
theme: o.theme
});
//events
collapsible
.bind( "expand collapse", function( event ) {
if ( !event.isDefaultPrevented() ) {
var $this = $( this ),
isCollapse = ( event.type === "collapse" );
event.preventDefault();
collapsibleHeading
.toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
.find( ".ui-collapsible-heading-status" )
.text( isCollapse ? o.expandCueText : o.collapseCueText )
.end()
.find( ".ui-icon" )
.toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
.toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
.end()
.find( "a" ).first().removeClass( $.mobile.activeBtnClass );
$this.toggleClass( "ui-collapsible-collapsed", isCollapse );
collapsibleContent.toggleClass( "ui-collapsible-content-collapsed", isCollapse ).attr( "aria-hidden", isCollapse );
collapsibleContent.trigger( "updatelayout" );
}
})
.trigger( o.collapsed ? "collapse" : "expand" );
collapsibleHeading
.bind( "tap", function( event ) {
collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
})
.bind( "click", function( event ) {
var type = collapsibleHeading.is( ".ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";
collapsible.trigger( type );
event.preventDefault();
event.stopPropagation();
});
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.collapsible.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.behaviors.addFirstLastClasses = {
_getVisibles: function( $els, create ) {
var visibles;
if ( create ) {
visibles = $els.not( ".ui-screen-hidden" );
} else {
visibles = $els.filter( ":visible" );
if ( visibles.length === 0 ) {
visibles = $els.not( ".ui-screen-hidden" );
}
}
return visibles;
},
_addFirstLastClasses: function( $els, $visibles, create ) {
$els.removeClass( "ui-first-child ui-last-child" );
$visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" );
if ( !create ) {
this.element.trigger( "updatelayout" );
}
}
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.collapsibleset", $.mobile.widget, $.extend( {
options: {
initSelector: ":jqmData(role='collapsible-set')"
},
_create: function() {
var $el = this.element.addClass( "ui-collapsible-set" ),
o = this.options;
// Inherit the theme from collapsible-set
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( $el, "c" );
}
// Inherit the content-theme from collapsible-set
if ( !o.contentTheme ) {
o.contentTheme = $el.jqmData( "content-theme" );
}
// Inherit the corner styling from collapsible-set
if ( !o.corners ) {
o.corners = $el.jqmData( "corners" );
}
if ( $el.jqmData( "inset" ) !== undefined ) {
o.inset = $el.jqmData( "inset" );
}
o.inset = o.inset !== undefined ? o.inset : true;
o.corners = o.corners !== undefined ? o.corners : true;
if ( !!o.corners && !!o.inset ) {
$el.addClass( "ui-corner-all" );
}
// Initialize the collapsible set if it's not already initialized
if ( !$el.jqmData( "collapsiblebound" ) ) {
$el
.jqmData( "collapsiblebound", true )
.bind( "expand", function( event ) {
var closestCollapsible = $( event.target )
.closest( ".ui-collapsible" );
if ( closestCollapsible.parent().is( ":jqmData(role='collapsible-set')" ) ) {
closestCollapsible
.siblings( ".ui-collapsible" )
.trigger( "collapse" );
}
});
}
},
_init: function() {
var $el = this.element,
collapsiblesInSet = $el.children( ":jqmData(role='collapsible')" ),
expanded = collapsiblesInSet.filter( ":jqmData(collapsed='false')" );
this._refresh( "true" );
// Because the corners are handled by the collapsible itself and the default state is collapsed
// That was causing https://github.com/jquery/jquery-mobile/issues/4116
expanded.trigger( "expand" );
},
_refresh: function( create ) {
var collapsiblesInSet = this.element.children( ":jqmData(role='collapsible')" );
$.mobile.collapsible.prototype.enhance( collapsiblesInSet.not( ".ui-collapsible" ) );
this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create );
},
refresh: function() {
this._refresh( false );
}
}, $.mobile.behaviors.addFirstLastClasses ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.collapsibleset.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
// filter function removes whitespace between label and form element so we can use inline-block (nodeType 3 = text)
$.fn.fieldcontain = function( options ) {
return this
.addClass( "ui-field-contain ui-body ui-br" )
.contents().filter( function() {
return ( this.nodeType === 3 && !/\S/.test( this.nodeValue ) );
}).remove();
};
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$( ":jqmData(role='fieldcontain')", e.target ).jqmEnhanceable().fieldcontain();
});
})( jQuery );
(function( $, undefined ) {
$.fn.grid = function( options ) {
return this.each(function() {
var $this = $( this ),
o = $.extend({
grid: null
}, options ),
$kids = $this.children(),
gridCols = { solo:1, a:2, b:3, c:4, d:5 },
grid = o.grid,
iterator;
if ( !grid ) {
if ( $kids.length <= 5 ) {
for ( var letter in gridCols ) {
if ( gridCols[ letter ] === $kids.length ) {
grid = letter;
}
}
} else {
grid = "a";
$this.addClass( "ui-grid-duo" );
}
}
iterator = gridCols[grid];
$this.addClass( "ui-grid-" + grid );
$kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" );
if ( iterator > 1 ) {
$kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" );
}
if ( iterator > 2 ) {
$kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" );
}
if ( iterator > 3 ) {
$kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" );
}
if ( iterator > 4 ) {
$kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" );
}
});
};
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.navbar", $.mobile.widget, {
options: {
iconpos: "top",
grid: null,
initSelector: ":jqmData(role='navbar')"
},
_create: function() {
var $navbar = this.element,
$navbtns = $navbar.find( "a" ),
iconpos = $navbtns.filter( ":jqmData(icon)" ).length ?
this.options.iconpos : undefined;
$navbar.addClass( "ui-navbar ui-mini" )
.attr( "role", "navigation" )
.find( "ul" )
.jqmEnhanceable()
.grid({ grid: this.options.grid });
$navbtns.buttonMarkup({
corners: false,
shadow: false,
inline: true,
iconpos: iconpos
});
$navbar.delegate( "a", "vclick", function( event ) {
// ui-btn-inner is returned as target
var target = $( event.target ).is( "a" ) ? $( this ) : $( this ).parent( "a" );
if ( !target.is( ".ui-disabled, .ui-btn-active" ) ) {
$navbtns.removeClass( $.mobile.activeBtnClass );
$( this ).addClass( $.mobile.activeBtnClass );
// The code below is a workaround to fix #1181
var activeBtn = $( this );
$( document ).one( "pagehide", function() {
activeBtn.removeClass( $.mobile.activeBtnClass );
});
}
});
// Buttons in the navbar with ui-state-persist class should regain their active state before page show
$navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() {
$navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass );
});
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.navbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget( "mobile.listview", $.mobile.widget, $.extend( {
options: {
theme: null,
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
icon: "arrow-r",
splitIcon: "arrow-r",
splitTheme: "b",
corners: true,
shadow: true,
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function() {
var t = this,
listviewClasses = "";
listviewClasses += t.options.inset ? " ui-listview-inset" : "";
if ( !!t.options.inset ) {
listviewClasses += t.options.corners ? " ui-corner-all" : "";
listviewClasses += t.options.shadow ? " ui-shadow" : "";
}
// create listview markup
t.element.addClass(function( i, orig ) {
return orig + " ui-listview" + listviewClasses;
});
t.refresh( true );
},
// This is a generic utility method for finding the first
// node with a given nodeName. It uses basic DOM traversal
// to be fast and is meant to be a substitute for simple
// $.fn.closest() and $.fn.children() calls on a single
// element. Note that callers must pass both the lowerCase
// and upperCase version of the nodeName they are looking for.
// The main reason for this is that this function will be
// called many times and we want to avoid having to lowercase
// the nodeName from the element every time to ensure we have
// a match. Note that this function lives here for now, but may
// be moved into $.mobile if other components need a similar method.
_findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) {
var dict = {};
dict[ lcName ] = dict[ ucName ] = true;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
return ele;
}
ele = ele[ nextProp ];
}
return null;
},
_getChildrenByTagName: function( ele, lcName, ucName ) {
var results = [],
dict = {};
dict[ lcName ] = dict[ ucName ] = true;
ele = ele.firstChild;
while ( ele ) {
if ( dict[ ele.nodeName ] ) {
results.push( ele );
}
ele = ele.nextSibling;
}
return $( results );
},
_addThumbClasses: function( containers ) {
var i, img, len = containers.length;
for ( i = 0; i < len; i++ ) {
img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
if ( img.length ) {
img.addClass( "ui-li-thumb" );
$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.is( ".ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
}
}
},
refresh: function( create ) {
this.parentPage = this.element.closest( ".ui-page" );
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData( "dividertheme" ) || o.dividerTheme,
listsplittheme = $list.jqmData( "splittheme" ),
listspliticon = $list.jqmData( "spliticon" ),
listicon = $list.jqmData( "icon" ),
li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
ol = !!$.nodeName( $list[ 0 ], "ol" ),
jsCount = !$.support.cssPseudoElement,
start = $list.attr( "start" ),
itemClassDict = {},
item, itemClass, itemTheme,
a, last, splittheme, counter, startCount, newStartCount, countParent, icon, imgParents, img, linkIcon;
if ( ol && jsCount ) {
$list.find( ".ui-li-dec" ).remove();
}
if ( ol ) {
// Check if a start attribute has been set while taking a value of 0 into account
if ( start || start === 0 ) {
if ( !jsCount ) {
startCount = parseInt( start , 10 ) - 1;
$list.css( "counter-reset", "listnumbering " + startCount );
} else {
counter = parseInt( start , 10 );
}
} else if ( jsCount ) {
counter = 1;
}
}
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
for ( var pos = 0, numli = li.length; pos < numli; pos++ ) {
item = li.eq( pos );
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if ( create || !item.hasClass( "ui-li" ) ) {
itemTheme = item.jqmData( "theme" ) || o.theme;
a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
var isDivider = ( item.jqmData( "role" ) === "list-divider" );
if ( a.length && !isDivider ) {
icon = item.jqmData( "icon" );
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
theme: itemTheme
});
if ( ( icon !== false ) && ( a.length === 1 ) ) {
item.addClass( "ui-li-has-arrow" );
}
a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );
if ( a.length > 1 ) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData( "theme" ) || o.splitTheme;
linkIcon = last.jqmData( "icon" );
last.appendTo( item )
.attr( "title", $.trim(last.getEncodedText()) )
.addClass( "ui-li-link-alt" )
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: "notext"
})
.find( ".ui-btn-inner" )
.append(
$( document.createElement( "span" ) ).buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
// link icon overrides list item icon overrides ul element overrides options
icon: linkIcon || icon || listspliticon || o.splitIcon
})
);
}
} else if ( isDivider ) {
itemClass += " ui-li-divider ui-bar-" + ( item.jqmData( "theme" ) || dividertheme );
item.attr( "role", "heading" );
if ( ol ) {
//reset counter when a divider heading is encountered
if ( start || start === 0 ) {
if ( !jsCount ) {
newStartCount = parseInt( start , 10 ) - 1;
item.css( "counter-reset", "listnumbering " + newStartCount );
} else {
counter = parseInt( start , 10 );
}
} else if ( jsCount ) {
counter = 1;
}
}
} else {
itemClass += " ui-li-static ui-btn-up-" + itemTheme;
}
}
if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" );
countParent.addClass( "ui-li-jsnumbering" )
.prepend( "<span class='ui-li-dec'>" + ( counter++ ) + ". </span>" );
}
// Instead of setting item class directly on the list item and its
// btn-inner at this point in time, push the item into a dictionary
// that tells us what class to set on it so we can do this after this
// processing loop is finished.
if ( !itemClassDict[ itemClass ] ) {
itemClassDict[ itemClass ] = [];
}
itemClassDict[ itemClass ].push( item[ 0 ] );
}
// Set the appropriate listview item classes on each list item
// and their btn-inner elements. The main reason we didn't do this
// in the for-loop above is because we can eliminate per-item function overhead
// by calling addClass() and children() once or twice afterwards. This
// can give us a significant boost on platforms like WP7.5.
for ( itemClass in itemClassDict ) {
$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
}
$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
.end()
.find( "p, dl" ).addClass( "ui-li-desc" )
.end()
.find( ".ui-li-aside" ).each(function() {
var $this = $( this );
$this.prependTo( $this.parent() ); //shift aside to front for css float
})
.end()
.find( ".ui-li-count" ).each(function() {
$( this ).closest( "li" ).addClass( "ui-li-has-count" );
}).addClass( "ui-btn-up-" + ( $list.jqmData( "counttheme" ) || this.options.countTheme) + " ui-btn-corner-all" );
// The idea here is to look at the first image in the list item
// itself, and any .ui-link-inherit element it may contain, so we
// can place the appropriate classes on the image and list item.
// Note that we used to use something like:
//
// li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
//
// But executing a find() like that on Windows Phone 7.5 took a
// really long time. Walking things manually with the code below
// allows the 400 listview item page to load in about 3 seconds as
// opposed to 30 seconds.
this._addThumbClasses( li );
this._addThumbClasses( $list.find( ".ui-link-inherit" ) );
this._addFirstLastClasses( li, this._getVisibles( li, create ), create );
// autodividers binds to this to redraw dividers after the listview refresh
this._trigger( "afterrefresh" );
},
//create a string for ID/subpage url creation
_idStringEscape: function( str ) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function() {
var parentList = this.element,
parentPage = parentList.closest( ".ui-page" ),
parentUrl = parentPage.jqmData( "url" ),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr( "id" ),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find( ":jqmData(role='footer')" ).jqmData( "id" ),
hasSubPages;
if ( typeof listCountPerPage[ parentId ] === "undefined" ) {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$( parentList.find( "li>ul, li>ol" ).toArray().reverse() ).each(function( i ) {
var self = this,
list = $( this ),
listId = list.attr( "id" ) || parentListId + "-" + i,
parent = list.parent(),
nodeElsFull = $( list.prevAll().toArray().reverse() ),
nodeEls = nodeElsFull.length ? nodeElsFull : $( "<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>" ),
title = nodeEls.first().getEncodedText(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData( "theme" ) || o.theme,
countTheme = list.jqmData( "counttheme" ) || parentList.jqmData( "counttheme" ) || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap( "<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>" )
.parent()
.before( "<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>" )
.after( persistentFooterID ? $( "<div " + dns + "role='footer' " + dns + "id='"+ persistentFooterID +"'>" ) : "" )
.parent()
.appendTo( $.mobile.pageContainer );
newPage.page();
anchor = parent.find( 'a:first' );
if ( !anchor.length ) {
anchor = $( "<a/>" ).html( nodeEls || title ).prependTo( parent.empty() );
}
anchor.attr( "href", "#" + id );
}).listview();
// on pagehide, remove any nested pages along with the parent page, as long as they aren't active
// and aren't embedded
if ( hasSubPages &&
parentPage.is( ":jqmData(external-page='true')" ) &&
parentPage.data( "mobile-page" ).options.domCache === false ) {
var newRemove = function( e, ui ) {
var nextPage = ui.nextPage, npURL,
prEvent = new $.Event( "pageremove" );
if ( ui.nextPage ) {
npURL = nextPage.jqmData( "url" );
if ( npURL.indexOf( parentUrl + "&" + $.mobile.subPageUrlKey ) !== 0 ) {
self.childPages().remove();
parentPage.trigger( prEvent );
if ( !prEvent.isDefaultPrevented() ) {
parentPage.removeWithDependents();
}
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind( "pagehide.remove" )
.bind( "pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function() {
var parentUrl = this.parentPage.jqmData( "url" );
return $( ":jqmData(url^='"+ parentUrl + "&" + $.mobile.subPageUrlKey + "')" );
}
}, $.mobile.behaviors.addFirstLastClasses ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.listview.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $ ) {
var meta = $( "meta[name=viewport]" ),
initialContent = meta.attr( "content" ),
disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no",
enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes",
disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent );
$.mobile.zoom = $.extend( {}, {
enabled: !disabledInitially,
locked: false,
disable: function( lock ) {
if ( !disabledInitially && !$.mobile.zoom.locked ) {
meta.attr( "content", disabledZoom );
$.mobile.zoom.enabled = false;
$.mobile.zoom.locked = lock || false;
}
},
enable: function( unlock ) {
if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) {
meta.attr( "content", enabledZoom );
$.mobile.zoom.enabled = true;
$.mobile.zoom.locked = false;
}
},
restore: function() {
if ( !disabledInitially ) {
meta.attr( "content", initialContent );
$.mobile.zoom.enabled = true;
}
}
});
}( jQuery ));
(function( $, undefined ) {
$.widget( "mobile.textinput", $.mobile.widget, {
options: {
theme: null,
mini: false,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "input[type='text'], input[type='search'], :jqmData(type='search'), input[type='number'], :jqmData(type='number'), input[type='password'], input[type='email'], input[type='url'], input[type='tel'], textarea, input[type='time'], input[type='date'], input[type='month'], input[type='week'], input[type='datetime'], input[type='datetime-local'], input[type='color'], input:not([type]), input[type='file']",
clearBtn: false,
clearSearchButtonText: null, //deprecating for 1.3...
clearBtnText: "clear text",
disabled: false
},
_create: function() {
var self = this,
input = this.element,
o = this.options,
theme = o.theme || $.mobile.getInheritedTheme( this.element, "c" ),
themeclass = " ui-body-" + theme,
miniclass = o.mini ? " ui-mini" : "",
isSearch = input.is( "[type='search'], :jqmData(type='search')" ),
focusedEl,
clearbtn,
clearBtnText = o.clearSearchButtonText || o.clearBtnText,
clearBtnBlacklist = input.is( "textarea, :jqmData(type='range')" ),
inputNeedsClearBtn = !!o.clearBtn && !clearBtnBlacklist,
inputNeedsWrap = input.is( "input" ) && !input.is( ":jqmData(type='range')" );
function toggleClear() {
setTimeout( function() {
clearbtn.toggleClass( "ui-input-clear-hidden", !input.val() );
}, 0 );
}
$( "label[for='" + input.attr( "id" ) + "']" ).addClass( "ui-input-text" );
focusedEl = input.addClass( "ui-input-text ui-body-"+ theme );
// XXX: Temporary workaround for issue 785 (Apple bug 8910589).
// Turn off autocorrect and autocomplete on non-iOS 5 devices
// since the popup they use can't be dismissed by the user. Note
// that we test for the presence of the feature by looking for
// the autocorrect property on the input element. We currently
// have no test for iOS 5 or newer so we're temporarily using
// the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. - jblas
if ( typeof input[0].autocorrect !== "undefined" && !$.support.touchOverflow ) {
// Set the attribute instead of the property just in case there
// is code that attempts to make modifications via HTML.
input[0].setAttribute( "autocorrect", "off" );
input[0].setAttribute( "autocomplete", "off" );
}
//"search" and "text" input widgets
if ( isSearch ) {
focusedEl = input.wrap( "<div class='ui-input-search ui-shadow-inset ui-btn-corner-all ui-btn-shadow ui-icon-searchfield" + themeclass + miniclass + "'></div>" ).parent();
} else if ( inputNeedsWrap ) {
focusedEl = input.wrap( "<div class='ui-input-text ui-shadow-inset ui-corner-all ui-btn-shadow" + themeclass + miniclass + "'></div>" ).parent();
}
if( inputNeedsClearBtn || isSearch ) {
clearbtn = $( "<a href='#' class='ui-input-clear' title='" + clearBtnText + "'>" + clearBtnText + "</a>" )
.bind( "click", function( event ) {
input
.val( "" )
.focus()
.trigger( "change" );
clearbtn.addClass( "ui-input-clear-hidden" );
event.preventDefault();
})
.appendTo( focusedEl )
.buttonMarkup({
icon: "delete",
iconpos: "notext",
corners: true,
shadow: true,
mini: o.mini
});
if ( !isSearch ) {
focusedEl.addClass( "ui-input-has-clear" );
}
toggleClear();
input.bind( "paste cut keyup input focus change blur", toggleClear );
}
else if ( !inputNeedsWrap && !isSearch ) {
input.addClass( "ui-corner-all ui-shadow-inset" + themeclass + miniclass );
}
input.focus(function() {
// In many situations, iOS will zoom into the input upon tap, this prevents that from happening
if ( o.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
focusedEl.addClass( $.mobile.focusClass );
})
.blur(function() {
focusedEl.removeClass( $.mobile.focusClass );
if ( o.preventFocusZoom ) {
$.mobile.zoom.enable( true );
}
});
// Autogrow
if ( input.is( "textarea" ) ) {
var extraLineHeight = 15,
keyupTimeoutBuffer = 100,
keyupTimeout;
this._keyup = function() {
var scrollHeight = input[ 0 ].scrollHeight,
clientHeight = input[ 0 ].clientHeight;
if ( clientHeight < scrollHeight ) {
var paddingTop = parseFloat( input.css( "padding-top" ) ),
paddingBottom = parseFloat( input.css( "padding-bottom" ) ),
paddingHeight = paddingTop + paddingBottom;
input.height( scrollHeight - paddingHeight + extraLineHeight );
}
};
input.on( "keyup change input paste", function() {
clearTimeout( keyupTimeout );
keyupTimeout = setTimeout( self._keyup, keyupTimeoutBuffer );
});
// binding to pagechange here ensures that for pages loaded via
// ajax the height is recalculated without user input
this._on( true, $.mobile.document, { "pagechange": "_keyup" });
// Issue 509: the browser is not providing scrollHeight properly until the styles load
if ( $.trim( input.val() ) ) {
// bind to the window load to make sure the height is calculated based on BOTH
// the DOM and CSS
this._on( true, $.mobile.window, {"load": "_keyup"});
}
}
if ( input.attr( "disabled" ) ) {
this.disable();
}
},
disable: function() {
var $el,
isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
parentNeedsDisabled = this.element.attr( "disabled", true ) && ( inputNeedsWrap || isSearch );
if ( parentNeedsDisabled ) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.addClass( "ui-disabled" );
return this._setOption( "disabled", true );
},
enable: function() {
var $el,
isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ),
inputNeedsWrap = this.element.is( "input" ) && !this.element.is( ":jqmData(type='range')" ),
parentNeedsEnabled = this.element.attr( "disabled", false ) && ( inputNeedsWrap || isSearch );
if ( parentNeedsEnabled ) {
$el = this.element.parent();
} else {
$el = this.element;
}
$el.removeClass( "ui-disabled" );
return this._setOption( "disabled", false );
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.textinput.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";
$.mobile.listview.prototype.options.filterReveal = false;
// TODO rename callback/deprecate and default to the item itself as the first argument
var defaultFilterCallback = function( text, searchValue, item ) {
return text.toString().toLowerCase().indexOf( searchValue ) === -1;
};
$.mobile.listview.prototype.options.filterCallback = defaultFilterCallback;
$.mobile.document.delegate( "ul, ol", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "mobile-listview" );
if ( !listview || !listview.options.filter ) {
return;
}
if ( listview.options.filterReveal ) {
list.children().addClass( "ui-screen-hidden" );
}
var wrapper = $( "<form>", {
"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
"role": "search"
}).submit( function( e ) {
e.preventDefault();
search.blur();
}),
onKeyUp = function( e ) {
var $this = $( this ),
val = this.value.toLowerCase(),
listItems = null,
li = list.children(),
lastval = $this.jqmData( "lastval" ) + "",
childItems = false,
itemtext = "",
item,
// Check if a custom filter callback applies
isCustomFilterCallback = listview.options.filterCallback !== defaultFilterCallback;
if ( lastval && lastval === val ) {
// Execute the handler only once per value change
return;
}
listview._trigger( "beforefilter", "beforefilter", { input: this } );
// Change val as lastval for next execution
$this.jqmData( "lastval" , val );
if ( isCustomFilterCallback || val.length < lastval.length || val.indexOf( lastval ) !== 0 ) {
// Custom filter callback applies or removed chars or pasted something totally different, check all items
listItems = list.children();
} else {
// Only chars added, not removed, only use visible subset
listItems = list.children( ":not(.ui-screen-hidden)" );
if ( !listItems.length && listview.options.filterReveal ) {
listItems = list.children( ".ui-screen-hidden" );
}
}
if ( val ) {
// This handles hiding regular rows without the text we search for
// and any list dividers without regular rows shown under it
for ( var i = listItems.length - 1; i >= 0; i-- ) {
item = $( listItems[ i ] );
itemtext = item.jqmData( "filtertext" ) || item.text();
if ( item.is( "li:jqmData(role=list-divider)" ) ) {
item.toggleClass( "ui-filter-hidequeue" , !childItems );
// New bucket!
childItems = false;
} else if ( listview.options.filterCallback( itemtext, val, item ) ) {
//mark to be hidden
item.toggleClass( "ui-filter-hidequeue" , true );
} else {
// There's a shown item in the bucket
childItems = true;
}
}
// Show items, not marked to be hidden
listItems
.filter( ":not(.ui-filter-hidequeue)" )
.toggleClass( "ui-screen-hidden", false );
// Hide items, marked to be hidden
listItems
.filter( ".ui-filter-hidequeue" )
.toggleClass( "ui-screen-hidden", true )
.toggleClass( "ui-filter-hidequeue", false );
} else {
//filtervalue is empty => show all
listItems.toggleClass( "ui-screen-hidden", !!listview.options.filterReveal );
}
listview._addFirstLastClasses( li, listview._getVisibles( li, false ), false );
},
search = $( "<input>", {
placeholder: listview.options.filterPlaceholder
})
.attr( "data-" + $.mobile.ns + "type", "search" )
.jqmData( "lastval", "" )
.bind( "keyup change input", onKeyUp )
.appendTo( wrapper )
.textinput();
if ( listview.options.inset ) {
wrapper.addClass( "ui-listview-filter-inset" );
}
wrapper.bind( "submit", function() {
return false;
})
.insertBefore( list );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.listview.prototype.options.autodividers = false;
$.mobile.listview.prototype.options.autodividersSelector = function( elt ) {
// look for the text in the given element
var text = $.trim( elt.text() ) || null;
if ( !text ) {
return null;
}
// create the text for the divider (first uppercased letter)
text = text.slice( 0, 1 ).toUpperCase();
return text;
};
$.mobile.document.delegate( "ul,ol", "listviewcreate", function() {
var list = $( this ),
listview = list.data( "mobile-listview" );
if ( !listview || !listview.options.autodividers ) {
return;
}
var replaceDividers = function () {
list.find( "li:jqmData(role='list-divider')" ).remove();
var lis = list.find( 'li' ),
lastDividerText = null, li, dividerText;
for ( var i = 0; i < lis.length ; i++ ) {
li = lis[i];
dividerText = listview.options.autodividersSelector( $( li ) );
if ( dividerText && lastDividerText !== dividerText ) {
var divider = document.createElement( 'li' );
divider.appendChild( document.createTextNode( dividerText ) );
divider.setAttribute( 'data-' + $.mobile.ns + 'role', 'list-divider' );
li.parentNode.insertBefore( divider, li );
}
lastDividerText = dividerText;
}
};
var afterListviewRefresh = function () {
list.unbind( 'listviewafterrefresh', afterListviewRefresh );
replaceDividers();
listview.refresh();
list.bind( 'listviewafterrefresh', afterListviewRefresh );
};
afterListviewRefresh();
});
})( jQuery );
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ) {
$( ":jqmData(role='nojs')", e.target ).addClass( "ui-nojs" );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.behaviors.formReset = {
_handleFormReset: function() {
this._on( this.element.closest( "form" ), {
reset: function() {
this._delay( "_reset" );
}
});
}
};
})( jQuery );
/*
* "checkboxradio" plugin
*/
(function( $, undefined ) {
$.widget( "mobile.checkboxradio", $.mobile.widget, $.extend( {
options: {
theme: null,
mini: false,
initSelector: "input[type='checkbox'],input[type='radio']"
},
_create: function() {
var self = this,
input = this.element,
o = this.options,
inheritAttr = function( input, dataAttr ) {
return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr );
},
// NOTE: Windows Phone could not find the label through a selector
// filter works though.
parentLabel = $( input ).closest( "label" ),
label = parentLabel.length ? parentLabel : $( input ).closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ).find( "label" ).filter( "[for='" + input[0].id + "']" ).first(),
inputtype = input[0].type,
mini = inheritAttr( input, "mini" ) || o.mini,
checkedState = inputtype + "-on",
uncheckedState = inputtype + "-off",
iconpos = inheritAttr( input, "iconpos" ),
checkedClass = "ui-" + checkedState,
uncheckedClass = "ui-" + uncheckedState;
if ( inputtype !== "checkbox" && inputtype !== "radio" ) {
return;
}
// Expose for other methods
$.extend( this, {
label: label,
inputtype: inputtype,
checkedClass: checkedClass,
uncheckedClass: uncheckedClass,
checkedicon: checkedState,
uncheckedicon: uncheckedState
});
// If there's no selected theme check the data attr
if ( !o.theme ) {
o.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
label.buttonMarkup({
theme: o.theme,
icon: uncheckedState,
shadow: false,
mini: mini,
iconpos: iconpos
});
// Wrap the input + label in a div
var wrapper = document.createElement('div');
wrapper.className = 'ui-' + inputtype;
input.add( label ).wrapAll( wrapper );
label.bind({
vmouseover: function( event ) {
if ( $( this ).parent().is( ".ui-disabled" ) ) {
event.stopPropagation();
}
},
vclick: function( event ) {
if ( input.is( ":disabled" ) ) {
event.preventDefault();
return;
}
self._cacheVals();
input.prop( "checked", inputtype === "radio" && true || !input.prop( "checked" ) );
// trigger click handler's bound directly to the input as a substitute for
// how label clicks behave normally in the browsers
// TODO: it would be nice to let the browser's handle the clicks and pass them
// through to the associate input. we can swallow that click at the parent
// wrapper element level
input.triggerHandler( 'click' );
// Input set for common radio buttons will contain all the radio
// buttons, but will not for checkboxes. clearing the checked status
// of other radios ensures the active button state is applied properly
self._getInputSet().not( input ).prop( "checked", false );
self._updateAll();
return false;
}
});
input
.bind({
vmousedown: function() {
self._cacheVals();
},
vclick: function() {
var $this = $( this );
// Adds checked attribute to checked input when keyboard is used
if ( $this.is( ":checked" ) ) {
$this.prop( "checked", true);
self._getInputSet().not( $this ).prop( "checked", false );
} else {
$this.prop( "checked", false );
}
self._updateAll();
},
focus: function() {
label.addClass( $.mobile.focusClass );
},
blur: function() {
label.removeClass( $.mobile.focusClass );
}
});
this._handleFormReset();
this.refresh();
},
_cacheVals: function() {
this._getInputSet().each(function() {
$( this ).jqmData( "cacheVal", this.checked );
});
},
//returns either a set of radios with the same name attribute, or a single checkbox
_getInputSet: function() {
if ( this.inputtype === "checkbox" ) {
return this.element;
}
return this.element.closest( "form, :jqmData(role='page'), :jqmData(role='dialog')" )
.find( "input[name='" + this.element[0].name + "'][type='" + this.inputtype + "']" );
},
_updateAll: function() {
var self = this;
this._getInputSet().each(function() {
var $this = $( this );
if ( this.checked || self.inputtype === "checkbox" ) {
$this.trigger( "change" );
}
})
.checkboxradio( "refresh" );
},
_reset: function() {
this.refresh();
},
refresh: function() {
var input = this.element[ 0 ],
active = " " + $.mobile.activeBtnClass,
checkedClass = this.checkedClass + ( this.element.parents( ".ui-controlgroup-horizontal" ).length ? active : "" ),
label = this.label;
if ( input.checked ) {
label.removeClass( this.uncheckedClass + active ).addClass( checkedClass ).buttonMarkup( { icon: this.checkedicon } );
} else {
label.removeClass( checkedClass ).addClass( this.uncheckedClass ).buttonMarkup( { icon: this.uncheckedicon } );
}
if ( input.disabled ) {
this.disable();
} else {
this.enable();
}
},
disable: function() {
this.element.prop( "disabled", true ).parent().addClass( "ui-disabled" );
},
enable: function() {
this.element.prop( "disabled", false ).parent().removeClass( "ui-disabled" );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.checkboxradio.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.button", $.mobile.widget, {
options: {
theme: null,
icon: null,
iconpos: null,
corners: true,
shadow: true,
iconshadow: true,
inline: null,
mini: null,
initSelector: "button, [type='button'], [type='submit'], [type='reset']"
},
_create: function() {
var $el = this.element,
$button,
// create a copy of this.options we can pass to buttonMarkup
o = ( function( tdo ) {
var key, ret = {};
for ( key in tdo ) {
if ( tdo[ key ] !== null && key !== "initSelector" ) {
ret[ key ] = tdo[ key ];
}
}
return ret;
} )( this.options ),
classes = "",
$buttonPlaceholder;
// if this is a link, check if it's been enhanced and, if not, use the right function
if ( $el[ 0 ].tagName === "A" ) {
if ( !$el.hasClass( "ui-btn" ) ) {
$el.buttonMarkup();
}
return;
}
// get the inherited theme
// TODO centralize for all widgets
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.element, "c" );
}
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if ( !!~$el[0].className.indexOf( "ui-btn-left" ) ) {
classes = "ui-btn-left";
}
if ( !!~$el[0].className.indexOf( "ui-btn-right" ) ) {
classes = "ui-btn-right";
}
if ( $el.attr( "type" ) === "submit" || $el.attr( "type" ) === "reset" ) {
if ( classes ) {
classes += " ui-submit";
} else {
classes = "ui-submit";
}
}
$( "label[for='" + $el.attr( "id" ) + "']" ).addClass( "ui-submit" );
// Add ARIA role
this.button = $( "<div></div>" )
[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() )
.insertBefore( $el )
.buttonMarkup( o )
.addClass( classes )
.append( $el.addClass( "ui-btn-hidden" ) );
$button = this.button;
$el.bind({
focus: function() {
$button.addClass( $.mobile.focusClass );
},
blur: function() {
$button.removeClass( $.mobile.focusClass );
}
});
this.refresh();
},
_setOption: function( key, value ) {
var op = {};
op[ key ] = value;
if ( key !== "initSelector" ) {
this.button.buttonMarkup( op );
// Record the option change in the options and in the DOM data-* attributes
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
}
this._super( "_setOption", key, value );
},
enable: function() {
this.element.attr( "disabled", false );
this.button.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.button.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
},
refresh: function() {
var $el = this.element;
if ( $el.prop("disabled") ) {
this.disable();
} else {
this.enable();
}
// Grab the button's text element from its implementation-independent data item
$( this.button.data( 'buttonElements' ).text )[ $el.html() ? "html" : "text" ]( $el.html() || $el.val() );
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.button.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.slider", $.mobile.widget, $.extend( {
widgetEventPrefix: "slide",
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')",
mini: false,
highlight: false
},
_create: function() {
// TODO: Each of these should have comments explain what they're for
var self = this,
control = this.element,
parentTheme = $.mobile.getInheritedTheme( control, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
cType = control[ 0 ].nodeName.toLowerCase(),
isSelect = this.isToggleSwitch = cType === "select",
isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ),
selectClass = ( this.isToggleSwitch ) ? "ui-slider-switch" : "",
controlID = control.attr( "id" ),
$label = $( "[for='" + controlID + "']" ),
labelID = $label.attr( "id" ) || controlID + "-label",
label = $label.attr( "id", labelID ),
min = !this.isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0,
max = !this.isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1,
step = window.parseFloat( control.attr( "step" ) || 1 ),
miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "",
domHandle = document.createElement( "a" ),
handle = $( domHandle ),
domSlider = document.createElement( "div" ),
slider = $( domSlider ),
valuebg = this.options.highlight && !this.isToggleSwitch ? (function() {
var bg = document.createElement( "div" );
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $( bg ).prependTo( slider );
})() : false,
options,
wrapper;
domHandle.setAttribute( "href", "#" );
domSlider.setAttribute( "role", "application" );
domSlider.className = [this.isToggleSwitch ? "ui-slider " : "ui-slider-track ",selectClass," ui-btn-down-",trackTheme," ui-btn-corner-all", miniClass].join( "" );
domHandle.className = "ui-slider-handle";
domSlider.appendChild( domHandle );
handle.buttonMarkup({ corners: true, theme: theme, shadow: true })
.attr({
"role": "slider",
"aria-valuemin": min,
"aria-valuemax": max,
"aria-valuenow": this._value(),
"aria-valuetext": this._value(),
"title": this._value(),
"aria-labelledby": labelID
});
$.extend( this, {
slider: slider,
handle: handle,
type: cType,
step: step,
max: max,
min: min,
valuebg: valuebg,
isRangeslider: isRangeslider,
dragging: false,
beforeStart: null,
userModified: false,
mouseMoved: false
});
if ( this.isToggleSwitch ) {
wrapper = document.createElement( "div" );
wrapper.className = "ui-slider-inneroffset";
for ( var j = 0, length = domSlider.childNodes.length; j < length; j++ ) {
wrapper.appendChild( domSlider.childNodes[j] );
}
domSlider.appendChild( wrapper );
// slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" );
// make the handle move with a smooth transition
handle.addClass( "ui-slider-handle-snapping" );
options = control.find( "option" );
for ( var i = 0, optionsCount = options.length; i < optionsCount; i++ ) {
var side = !i ? "b" : "a",
sliderTheme = !i ? " ui-btn-down-" + trackTheme : ( " " + $.mobile.activeBtnClass ),
sliderLabel = document.createElement( "div" ),
sliderImg = document.createElement( "span" );
sliderImg.className = ["ui-slider-label ui-slider-label-", side, sliderTheme, " ui-btn-corner-all"].join( "" );
sliderImg.setAttribute( "role", "img" );
sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) );
$( sliderImg ).prependTo( slider );
}
self._labels = $( ".ui-slider-label", slider );
}
label.addClass( "ui-slider" );
// monitor the input for updated values
control.addClass( this.isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" );
this._on( control, {
"change": "_controlChange",
"keyup": "_controlKeyup",
"blur": "_controlBlur",
"vmouseup": "_controlVMouseUp"
});
slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) )
.bind( "vclick", false );
// We have to instantiate a new function object for the unbind to work properly
// since the method itself is defined in the prototype (causing it to unbind everything)
this._on( document, { "vmousemove": "_preventDocumentDrag" });
this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" });
slider.insertAfter( control );
// wrap in a div for styling purposes
if ( !this.isToggleSwitch && !isRangeslider ) {
wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>";
control.add( slider ).wrapAll( wrapper );
}
// Only add focus class to toggle switch, sliders get it automatically from ui-btn
if ( this.isToggleSwitch ) {
this.handle.bind({
focus: function() {
slider.addClass( $.mobile.focusClass );
},
blur: function() {
slider.removeClass( $.mobile.focusClass );
}
});
}
// bind the handle event callbacks and set the context to the widget instance
this._on( this.handle, {
"vmousedown": "_handleVMouseDown",
"keydown": "_handleKeydown",
"keyup": "_handleKeyup"
});
this.handle.bind( "vclick", false );
this._handleFormReset();
this.refresh( undefined, undefined, true );
},
_controlChange: function( event ) {
// if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again
if ( this._trigger( "controlchange", event ) === false ) {
return false;
}
if ( !this.mouseMoved ) {
this.refresh( this._value(), true );
}
},
_controlKeyup: function( event ) { // necessary?
this.refresh( this._value(), true, true );
},
_controlBlur: function( event ) {
this.refresh( this._value(), true );
},
// it appears the clicking the up and down buttons in chrome on
// range/number inputs doesn't trigger a change until the field is
// blurred. Here we check thif the value has changed and refresh
_controlVMouseUp: function( event ) {
this._checkedRefresh();
},
// NOTE force focus on handle
_handleVMouseDown: function( event ) {
this.handle.focus();
},
_handleKeydown: function( event ) {
var index = this._value();
if ( this.options.disabled ) {
return;
}
// In all cases prevent the default and mark the handle as active
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
case $.mobile.keyCode.END:
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
event.preventDefault();
if ( !this._keySliding ) {
this._keySliding = true;
this.handle.addClass( "ui-state-active" );
}
break;
}
// move the slider according to the keypress
switch ( event.keyCode ) {
case $.mobile.keyCode.HOME:
this.refresh( this.min );
break;
case $.mobile.keyCode.END:
this.refresh( this.max );
break;
case $.mobile.keyCode.PAGE_UP:
case $.mobile.keyCode.UP:
case $.mobile.keyCode.RIGHT:
this.refresh( index + this.step );
break;
case $.mobile.keyCode.PAGE_DOWN:
case $.mobile.keyCode.DOWN:
case $.mobile.keyCode.LEFT:
this.refresh( index - this.step );
break;
}
}, // remove active mark
_handleKeyup: function( event ) {
if ( this._keySliding ) {
this._keySliding = false;
this.handle.removeClass( "ui-state-active" );
}
},
_sliderVMouseDown: function( event ) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if ( this.options.disabled || !( event.which === 1 || event.which === 0 ) ) {
return false;
}
if ( this._trigger( "beforestart", event ) === false ) {
return false;
}
this.dragging = true;
this.userModified = false;
this.mouseMoved = false;
if ( this.isToggleSwitch ) {
this.beforeStart = this.element[0].selectedIndex;
}
this.refresh( event );
this._trigger( "start" );
return false;
},
_sliderVMouseUp: function() {
if ( this.dragging ) {
this.dragging = false;
if ( this.isToggleSwitch ) {
// make the handle move with a smooth transition
this.handle.addClass( "ui-slider-handle-snapping" );
if ( this.mouseMoved ) {
// this is a drag, change the value only if user dragged enough
if ( this.userModified ) {
this.refresh( this.beforeStart === 0 ? 1 : 0 );
} else {
this.refresh( this.beforeStart );
}
} else {
// this is just a click, change the value
this.refresh( this.beforeStart === 0 ? 1 : 0 );
}
}
this.mouseMoved = false;
this._trigger( "stop" );
return false;
}
},
_preventDocumentDrag: function( event ) {
// NOTE: we don't do this in refresh because we still want to
// support programmatic alteration of disabled inputs
if ( this._trigger( "drag", event ) === false) {
return false;
}
if ( this.dragging && !this.options.disabled ) {
// this.mouseMoved must be updated before refresh() because it will be used in the control "change" event
this.mouseMoved = true;
if ( this.isToggleSwitch ) {
// make the handle move in sync with the mouse
this.handle.removeClass( "ui-slider-handle-snapping" );
}
this.refresh( event );
// only after refresh() you can calculate this.userModified
this.userModified = this.beforeStart !== this.element[0].selectedIndex;
return false;
}
},
_checkedRefresh: function() {
if ( this.value !== this._value() ) {
this.refresh( this._value() );
}
},
_value: function() {
return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ;
},
_reset: function() {
this.refresh( undefined, false, true );
},
refresh: function( val, isfromControl, preventInputUpdate ) {
// NOTE: we don't return here because we want to support programmatic
// alteration of the input value, which should still update the slider
var self = this,
parentTheme = $.mobile.getInheritedTheme( this.element, "c" ),
theme = this.options.theme || parentTheme,
trackTheme = this.options.trackTheme || parentTheme,
left, width, data, tol;
self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch" : "ui-slider-track"," ui-btn-down-" + trackTheme,' ui-btn-corner-all', ( this.options.mini ) ? " ui-mini":""].join( "" );
if ( this.options.disabled || this.element.attr( "disabled" ) ) {
this.disable();
}
// set the stored value for comparison later
this.value = this._value();
if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) {
this.valuebg = (function() {
var bg = document.createElement( "div" );
bg.className = "ui-slider-bg " + $.mobile.activeBtnClass + " ui-btn-corner-all";
return $( bg ).prependTo( self.slider );
})();
}
this.handle.buttonMarkup({ corners: true, theme: theme, shadow: true });
var pxStep, percent,
control = this.element,
isInput = !this.isToggleSwitch,
optionElements = isInput ? [] : control.find( "option" ),
min = isInput ? parseFloat( control.attr( "min" ) ) : 0,
max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1,
step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1;
if ( typeof val === "object" ) {
data = val;
// a slight tolerance helped get to the ends of the slider
tol = 8;
left = this.slider.offset().left;
width = this.slider.width();
pxStep = width/((max-min)/step);
if ( !this.dragging ||
data.pageX < left - tol ||
data.pageX > left + width + tol ) {
return;
}
if ( pxStep > 1 ) {
percent = ( ( data.pageX - left ) / width ) * 100;
} else {
percent = Math.round( ( ( data.pageX - left ) / width ) * 100 );
}
} else {
if ( val == null ) {
val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex;
}
percent = ( parseFloat( val ) - min ) / ( max - min ) * 100;
}
if ( isNaN( percent ) ) {
return;
}
var newval = ( percent / 100 ) * ( max - min ) + min;
//from jQuery UI slider, the following source will round to the nearest step
var valModStep = ( newval - min ) % step;
var alignValue = newval - valModStep;
if ( Math.abs( valModStep ) * 2 >= step ) {
alignValue += ( valModStep > 0 ) ? step : ( -step );
}
var percentPerStep = 100/((max-min)/step);
// Since JavaScript has problems with large floats, round
// the final value to 5 digits after the decimal point (see jQueryUI: #4124)
newval = parseFloat( alignValue.toFixed(5) );
if ( typeof pxStep === "undefined" ) {
pxStep = width / ( (max-min) / step );
}
if ( pxStep > 1 && isInput ) {
percent = ( newval - min ) * percentPerStep * ( 1 / step );
}
if ( percent < 0 ) {
percent = 0;
}
if ( percent > 100 ) {
percent = 100;
}
if ( newval < min ) {
newval = min;
}
if ( newval > max ) {
newval = max;
}
this.handle.css( "left", percent + "%" );
this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) );
this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() );
if ( this.valuebg ) {
this.valuebg.css( "width", percent + "%" );
}
// drag the label widths
if ( this._labels ) {
var handlePercent = this.handle.width() / this.slider.width() * 100,
aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100,
bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 );
this._labels.each(function() {
var ab = $( this ).is( ".ui-slider-label-a" );
$( this ).width( ( ab ? aPercent : bPercent ) + "%" );
});
}
if ( !preventInputUpdate ) {
var valueChanged = false;
// update control"s value
if ( isInput ) {
valueChanged = control.val() !== newval;
control.val( newval );
} else {
valueChanged = control[ 0 ].selectedIndex !== newval;
control[ 0 ].selectedIndex = newval;
}
if ( this._trigger( "beforechange", val ) === false) {
return false;
}
if ( !isfromControl && valueChanged ) {
control.trigger( "change" );
}
}
},
enable: function() {
this.element.attr( "disabled", false );
this.slider.removeClass( "ui-disabled" ).attr( "aria-disabled", false );
return this._setOption( "disabled", false );
},
disable: function() {
this.element.attr( "disabled", true );
this.slider.addClass( "ui-disabled" ).attr( "aria-disabled", true );
return this._setOption( "disabled", true );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.slider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.rangeslider", $.mobile.widget, {
options: {
theme: null,
trackTheme: null,
disabled: false,
initSelector: ":jqmData(role='rangeslider')",
mini: false,
highlight: true
},
_create: function() {
var secondLabel,
$el = this.element,
elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider",
_inputFirst = $el.find( "input" ).first(),
_inputLast = $el.find( "input" ).last(),
label = $el.find( "label" ).first(),
_sliderFirst = $.data( _inputFirst.get(0), "mobileSlider" ).slider,
_sliderLast = $.data( _inputLast.get(0), "mobileSlider" ).slider,
firstHandle = $.data( _inputFirst.get(0), "mobileSlider" ).handle,
_sliders = $( "<div class=\"ui-rangeslider-sliders\" />" ).appendTo( $el );
if ( $el.find( "label" ).length > 1 ) {
secondLabel = $el.find( "label" ).last().hide();
}
_inputFirst.addClass( "ui-rangeslider-first" );
_inputLast.addClass( "ui-rangeslider-last" );
$el.addClass( elClass );
_sliderFirst.appendTo( _sliders );
_sliderLast.appendTo( _sliders );
label.prependTo( $el );
firstHandle.prependTo( _sliderLast );
$.extend( this, {
_inputFirst: _inputFirst,
_inputLast: _inputLast,
_sliderFirst: _sliderFirst,
_sliderLast: _sliderLast,
_targetVal: null,
_sliderTarget: false,
_sliders: _sliders,
_proxy: false
});
this.refresh();
this._on( this.element.find( "input.ui-slider-input" ), {
"slidebeforestart": "_slidebeforestart",
"slidestop": "_slidestop",
"slidedrag": "_slidedrag",
"slidebeforechange": "_change",
"blur": "_change",
"keyup": "_change"
});
this._on({
"mousedown":"_change"
});
this._on( this.element.closest( "form" ), {
"reset":"_handleReset"
});
this._on( firstHandle, {
"vmousedown": "_dragFirstHandle"
});
},
_handleReset: function(){
var self = this;
//we must wait for the stack to unwind before updateing other wise sliders will not have updated yet
setTimeout( function(){
self._updateHighlight();
},0);
},
_dragFirstHandle: function( event ) {
//if the first handle is dragged send the event to the first slider
$.data( this._inputFirst.get(0), "mobileSlider" ).dragging = true;
$.data( this._inputFirst.get(0), "mobileSlider" ).refresh( event );
return false;
},
_slidedrag: function( event ) {
var first = $( event.target ).is( this._inputFirst ),
otherSlider = ( first ) ? this._inputLast : this._inputFirst;
this._sliderTarget = false;
//if the drag was initiated on an extreme and the other handle is focused send the events to
//the closest handle
if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) {
$.data( otherSlider.get(0), "mobileSlider" ).dragging = true;
$.data( otherSlider.get(0), "mobileSlider" ).refresh( event );
return false;
}
},
_slidestop: function( event ) {
var first = $( event.target ).is( this._inputFirst );
this._proxy = false;
//this stops dragging of the handle and brings the active track to the front
//this makes clicks on the track go the the last handle used
this.element.find( "input" ).trigger( "vmouseup" );
this._sliderFirst.css( "z-index", first ? 1 : "" );
},
_slidebeforestart: function( event ) {
this._sliderTarget = false;
//if the track is the target remember this and the original value
if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) {
this._sliderTarget = true;
this._targetVal = $( event.target ).val();
}
},
_setOption: function( options ) {
this._superApply( options );
this.refresh();
},
refresh: function() {
var $el = this.element,
o = this.options;
$el.find( "input" ).slider({
theme: o.theme,
trackTheme: o.trackTheme,
disabled: o.disabled,
mini: o.mini,
highlight: o.highlight
}).slider( "refresh" );
this._updateHighlight();
},
_change: function( event ) {
if ( event.type === "keyup" ) {
this._updateHighlight();
return false;
}
var self = this,
min = parseFloat( this._inputFirst.val(), 10 ),
max = parseFloat( this._inputLast.val(), 10 ),
first = $( event.target ).hasClass( "ui-rangeslider-first" ),
thisSlider = first ? this._inputFirst : this._inputLast,
otherSlider = first ? this._inputLast : this._inputFirst;
if( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ){
thisSlider.blur();
} else if( event.type === "mousedown" ){
return;
}
if ( min > max && !this._sliderTarget ) {
//this prevents min from being greater then max
thisSlider.val( first ? max: min ).slider( "refresh" );
this._trigger( "normalize" );
} else if ( min > max ) {
//this makes it so clicks on the target on either extreme go to the closest handle
thisSlider.val( this._targetVal ).slider( "refresh" );
//You must wait for the stack to unwind so first slider is updated before updating second
setTimeout( function() {
otherSlider.val( first ? min: max ).slider( "refresh" );
$.data( otherSlider.get(0), "mobileSlider" ).handle.focus();
self._sliderFirst.css( "z-index", first ? "" : 1 );
self._trigger( "normalize" );
}, 0 );
this._proxy = ( first ) ? "first" : "last";
}
//fixes issue where when both _sliders are at min they cannot be adjusted
if ( min === max ) {
$.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", 1 );
$.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", 0 );
} else {
$.data( otherSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
$.data( thisSlider.get(0), "mobileSlider" ).handle.css( "z-index", "" );
}
this._updateHighlight();
if ( min >= max ) {
return false;
}
},
_updateHighlight: function() {
var min = parseInt( $.data( this._inputFirst.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
max = parseInt( $.data( this._inputLast.get(0), "mobileSlider" ).handle.get(0).style.left, 10 ),
width = (max - min);
this.element.find( ".ui-slider-bg" ).css({
"margin-left": min + "%",
"width": width + "%"
});
},
_destroy: function() {
this.element.removeClass( "ui-rangeslider ui-mini" ).find( "label" ).show();
this._inputFirst.after( this._sliderFirst );
this._inputLast.after( this._sliderLast );
this._sliders.remove();
this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" );
}
});
$.widget( "mobile.rangeslider", $.mobile.rangeslider, $.mobile.behaviors.formReset );
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$.mobile.rangeslider.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.selectmenu", $.mobile.widget, $.extend( {
options: {
theme: null,
disabled: false,
icon: "arrow-d",
iconpos: "right",
inline: false,
corners: true,
shadow: true,
iconshadow: true,
overlayTheme: "a",
dividerTheme: "b",
hidePlaceholderMenuItems: true,
closeText: "Close",
nativeMenu: true,
// This option defaults to true on iOS devices.
preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1,
initSelector: "select:not( :jqmData(role='slider') )",
mini: false
},
_button: function() {
return $( "<div/>" );
},
_setDisabled: function( value ) {
this.element.attr( "disabled", value );
this.button.attr( "aria-disabled", value );
return this._setOption( "disabled", value );
},
_focusButton : function() {
var self = this;
setTimeout( function() {
self.button.focus();
}, 40);
},
_selectOptions: function() {
return this.select.find( "option" );
},
// setup items that are generally necessary for select menu extension
_preExtension: function() {
var classes = "";
// TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577
/* if ( $el[0].className.length ) {
classes = $el[0].className;
} */
if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) {
classes = " ui-btn-left";
}
if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) {
classes = " ui-btn-right";
}
this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" );
this.selectID = this.select.attr( "id" );
this.label = $( "label[for='"+ this.selectID +"']" ).addClass( "ui-select" );
this.isMultiple = this.select[ 0 ].multiple;
if ( !this.options.theme ) {
this.options.theme = $.mobile.getInheritedTheme( this.select, "c" );
}
},
_destroy: function() {
var wrapper = this.element.parents( ".ui-select" );
if ( wrapper.length > 0 ) {
if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) {
this.element.addClass( wrapper.is( ".ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" );
}
this.element.insertAfter( wrapper );
wrapper.remove();
}
},
_create: function() {
this._preExtension();
// Allows for extension of the native select for custom selects and other plugins
// see select.custom for example extension
// TODO explore plugin registration
this._trigger( "beforeCreate" );
this.button = this._button();
var self = this,
options = this.options,
inline = options.inline || this.select.jqmData( "inline" ),
mini = options.mini || this.select.jqmData( "mini" ),
iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false,
// IE throws an exception at options.item() function when
// there is no selected item
// select first in this case
selectedIndex = this.select[ 0 ].selectedIndex === -1 ? 0 : this.select[ 0 ].selectedIndex,
// TODO values buttonId and menuId are undefined here
button = this.button
.insertBefore( this.select )
.buttonMarkup( {
theme: options.theme,
icon: options.icon,
iconpos: iconpos,
inline: inline,
corners: options.corners,
shadow: options.shadow,
iconshadow: options.iconshadow,
mini: mini
});
this.setButtonText();
// Opera does not properly support opacity on select elements
// In Mini, it hides the element, but not its text
// On the desktop,it seems to do the opposite
// for these reasons, using the nativeMenu option results in a full native select in Opera
if ( options.nativeMenu && window.opera && window.opera.version ) {
button.addClass( "ui-select-nativeonly" );
}
// Add counter for multi selects
if ( this.isMultiple ) {
this.buttonCount = $( "<span>" )
.addClass( "ui-li-count ui-btn-up-c ui-btn-corner-all" )
.hide()
.appendTo( button.addClass('ui-li-has-count') );
}
// Disable if specified
if ( options.disabled || this.element.attr('disabled')) {
this.disable();
}
// Events on native select
this.select.change(function() {
self.refresh();
if ( !!options.nativeMenu ) {
this.blur();
}
});
this._handleFormReset();
this.build();
},
build: function() {
var self = this;
this.select
.appendTo( self.button )
.bind( "vmousedown", function() {
// Add active class to button
self.button.addClass( $.mobile.activeBtnClass );
})
.bind( "focus", function() {
self.button.addClass( $.mobile.focusClass );
})
.bind( "blur", function() {
self.button.removeClass( $.mobile.focusClass );
})
.bind( "focus vmouseover", function() {
self.button.trigger( "vmouseover" );
})
.bind( "vmousemove", function() {
// Remove active class on scroll/touchmove
self.button.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur vmouseout", function() {
self.button.trigger( "vmouseout" )
.removeClass( $.mobile.activeBtnClass );
})
.bind( "change blur", function() {
self.button.removeClass( "ui-btn-down-" + self.options.theme );
});
// In many situations, iOS will zoom into the select upon tap, this prevents that from happening
self.button.bind( "vmousedown", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.label.bind( "click focus", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.select.bind( "focus", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.disable( true );
}
});
self.button.bind( "mouseup", function() {
if ( self.options.preventFocusZoom ) {
setTimeout(function() {
$.mobile.zoom.enable( true );
}, 0 );
}
});
self.select.bind( "blur", function() {
if ( self.options.preventFocusZoom ) {
$.mobile.zoom.enable( true );
}
});
},
selected: function() {
return this._selectOptions().filter( ":selected" );
},
selectedIndices: function() {
var self = this;
return this.selected().map(function() {
return self._selectOptions().index( this );
}).get();
},
setButtonText: function() {
var self = this,
selected = this.selected(),
text = this.placeholder,
span = $( document.createElement( "span" ) );
this.button.find( ".ui-btn-text" ).html(function() {
if ( selected.length ) {
text = selected.map(function() {
return $( this ).text();
}).get().join( ", " );
} else {
text = self.placeholder;
}
// TODO possibly aggregate multiple select option classes
return span.text( text )
.addClass( self.select.attr( "class" ) )
.addClass( selected.attr( "class" ) );
});
},
setButtonCount: function() {
var selected = this.selected();
// multiple count inside button
if ( this.isMultiple ) {
this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length );
}
},
_reset: function() {
this.refresh();
},
refresh: function() {
this.setButtonText();
this.setButtonCount();
},
// open and close preserved in native selects
// to simplify users code when looping over selects
open: $.noop,
close: $.noop,
disable: function() {
this._setDisabled( true );
this.button.addClass( "ui-disabled" );
},
enable: function() {
this._setDisabled( false );
this.button.removeClass( "ui-disabled" );
}
}, $.mobile.behaviors.formReset ) );
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.selectmenu.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
(function( $, undefined ) {
function fitSegmentInsideSegment( winSize, segSize, offset, desired ) {
var ret = desired;
if ( winSize < segSize ) {
// Center segment if it's bigger than the window
ret = offset + ( winSize - segSize ) / 2;
} else {
// Otherwise center it at the desired coordinate while keeping it completely inside the window
ret = Math.min( Math.max( offset, desired - segSize / 2 ), offset + winSize - segSize );
}
return ret;
}
function windowCoords() {
var $win = $.mobile.window;
return {
x: $win.scrollLeft(),
y: $win.scrollTop(),
cx: ( window.innerWidth || $win.width() ),
cy: ( window.innerHeight || $win.height() )
};
}
$.widget( "mobile.popup", $.mobile.widget, {
options: {
theme: null,
overlayTheme: null,
shadow: true,
corners: true,
transition: "none",
positionTo: "origin",
tolerance: null,
initSelector: ":jqmData(role='popup')",
closeLinkSelector: "a:jqmData(rel='back')",
closeLinkEvents: "click.popup",
navigateEvents: "navigate.popup",
closeEvents: "navigate.popup pagebeforechange.popup",
dismissible: true,
// NOTE Windows Phone 7 has a scroll position caching issue that
// requires us to disable popup history management by default
// https://github.com/jquery/jquery-mobile/issues/4784
//
// NOTE this option is modified in _create!
history: !$.mobile.browser.oldIE
},
_eatEventAndClose: function( e ) {
e.preventDefault();
e.stopImmediatePropagation();
if ( this.options.dismissible ) {
this.close();
}
return false;
},
// Make sure the screen size is increased beyond the page height if the popup's causes the document to increase in height
_resizeScreen: function() {
var popupHeight = this._ui.container.outerHeight( true );
this._ui.screen.removeAttr( "style" );
if ( popupHeight > this._ui.screen.height() ) {
this._ui.screen.height( popupHeight );
}
},
_handleWindowKeyUp: function( e ) {
if ( this._isOpen && e.keyCode === $.mobile.keyCode.ESCAPE ) {
return this._eatEventAndClose( e );
}
},
_expectResizeEvent: function() {
var winCoords = windowCoords();
if ( this._resizeData ) {
if ( winCoords.x === this._resizeData.winCoords.x &&
winCoords.y === this._resizeData.winCoords.y &&
winCoords.cx === this._resizeData.winCoords.cx &&
winCoords.cy === this._resizeData.winCoords.cy ) {
// timeout not refreshed
return false;
} else {
// clear existing timeout - it will be refreshed below
clearTimeout( this._resizeData.timeoutId );
}
}
this._resizeData = {
timeoutId: setTimeout( $.proxy( this, "_resizeTimeout" ), 200 ),
winCoords: winCoords
};
return true;
},
_resizeTimeout: function() {
if ( this._isOpen ) {
if ( !this._expectResizeEvent() ) {
if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-open the popup while leaving the screen intact
this._ui.container.removeClass( "ui-popup-hidden" );
this.reposition( { positionTo: "window" } );
this._ignoreResizeEvents();
}
this._resizeScreen();
this._resizeData = null;
this._orientationchangeInProgress = false;
}
} else {
this._resizeData = null;
this._orientationchangeInProgress = false;
}
},
_ignoreResizeEvents: function() {
var self = this;
if ( this._ignoreResizeTo ) {
clearTimeout( this._ignoreResizeTo );
}
this._ignoreResizeTo = setTimeout( function() { self._ignoreResizeTo = 0; }, 1000 );
},
_handleWindowResize: function( e ) {
if ( this._isOpen && this._ignoreResizeTo === 0 ) {
if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) &&
!this._ui.container.hasClass( "ui-popup-hidden" ) ) {
// effectively rapid-close the popup while leaving the screen intact
this._ui.container
.addClass( "ui-popup-hidden" )
.removeAttr( "style" );
}
}
},
_handleWindowOrientationchange: function( e ) {
if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) {
this._expectResizeEvent();
this._orientationchangeInProgress = true;
}
},
// When the popup is open, attempting to focus on an element that is not a
// child of the popup will redirect focus to the popup
_handleDocumentFocusIn: function( e ) {
var tgt = e.target, $tgt, ui = this._ui;
if ( !this._isOpen ) {
return;
}
if ( tgt !== ui.container[ 0 ] ) {
$tgt = $( e.target );
if ( 0 === $tgt.parents().filter( ui.container[ 0 ] ).length ) {
$( document.activeElement ).one( "focus", function( e ) {
$tgt.blur();
});
ui.focusElement.focus();
e.preventDefault();
e.stopImmediatePropagation();
return false;
} else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) {
ui.focusElement = $tgt;
}
}
this._ignoreResizeEvents();
},
_create: function() {
var ui = {
screen: $( "<div class='ui-screen-hidden ui-popup-screen'></div>" ),
placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ),
container: $( "<div class='ui-popup-container ui-popup-hidden'></div>" )
},
thisPage = this.element.closest( ".ui-page" ),
myId = this.element.attr( "id" ),
self = this;
// We need to adjust the history option to be false if there's no AJAX nav.
// We can't do it in the option declarations because those are run before
// it is determined whether there shall be AJAX nav.
this.options.history = this.options.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled;
if ( thisPage.length === 0 ) {
thisPage = $( "body" );
}
// define the container for navigation event bindings
// TODO this would be nice at the the mobile widget level
this.options.container = this.options.container || $.mobile.pageContainer;
// Apply the proto
thisPage.append( ui.screen );
ui.container.insertAfter( ui.screen );
// Leave a placeholder where the element used to be
ui.placeholder.insertAfter( this.element );
if ( myId ) {
ui.screen.attr( "id", myId + "-screen" );
ui.container.attr( "id", myId + "-popup" );
ui.placeholder.html( "<!-- placeholder for " + myId + " -->" );
}
ui.container.append( this.element );
ui.focusElement = ui.container;
// Add class to popup element
this.element.addClass( "ui-popup" );
// Define instance variables
$.extend( this, {
_scrollTop: 0,
_page: thisPage,
_ui: ui,
_fallbackTransition: "",
_currentTransition: false,
_prereqs: null,
_isOpen: false,
_tolerance: null,
_resizeData: null,
_ignoreResizeTo: 0,
_orientationchangeInProgress: false
});
$.each( this.options, function( key, value ) {
// Cause initial options to be applied by their handler by temporarily setting the option to undefined
// - the handler then sets it to the initial value
self.options[ key ] = undefined;
self._setOption( key, value, true );
});
ui.screen.bind( "vclick", $.proxy( this, "_eatEventAndClose" ) );
this._on( $.mobile.window, {
orientationchange: $.proxy( this, "_handleWindowOrientationchange" ),
resize: $.proxy( this, "_handleWindowResize" ),
keyup: $.proxy( this, "_handleWindowKeyUp" )
});
this._on( $.mobile.document, {
focusin: $.proxy( this, "_handleDocumentFocusIn" )
});
},
_applyTheme: function( dst, theme, prefix ) {
var classes = ( dst.attr( "class" ) || "").split( " " ),
alreadyAdded = true,
currentTheme = null,
matches,
themeStr = String( theme );
while ( classes.length > 0 ) {
currentTheme = classes.pop();
matches = ( new RegExp( "^ui-" + prefix + "-([a-z])$" ) ).exec( currentTheme );
if ( matches && matches.length > 1 ) {
currentTheme = matches[ 1 ];
break;
} else {
currentTheme = null;
}
}
if ( theme !== currentTheme ) {
dst.removeClass( "ui-" + prefix + "-" + currentTheme );
if ( ! ( theme === null || theme === "none" ) ) {
dst.addClass( "ui-" + prefix + "-" + themeStr );
}
}
},
_setTheme: function( value ) {
this._applyTheme( this.element, value, "body" );
},
_setOverlayTheme: function( value ) {
this._applyTheme( this._ui.screen, value, "overlay" );
if ( this._isOpen ) {
this._ui.screen.addClass( "in" );
}
},
_setShadow: function( value ) {
this.element.toggleClass( "ui-overlay-shadow", value );
},
_setCorners: function( value ) {
this.element.toggleClass( "ui-corner-all", value );
},
_applyTransition: function( value ) {
this._ui.container.removeClass( this._fallbackTransition );
if ( value && value !== "none" ) {
this._fallbackTransition = $.mobile._maybeDegradeTransition( value );
if ( this._fallbackTransition === "none" ) {
this._fallbackTransition = "";
}
this._ui.container.addClass( this._fallbackTransition );
}
},
_setTransition: function( value ) {
if ( !this._currentTransition ) {
this._applyTransition( value );
}
},
_setTolerance: function( value ) {
var tol = { t: 30, r: 15, b: 30, l: 15 };
if ( value !== undefined ) {
var ar = String( value ).split( "," );
$.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } );
switch( ar.length ) {
// All values are to be the same
case 1:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.r = tol.b = tol.l = ar[ 0 ];
}
break;
// The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance
case 2:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = tol.b = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.l = tol.r = ar[ 1 ];
}
break;
// The array contains values in the order top, right, bottom, left
case 4:
if ( !isNaN( ar[ 0 ] ) ) {
tol.t = ar[ 0 ];
}
if ( !isNaN( ar[ 1 ] ) ) {
tol.r = ar[ 1 ];
}
if ( !isNaN( ar[ 2 ] ) ) {
tol.b = ar[ 2 ];
}
if ( !isNaN( ar[ 3 ] ) ) {
tol.l = ar[ 3 ];
}
break;
default:
break;
}
}
this._tolerance = tol;
},
_setOption: function( key, value ) {
var exclusions, setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
if ( this[ setter ] !== undefined ) {
this[ setter ]( value );
}
// TODO REMOVE FOR 1.2.1 by moving them out to a default options object
exclusions = [
"initSelector",
"closeLinkSelector",
"closeLinkEvents",
"navigateEvents",
"closeEvents",
"history",
"container"
];
$.mobile.widget.prototype._setOption.apply( this, arguments );
if ( $.inArray( key, exclusions ) === -1 ) {
// Record the option change in the options and in the DOM data-* attributes
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
}
},
// Try and center the overlay over the given coordinates
_placementCoords: function( desired ) {
// rectangle within which the popup must fit
var
winCoords = windowCoords(),
rc = {
x: this._tolerance.l,
y: winCoords.y + this._tolerance.t,
cx: winCoords.cx - this._tolerance.l - this._tolerance.r,
cy: winCoords.cy - this._tolerance.t - this._tolerance.b
},
menuSize, ret;
// Clamp the width of the menu before grabbing its size
this._ui.container.css( "max-width", rc.cx );
menuSize = {
cx: this._ui.container.outerWidth( true ),
cy: this._ui.container.outerHeight( true )
};
// Center the menu over the desired coordinates, while not going outside
// the window tolerances. This will center wrt. the window if the popup is too large.
ret = {
x: fitSegmentInsideSegment( rc.cx, menuSize.cx, rc.x, desired.x ),
y: fitSegmentInsideSegment( rc.cy, menuSize.cy, rc.y, desired.y )
};
// Make sure the top of the menu is visible
ret.y = Math.max( 0, ret.y );
// If the height of the menu is smaller than the height of the document
// align the bottom with the bottom of the document
// fix for $.mobile.document.height() bug in core 1.7.2.
var docEl = document.documentElement, docBody = document.body,
docHeight = Math.max( docEl.clientHeight, docBody.scrollHeight, docBody.offsetHeight, docEl.scrollHeight, docEl.offsetHeight );
ret.y -= Math.min( ret.y, Math.max( 0, ret.y + menuSize.cy - docHeight ) );
return { left: ret.x, top: ret.y };
},
_createPrereqs: function( screenPrereq, containerPrereq, whenDone ) {
var self = this, prereqs;
// It is important to maintain both the local variable prereqs and self._prereqs. The local variable remains in
// the closure of the functions which call the callbacks passed in. The comparison between the local variable and
// self._prereqs is necessary, because once a function has been passed to .animationComplete() it will be called
// next time an animation completes, even if that's not the animation whose end the function was supposed to catch
// (for example, if an abort happens during the opening animation, the .animationComplete handler is not called for
// that animation anymore, but the handler remains attached, so it is called the next time the popup is opened
// - making it stale. Comparing the local variable prereqs to the widget-level variable self._prereqs ensures that
// callbacks triggered by a stale .animationComplete will be ignored.
prereqs = {
screen: $.Deferred(),
container: $.Deferred()
};
prereqs.screen.then( function() {
if ( prereqs === self._prereqs ) {
screenPrereq();
}
});
prereqs.container.then( function() {
if ( prereqs === self._prereqs ) {
containerPrereq();
}
});
$.when( prereqs.screen, prereqs.container ).done( function() {
if ( prereqs === self._prereqs ) {
self._prereqs = null;
whenDone();
}
});
self._prereqs = prereqs;
},
_animate: function( args ) {
// NOTE before removing the default animation of the screen
// this had an animate callback that would resolve the deferred
// now the deferred is resolved immediately
// TODO remove the dependency on the screen deferred
this._ui.screen
.removeClass( args.classToRemove )
.addClass( args.screenClassToAdd );
args.prereqs.screen.resolve();
if ( args.transition && args.transition !== "none" ) {
if ( args.applyTransition ) {
this._applyTransition( args.transition );
}
if ( this._fallbackTransition ) {
this._ui.container
.animationComplete( $.proxy( args.prereqs.container, "resolve" ) )
.addClass( args.containerClassToAdd )
.removeClass( args.classToRemove );
return;
}
}
this._ui.container.removeClass( args.classToRemove );
args.prereqs.container.resolve();
},
// The desired coordinates passed in will be returned untouched if no reference element can be identified via
// desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid
// x and y coordinates by specifying the center middle of the window if the coordinates are absent.
// options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector
_desiredCoords: function( o ) {
var dst = null, offset, winCoords = windowCoords(), x = o.x, y = o.y, pTo = o.positionTo;
// Establish which element will serve as the reference
if ( pTo && pTo !== "origin" ) {
if ( pTo === "window" ) {
x = winCoords.cx / 2 + winCoords.x;
y = winCoords.cy / 2 + winCoords.y;
} else {
try {
dst = $( pTo );
} catch( e ) {
dst = null;
}
if ( dst ) {
dst.filter( ":visible" );
if ( dst.length === 0 ) {
dst = null;
}
}
}
}
// If an element was found, center over it
if ( dst ) {
offset = dst.offset();
x = offset.left + dst.outerWidth() / 2;
y = offset.top + dst.outerHeight() / 2;
}
// Make sure x and y are valid numbers - center over the window
if ( $.type( x ) !== "number" || isNaN( x ) ) {
x = winCoords.cx / 2 + winCoords.x;
}
if ( $.type( y ) !== "number" || isNaN( y ) ) {
y = winCoords.cy / 2 + winCoords.y;
}
return { x: x, y: y };
},
_reposition: function( o ) {
// We only care about position-related parameters for repositioning
o = { x: o.x, y: o.y, positionTo: o.positionTo };
this._trigger( "beforeposition", o );
this._ui.container.offset( this._placementCoords( this._desiredCoords( o ) ) );
},
reposition: function( o ) {
if ( this._isOpen ) {
this._reposition( o );
}
},
_openPrereqsComplete: function() {
this._ui.container.addClass( "ui-popup-active" );
this._isOpen = true;
this._resizeScreen();
this._ui.container.attr( "tabindex", "0" ).focus();
this._ignoreResizeEvents();
this._trigger( "afteropen" );
},
_open: function( options ) {
var o = $.extend( {}, this.options, options ),
// TODO move blacklist to private method
androidBlacklist = ( function() {
var w = window,
ua = navigator.userAgent,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ),
andversion = !!androidmatch && androidmatch[ 1 ],
chromematch = ua.indexOf( "Chrome" ) > -1;
// Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome.
if( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) {
return true;
}
return false;
}());
// Count down to triggering "popupafteropen" - we have two prerequisites:
// 1. The popup window animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.noop,
$.noop,
$.proxy( this, "_openPrereqsComplete" ) );
this._currentTransition = o.transition;
this._applyTransition( o.transition );
if ( !this.options.theme ) {
this._setTheme( this._page.jqmData( "theme" ) || $.mobile.getInheritedTheme( this._page, "c" ) );
}
this._ui.screen.removeClass( "ui-screen-hidden" );
this._ui.container.removeClass( "ui-popup-hidden" );
// Give applications a chance to modify the contents of the container before it appears
this._reposition( o );
if ( this.options.overlayTheme && androidBlacklist ) {
/* TODO:
The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed
above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain
types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser:
https://github.com/scottjehl/Device-Bugs/issues/3
This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ):
https://github.com/jquery/jquery-mobile/issues/4816
https://github.com/jquery/jquery-mobile/issues/4844
https://github.com/jquery/jquery-mobile/issues/4874
*/
// TODO sort out why this._page isn't working
this.element.closest( ".ui-page" ).addClass( "ui-popup-open" );
}
this._animate({
additionalCondition: true,
transition: o.transition,
classToRemove: "",
screenClassToAdd: "in",
containerClassToAdd: "in",
applyTransition: false,
prereqs: this._prereqs
});
},
_closePrereqScreen: function() {
this._ui.screen
.removeClass( "out" )
.addClass( "ui-screen-hidden" );
},
_closePrereqContainer: function() {
this._ui.container
.removeClass( "reverse out" )
.addClass( "ui-popup-hidden" )
.removeAttr( "style" );
},
_closePrereqsDone: function() {
var opts = this.options;
this._ui.container.removeAttr( "tabindex" );
// remove the global mutex for popups
$.mobile.popup.active = undefined;
// alert users that the popup is closed
this._trigger( "afterclose" );
},
_close: function( immediate ) {
this._ui.container.removeClass( "ui-popup-active" );
this._page.removeClass( "ui-popup-open" );
this._isOpen = false;
// Count down to triggering "popupafterclose" - we have two prerequisites:
// 1. The popup window reverse animation completes (container())
// 2. The screen opacity animation completes (screen())
this._createPrereqs(
$.proxy( this, "_closePrereqScreen" ),
$.proxy( this, "_closePrereqContainer" ),
$.proxy( this, "_closePrereqsDone" ) );
this._animate( {
additionalCondition: this._ui.screen.hasClass( "in" ),
transition: ( immediate ? "none" : ( this._currentTransition ) ),
classToRemove: "in",
screenClassToAdd: "out",
containerClassToAdd: "reverse out",
applyTransition: true,
prereqs: this._prereqs
});
},
_unenhance: function() {
// Put the element back to where the placeholder was and remove the "ui-popup" class
this._setTheme( "none" );
this.element
// Cannot directly insertAfter() - we need to detach() first, because
// insertAfter() will do nothing if the payload div was not attached
// to the DOM at the time the widget was created, and so the payload
// will remain inside the container even after we call insertAfter().
// If that happens and we remove the container a few lines below, we
// will cause an infinite recursion - #5244
.detach()
.insertAfter( this._ui.placeholder )
.removeClass( "ui-popup ui-overlay-shadow ui-corner-all" );
this._ui.screen.remove();
this._ui.container.remove();
this._ui.placeholder.remove();
},
_destroy: function() {
if ( $.mobile.popup.active === this ) {
this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) );
this.close();
} else {
this._unenhance();
}
},
_closePopup: function( e, data ) {
var parsedDst, toUrl, o = this.options, immediate = false;
// restore location on screen
window.scrollTo( 0, this._scrollTop );
if ( e && e.type === "pagebeforechange" && data ) {
// Determine whether we need to rapid-close the popup, or whether we can
// take the time to run the closing transition
if ( typeof data.toPage === "string" ) {
parsedDst = data.toPage;
} else {
parsedDst = data.toPage.jqmData( "url" );
}
parsedDst = $.mobile.path.parseUrl( parsedDst );
toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash;
if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) {
// Going to a different page - close immediately
immediate = true;
} else {
e.preventDefault();
}
}
// remove nav bindings
o.container.unbind( o.closeEvents );
// unbind click handlers added when history is disabled
this.element.undelegate( o.closeLinkSelector, o.closeLinkEvents );
this._close( immediate );
},
// any navigation event after a popup is opened should close the popup
// NOTE the pagebeforechange is bound to catch navigation events that don't
// alter the url (eg, dialogs from popups)
_bindContainerClose: function() {
this.options.container
.one( this.options.closeEvents, $.proxy( this, "_closePopup" ) );
},
// TODO no clear deliniation of what should be here and
// what should be in _open. Seems to be "visual" vs "history" for now
open: function( options ) {
var self = this, opts = this.options, url, hashkey, activePage, currentIsDialog, hasHash, urlHistory;
// make sure open is idempotent
if( $.mobile.popup.active ) {
return;
}
// set the global popup mutex
$.mobile.popup.active = this;
this._scrollTop = $.mobile.window.scrollTop();
// if history alteration is disabled close on navigate events
// and leave the url as is
if( !( opts.history ) ) {
self._open( options );
self._bindContainerClose();
// When histoy is disabled we have to grab the data-rel
// back link clicks so we can close the popup instead of
// relying on history to do it for us
self.element
.delegate( opts.closeLinkSelector, opts.closeLinkEvents, function( e ) {
self.close();
e.preventDefault();
});
return;
}
// cache some values for min/readability
urlHistory = $.mobile.urlHistory;
hashkey = $.mobile.dialogHashKey;
activePage = $.mobile.activePage;
currentIsDialog = activePage.is( ".ui-dialog" );
this._myUrl = url = urlHistory.getActive().url;
hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 );
if ( hasHash ) {
self._open( options );
self._bindContainerClose();
return;
}
// if the current url has no dialog hash key proceed as normal
// otherwise, if the page is a dialog simply tack on the hash key
if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ){
url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey);
} else {
url = $.mobile.path.parseLocation().hash + hashkey;
}
// Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash
if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) {
url += hashkey;
}
// swallow the the initial navigation event, and bind for the next
$(window).one( "beforenavigate", function( e ) {
e.preventDefault();
self._open( options );
self._bindContainerClose();
});
this.urlAltered = true;
$.mobile.navigate( url, {role: "dialog"} );
},
close: function() {
// make sure close is idempotent
if( $.mobile.popup.active !== this ) {
return;
}
this._scrollTop = $.mobile.window.scrollTop();
if( this.options.history && this.urlAltered ) {
$.mobile.back();
this.urlAltered = false;
} else {
// simulate the nav bindings having fired
this._closePopup();
}
}
});
// TODO this can be moved inside the widget
$.mobile.popup.handleLink = function( $link ) {
var closestPage = $link.closest( ":jqmData(role='page')" ),
scope = ( ( closestPage.length === 0 ) ? $( "body" ) : closestPage ),
// NOTE make sure to get only the hash, ie7 (wp7) return the absolute href
// in this case ruining the element selection
popup = $( $.mobile.path.parseUrl($link.attr( "href" )).hash, scope[0] ),
offset;
if ( popup.data( "mobile-popup" ) ) {
offset = $link.offset();
popup.popup( "open", {
x: offset.left + $link.outerWidth() / 2,
y: offset.top + $link.outerHeight() / 2,
transition: $link.jqmData( "transition" ),
positionTo: $link.jqmData( "position-to" )
});
}
//remove after delay
setTimeout( function() {
// Check if we are in a listview
var $parent = $link.parent().parent();
if ($parent.hasClass("ui-li")) {
$link = $parent.parent();
}
$link.removeClass( $.mobile.activeBtnClass );
}, 300 );
};
// TODO move inside _create
$.mobile.document.bind( "pagebeforechange", function( e, data ) {
if ( data.options.role === "popup" ) {
$.mobile.popup.handleLink( data.options.link );
e.preventDefault();
}
});
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.popup.prototype.enhanceWithin( e.target, true );
});
})( jQuery );
/*
* custom "selectmenu" plugin
*/
(function( $, undefined ) {
var extendSelect = function( widget ) {
var select = widget.select,
origDestroy = widget._destroy,
selectID = widget.selectID,
prefix = ( selectID ? selectID : ( ( $.mobile.ns || "" ) + "uuid-" + widget.uuid ) ),
popupID = prefix + "-listbox",
dialogID = prefix + "-dialog",
label = widget.label,
thisPage = widget.select.closest( ".ui-page" ),
selectOptions = widget._selectOptions(),
isMultiple = widget.isMultiple = widget.select[ 0 ].multiple,
buttonId = selectID + "-button",
menuId = selectID + "-menu",
menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' id='" + dialogID + "' data-" +$.mobile.ns + "theme='"+ widget.options.theme +"' data-" +$.mobile.ns + "overlay-theme='"+ widget.options.overlayTheme +"'>" +
"<div data-" + $.mobile.ns + "role='header'>" +
"<div class='ui-title'>" + label.getEncodedText() + "</div>"+
"</div>"+
"<div data-" + $.mobile.ns + "role='content'></div>"+
"</div>" ),
listbox = $( "<div id='" + popupID + "' class='ui-selectmenu'>" ).insertAfter( widget.select ).popup( { theme: widget.options.overlayTheme } ),
list = $( "<ul>", {
"class": "ui-selectmenu-list",
"id": menuId,
"role": "listbox",
"aria-labelledby": buttonId
}).attr( "data-" + $.mobile.ns + "theme", widget.options.theme )
.attr( "data-" + $.mobile.ns + "divider-theme", widget.options.dividerTheme )
.appendTo( listbox ),
header = $( "<div>", {
"class": "ui-header ui-bar-" + widget.options.theme
}).prependTo( listbox ),
headerTitle = $( "<h1>", {
"class": "ui-title"
}).appendTo( header ),
menuPageContent,
menuPageClose,
headerClose;
if ( widget.isMultiple ) {
headerClose = $( "<a>", {
"text": widget.options.closeText,
"href": "#",
"class": "ui-btn-left"
}).attr( "data-" + $.mobile.ns + "iconpos", "notext" ).attr( "data-" + $.mobile.ns + "icon", "delete" ).appendTo( header ).buttonMarkup();
}
$.extend( widget, {
select: widget.select,
selectID: selectID,
buttonId: buttonId,
menuId: menuId,
popupID: popupID,
dialogID: dialogID,
thisPage: thisPage,
menuPage: menuPage,
label: label,
selectOptions: selectOptions,
isMultiple: isMultiple,
theme: widget.options.theme,
listbox: listbox,
list: list,
header: header,
headerTitle: headerTitle,
headerClose: headerClose,
menuPageContent: menuPageContent,
menuPageClose: menuPageClose,
placeholder: "",
build: function() {
var self = this;
// Create list from select, update state
self.refresh();
if ( self._origTabIndex === undefined ) {
// Map undefined to false, because self._origTabIndex === undefined
// indicates that we have not yet checked whether the select has
// originally had a tabindex attribute, whereas false indicates that
// we have checked the select for such an attribute, and have found
// none present.
self._origTabIndex = ( self.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : self.select.attr( "tabindex" );
}
self.select.attr( "tabindex", "-1" ).focus(function() {
$( this ).blur();
self.button.focus();
});
// Button events
self.button.bind( "vclick keydown" , function( event ) {
if ( self.options.disabled || self.isOpen ) {
return;
}
if (event.type === "vclick" ||
event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER ||
event.keyCode === $.mobile.keyCode.SPACE)) {
self._decideFormat();
if ( self.menuType === "overlay" ) {
self.button.attr( "href", "#" + self.popupID ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" );
} else {
self.button.attr( "href", "#" + self.dialogID ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" );
}
self.isOpen = true;
// Do not prevent default, so the navigation may have a chance to actually open the chosen format
}
});
// Events for list items
self.list.attr( "role", "listbox" )
.bind( "focusin", function( e ) {
$( e.target )
.attr( "tabindex", "0" )
.trigger( "vmouseover" );
})
.bind( "focusout", function( e ) {
$( e.target )
.attr( "tabindex", "-1" )
.trigger( "vmouseout" );
})
.delegate( "li:not(.ui-disabled, .ui-li-divider)", "click", function( event ) {
// index of option tag to be selected
var oldIndex = self.select[ 0 ].selectedIndex,
newIndex = self.list.find( "li:not(.ui-li-divider)" ).index( this ),
option = self._selectOptions().eq( newIndex )[ 0 ];
// toggle selected status on the tag for multi selects
option.selected = self.isMultiple ? !option.selected : true;
// toggle checkbox class for multiple selects
if ( self.isMultiple ) {
$( this ).find( ".ui-icon" )
.toggleClass( "ui-icon-checkbox-on", option.selected )
.toggleClass( "ui-icon-checkbox-off", !option.selected );
}
// trigger change if value changed
if ( self.isMultiple || oldIndex !== newIndex ) {
self.select.trigger( "change" );
}
// hide custom select for single selects only - otherwise focus clicked item
// We need to grab the clicked item the hard way, because the list may have been rebuilt
if ( self.isMultiple ) {
self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex )
.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
else {
self.close();
}
event.preventDefault();
})
.keydown(function( event ) { //keyboard events for menu items
var target = $( event.target ),
li = target.closest( "li" ),
prev, next;
// switch logic based on which key was pressed
switch ( event.keyCode ) {
// up or left arrow keys
case 38:
prev = li.prev().not( ".ui-selectmenu-placeholder" );
if ( prev.is( ".ui-li-divider" ) ) {
prev = prev.prev();
}
// if there's a previous option, focus it
if ( prev.length ) {
target
.blur()
.attr( "tabindex", "-1" );
prev.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
// down or right arrow keys
case 40:
next = li.next();
if ( next.is( ".ui-li-divider" ) ) {
next = next.next();
}
// if there's a next option, focus it
if ( next.length ) {
target
.blur()
.attr( "tabindex", "-1" );
next.addClass( "ui-btn-down-" + widget.options.theme ).find( "a" ).first().focus();
}
return false;
// If enter or space is pressed, trigger click
case 13:
case 32:
target.trigger( "click" );
return false;
}
});
// button refocus ensures proper height calculation
// by removing the inline style and ensuring page inclusion
self.menuPage.bind( "pagehide", function() {
// TODO centralize page removal binding / handling in the page plugin.
// Suggestion from @jblas to do refcounting
//
// TODO extremely confusing dependency on the open method where the pagehide.remove
// bindings are stripped to prevent the parent page from disappearing. The way
// we're keeping pages in the DOM right now sucks
//
// rebind the page remove that was unbound in the open function
// to allow for the parent page removal from actions other than the use
// of a dialog sized custom select
//
// doing this here provides for the back button on the custom select dialog
$.mobile._bindPageRemove.call( self.thisPage );
});
// Events on the popup
self.listbox.bind( "popupafterclose", function( event ) {
self.close();
});
// Close button on small overlays
if ( self.isMultiple ) {
self.headerClose.click(function() {
if ( self.menuType === "overlay" ) {
self.close();
return false;
}
});
}
// track this dependency so that when the parent page
// is removed on pagehide it will also remove the menupage
self.thisPage.addDependents( this.menuPage );
},
_isRebuildRequired: function() {
var list = this.list.find( "li" ),
options = this._selectOptions();
// TODO exceedingly naive method to determine difference
// ignores value changes etc in favor of a forcedRebuild
// from the user in the refresh method
return options.text() !== list.text();
},
selected: function() {
return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" );
},
refresh: function( forceRebuild , foo ) {
var self = this,
select = this.element,
isMultiple = this.isMultiple,
indicies;
if ( forceRebuild || this._isRebuildRequired() ) {
self._buildList();
}
indicies = this.selectedIndices();
self.setButtonText();
self.setButtonCount();
self.list.find( "li:not(.ui-li-divider)" )
.removeClass( $.mobile.activeBtnClass )
.attr( "aria-selected", false )
.each(function( i ) {
if ( $.inArray( i, indicies ) > -1 ) {
var item = $( this );
// Aria selected attr
item.attr( "aria-selected", true );
// Multiple selects: add the "on" checkbox state to the icon
if ( self.isMultiple ) {
item.find( ".ui-icon" ).removeClass( "ui-icon-checkbox-off" ).addClass( "ui-icon-checkbox-on" );
} else {
if ( item.is( ".ui-selectmenu-placeholder" ) ) {
item.next().addClass( $.mobile.activeBtnClass );
} else {
item.addClass( $.mobile.activeBtnClass );
}
}
}
});
},
close: function() {
if ( this.options.disabled || !this.isOpen ) {
return;
}
var self = this;
if ( self.menuType === "page" ) {
self.menuPage.dialog( "close" );
self.list.appendTo( self.listbox );
} else {
self.listbox.popup( "close" );
}
self._focusButton();
// allow the dialog to be closed again
self.isOpen = false;
},
open: function() {
this.button.click();
},
_decideFormat: function() {
var self = this,
$window = $.mobile.window,
selfListParent = self.list.parent(),
menuHeight = selfListParent.outerHeight(),
menuWidth = selfListParent.outerWidth(),
activePage = $( "." + $.mobile.activePageClass ),
scrollTop = $window.scrollTop(),
btnOffset = self.button.offset().top,
screenHeight = $window.height(),
screenWidth = $window.width();
function focusMenuItem() {
var selector = self.list.find( "." + $.mobile.activeBtnClass + " a" );
if ( selector.length === 0 ) {
selector = self.list.find( "li.ui-btn:not( :jqmData(placeholder='true') ) a" );
}
selector.first().focus().closest( "li" ).addClass( "ui-btn-down-" + widget.options.theme );
}
if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) {
self.menuPage.appendTo( $.mobile.pageContainer ).page();
self.menuPageContent = menuPage.find( ".ui-content" );
self.menuPageClose = menuPage.find( ".ui-header a" );
// prevent the parent page from being removed from the DOM,
// otherwise the results of selecting a list item in the dialog
// fall into a black hole
self.thisPage.unbind( "pagehide.remove" );
//for WebOS/Opera Mini (set lastscroll using button offset)
if ( scrollTop === 0 && btnOffset > screenHeight ) {
self.thisPage.one( "pagehide", function() {
$( this ).jqmData( "lastScroll", btnOffset );
});
}
self.menuPage
.one( "pageshow", function() {
focusMenuItem();
})
.one( "pagehide", function() {
self.close();
});
self.menuType = "page";
self.menuPageContent.append( self.list );
self.menuPage.find("div .ui-title").text(self.label.text());
} else {
self.menuType = "overlay";
self.listbox.one( "popupafteropen", focusMenuItem );
}
},
_buildList: function() {
var self = this,
o = this.options,
placeholder = this.placeholder,
needPlaceholder = true,
optgroups = [],
lis = [],
dataIcon = self.isMultiple ? "checkbox-off" : "false";
self.list.empty().filter( ".ui-listview" ).listview( "destroy" );
var $options = self.select.find( "option" ),
numOptions = $options.length,
select = this.select[ 0 ],
dataPrefix = 'data-' + $.mobile.ns,
dataIndexAttr = dataPrefix + 'option-index',
dataIconAttr = dataPrefix + 'icon',
dataRoleAttr = dataPrefix + 'role',
dataPlaceholderAttr = dataPrefix + 'placeholder',
fragment = document.createDocumentFragment(),
isPlaceholderItem = false,
optGroup;
for (var i = 0; i < numOptions;i++, isPlaceholderItem = false) {
var option = $options[i],
$option = $( option ),
parent = option.parentNode,
text = $option.text(),
anchor = document.createElement( 'a' ),
classes = [];
anchor.setAttribute( 'href', '#' );
anchor.appendChild( document.createTextNode( text ) );
// Are we inside an optgroup?
if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) {
var optLabel = parent.getAttribute( 'label' );
if ( optLabel !== optGroup ) {
var divider = document.createElement( 'li' );
divider.setAttribute( dataRoleAttr, 'list-divider' );
divider.setAttribute( 'role', 'option' );
divider.setAttribute( 'tabindex', '-1' );
divider.appendChild( document.createTextNode( optLabel ) );
fragment.appendChild( divider );
optGroup = optLabel;
}
}
if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) {
needPlaceholder = false;
isPlaceholderItem = true;
// If we have identified a placeholder, record the fact that it was
// us who have added the placeholder to the option and mark it
// retroactively in the select as well
if ( null === option.getAttribute( dataPlaceholderAttr ) ) {
this._removePlaceholderAttr = true;
}
option.setAttribute( dataPlaceholderAttr, true );
if ( o.hidePlaceholderMenuItems ) {
classes.push( "ui-selectmenu-placeholder" );
}
if ( placeholder !== text ) {
placeholder = self.placeholder = text;
}
}
var item = document.createElement('li');
if ( option.disabled ) {
classes.push( "ui-disabled" );
item.setAttribute('aria-disabled',true);
}
item.setAttribute( dataIndexAttr,i );
item.setAttribute( dataIconAttr, dataIcon );
if ( isPlaceholderItem ) {
item.setAttribute( dataPlaceholderAttr, true );
}
item.className = classes.join( " " );
item.setAttribute( 'role', 'option' );
anchor.setAttribute( 'tabindex', '-1' );
item.appendChild( anchor );
fragment.appendChild( item );
}
self.list[0].appendChild( fragment );
// Hide header if it's not a multiselect and there's no placeholder
if ( !this.isMultiple && !placeholder.length ) {
this.header.hide();
} else {
this.headerTitle.text( this.placeholder );
}
// Now populated, create listview
self.list.listview();
},
_button: function() {
return $( "<a>", {
"href": "#",
"role": "button",
// TODO value is undefined at creation
"id": this.buttonId,
"aria-haspopup": "true",
// TODO value is undefined at creation
"aria-owns": this.menuId
});
},
_destroy: function() {
this.close();
// Restore the tabindex attribute to its original value
if ( this._origTabIndex !== undefined ) {
if ( this._origTabIndex !== false ) {
this.select.attr( "tabindex", this._origTabIndex );
} else {
this.select.removeAttr( "tabindex" );
}
}
// Remove the placeholder attribute if we were the ones to add it
if ( this._removePlaceholderAttr ) {
this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" );
}
// Remove the popup
this.listbox.remove();
// Chain up
origDestroy.apply( this, arguments );
}
});
};
// issue #3894 - core doesn't trigger events on disabled delegates
$.mobile.document.bind( "selectmenubeforecreate", function( event ) {
var selectmenuWidget = $( event.target ).data( "mobile-selectmenu" );
if ( !selectmenuWidget.options.nativeMenu &&
selectmenuWidget.element.parents( ":jqmData(role='popup')" ).length === 0 ) {
extendSelect( selectmenuWidget );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.controlgroup", $.mobile.widget, $.extend( {
options: {
shadow: false,
corners: true,
excludeInvisible: true,
type: "vertical",
mini: false,
initSelector: ":jqmData(role='controlgroup')"
},
_create: function() {
var $el = this.element,
ui = {
inner: $( "<div class='ui-controlgroup-controls'></div>" ),
legend: $( "<div role='heading' class='ui-controlgroup-label'></div>" )
},
grouplegend = $el.children( "legend" ),
self = this;
// Apply the proto
$el.wrapInner( ui.inner );
if ( grouplegend.length ) {
ui.legend.append( grouplegend ).insertBefore( $el.children( 0 ) );
}
$el.addClass( "ui-corner-all ui-controlgroup" );
$.extend( this, {
_initialRefresh: true
});
$.each( this.options, function( key, value ) {
// Cause initial options to be applied by their handler by temporarily setting the option to undefined
// - the handler then sets it to the initial value
self.options[ key ] = undefined;
self._setOption( key, value, true );
});
},
_init: function() {
this.refresh();
},
_setOption: function( key, value ) {
var setter = "_set" + key.charAt( 0 ).toUpperCase() + key.slice( 1 );
if ( this[ setter ] !== undefined ) {
this[ setter ]( value );
}
this._super( key, value );
this.element.attr( "data-" + ( $.mobile.ns || "" ) + ( key.replace( /([A-Z])/, "-$1" ).toLowerCase() ), value );
},
_setType: function( value ) {
this.element
.removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" )
.addClass( "ui-controlgroup-" + value );
this.refresh();
},
_setCorners: function( value ) {
this.element.toggleClass( "ui-corner-all", value );
},
_setShadow: function( value ) {
this.element.toggleClass( "ui-shadow", value );
},
_setMini: function( value ) {
this.element.toggleClass( "ui-mini", value );
},
container: function() {
return this.element.children( ".ui-controlgroup-controls" );
},
refresh: function() {
var els = this.element.find( ".ui-btn" ).not( ".ui-slider-handle" ),
create = this._initialRefresh;
if ( $.mobile.checkboxradio ) {
this.element.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" );
}
this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create );
this._initialRefresh = false;
}
}, $.mobile.behaviors.addFirstLastClasses ) );
// TODO: Implement a mechanism to allow widgets to become enhanced in the
// correct order when their correct enhancement depends on other widgets in
// the page being correctly enhanced already.
//
// For now, we wait until dom-ready to attach the controlgroup's enhancement
// hook, because by that time, all the other widgets' enhancement hooks should
// already be in place, ensuring that all widgets that need to be grouped will
// already have been enhanced by the time the controlgroup is created.
$( function() {
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.controlgroup.prototype.enhanceWithin( e.target, true );
});
});
})(jQuery);
(function( $, undefined ) {
$( document ).bind( "pagecreate create", function( e ) {
//links within content areas, tests included with page
$( e.target )
.find( "a" )
.jqmEnhanceable()
.not( ".ui-btn, .ui-link-inherit, :jqmData(role='none'), :jqmData(role='nojs')" )
.addClass( "ui-link" );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.widget, {
options: {
visibleOnPageShow: true,
disablePageZoom: true,
transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown)
fullscreen: false,
tapToggle: true,
tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-popup, .ui-panel, .ui-panel-dismiss-open",
hideDuringFocus: "input, textarea, select",
updatePagePadding: true,
trackPersistentToolbars: true,
// Browser detection! Weeee, here we go...
// Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately.
// Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience.
// Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window
// The following function serves to rule out some popular browsers with known fixed-positioning issues
// This is a plugin option like any other, so feel free to improve or overwrite it
supportBlacklist: function() {
return !$.support.fixedPosition;
},
initSelector: ":jqmData(position='fixed')"
},
_create: function() {
var self = this,
o = self.options,
$el = self.element,
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer",
$page = $el.closest( ".ui-page" );
// Feature detecting support for
if ( o.supportBlacklist() ) {
self.destroy();
return;
}
$el.addClass( "ui-"+ tbtype +"-fixed" );
// "fullscreen" overlay positioning
if ( o.fullscreen ) {
$el.addClass( "ui-"+ tbtype +"-fullscreen" );
$page.addClass( "ui-page-" + tbtype + "-fullscreen" );
}
// If not fullscreen, add class to page to set top or bottom padding
else{
$page.addClass( "ui-page-" + tbtype + "-fixed" );
}
$.extend( this, {
_thisPage: null
});
self._addTransitionClass();
self._bindPageEvents();
self._bindToggleHandlers();
},
_addTransitionClass: function() {
var tclass = this.options.transition;
if ( tclass && tclass !== "none" ) {
// use appropriate slide for header or footer
if ( tclass === "slide" ) {
tclass = this.element.is( ".ui-header" ) ? "slidedown" : "slideup";
}
this.element.addClass( tclass );
}
},
_bindPageEvents: function() {
this._thisPage = this.element.closest( ".ui-page" );
//page event bindings
// Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up
// This method is meant to disable zoom while a fixed-positioned toolbar page is visible
this._on( this._thisPage, {
"pagebeforeshow": "_handlePageBeforeShow",
"webkitAnimationStart":"_handleAnimationStart",
"animationstart":"_handleAnimationStart",
"updatelayout": "_handleAnimationStart",
"pageshow": "_handlePageShow",
"pagebeforehide": "_handlePageBeforeHide"
});
},
_handlePageBeforeShow: function() {
var o = this.options;
if ( o.disablePageZoom ) {
$.mobile.zoom.disable( true );
}
if ( !o.visibleOnPageShow ) {
this.hide( true );
}
},
_handleAnimationStart: function() {
if ( this.options.updatePagePadding ) {
this.updatePagePadding( this._thisPage );
}
},
_handlePageShow: function() {
this.updatePagePadding( this._thisPage );
if ( this.options.updatePagePadding ) {
this._on( $.mobile.window, { "throttledresize": "updatePagePadding" } );
}
},
_handlePageBeforeHide: function( e, ui ) {
var o = this.options;
if ( o.disablePageZoom ) {
$.mobile.zoom.enable( true );
}
if ( o.updatePagePadding ) {
this._off( $.mobile.window, "throttledresize" );
}
if ( o.trackPersistentToolbars ) {
var thisFooter = $( ".ui-footer-fixed:jqmData(id)", this._thisPage ),
thisHeader = $( ".ui-header-fixed:jqmData(id)", this._thisPage ),
nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(),
nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $();
if ( nextFooter.length || nextHeader.length ) {
nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer );
ui.nextPage.one( "pageshow", function() {
nextHeader.prependTo( this );
nextFooter.appendTo( this );
});
}
}
},
_visible: true,
// This will set the content element's top or bottom padding equal to the toolbar's height
updatePagePadding: function( tbPage ) {
var $el = this.element,
header = $el.is( ".ui-header" ),
pos = parseFloat( $el.css( header ? "top" : "bottom" ) );
// This behavior only applies to "fixed", not "fullscreen"
if ( this.options.fullscreen ) { return; }
// tbPage argument can be a Page object or an event, if coming from throttled resize.
tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this._thisPage || $el.closest( ".ui-page" );
$( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos );
},
_useTransition: function( notransition ) {
var $win = $.mobile.window,
$el = this.element,
scroll = $win.scrollTop(),
elHeight = $el.height(),
pHeight = $el.closest( ".ui-page" ).height(),
viewportHeight = $.mobile.getScreenHeight(),
tbtype = $el.is( ":jqmData(role='header')" ) ? "header" : "footer";
return !notransition &&
( this.options.transition && this.options.transition !== "none" &&
(
( tbtype === "header" && !this.options.fullscreen && scroll > elHeight ) ||
( tbtype === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight )
) || this.options.fullscreen
);
},
show: function( notransition ) {
var hideClass = "ui-fixed-hidden",
$el = this.element;
if ( this._useTransition( notransition ) ) {
$el
.removeClass( "out " + hideClass )
.addClass( "in" )
.animationComplete(function () {
$el.removeClass('in');
});
}
else {
$el.removeClass( hideClass );
}
this._visible = true;
},
hide: function( notransition ) {
var hideClass = "ui-fixed-hidden",
$el = this.element,
// if it's a slide transition, our new transitions need the reverse class as well to slide outward
outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" );
if( this._useTransition( notransition ) ) {
$el
.addClass( outclass )
.removeClass( "in" )
.animationComplete(function() {
$el.addClass( hideClass ).removeClass( outclass );
});
}
else {
$el.addClass( hideClass ).removeClass( outclass );
}
this._visible = false;
},
toggle: function() {
this[ this._visible ? "hide" : "show" ]();
},
_bindToggleHandlers: function() {
var self = this,
o = self.options,
$el = self.element,
delayShow, delayHide,
isVisible = true;
// tap toggle
$el.closest( ".ui-page" )
.bind( "vclick", function( e ) {
if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) {
self.toggle();
}
})
.bind( "focusin focusout", function( e ) {
//this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which
//positions fixed toolbars in the middle of the screen on pop if the input is near the top or
//bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment
//and issue #4113 Header and footer change their position after keyboard popup - iOS
//and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment
if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) {
//Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system
//controls causes fixed position, tap-toggle false Header to reveal itself
// isVisible instead of self._visible because the focusin and focusout events fire twice at the same time
// Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed
// by a focusout when a native selects opens and the other way around when it closes.
if ( e.type === "focusout" && !isVisible ) {
isVisible = true;
//wait for the stack to unwind and see if we have jumped to another input
clearTimeout( delayHide );
delayShow = setTimeout( function() {
self.show();
}, 0 );
} else if ( e.type === "focusin" && !!isVisible ) {
//if we have jumped to another input clear the time out to cancel the show.
clearTimeout( delayShow );
isVisible = false;
delayHide = setTimeout( function() {
self.hide();
}, 0 );
}
}
});
},
_destroy: function() {
var $el = this.element,
header = $el.is( ".ui-header" );
$el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" );
$el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" );
$el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" );
}
});
//auto self-init widgets
$.mobile.document
.bind( "pagecreate create", function( e ) {
// DEPRECATED in 1.1: support for data-fullscreen=true|false on the page element.
// This line ensures it still works, but we recommend moving the attribute to the toolbars themselves.
if ( $( e.target ).jqmData( "fullscreen" ) ) {
$( $.mobile.fixedtoolbar.prototype.options.initSelector, e.target ).not( ":jqmData(fullscreen)" ).jqmData( "fullscreen", true );
}
$.mobile.fixedtoolbar.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.fixedtoolbar, {
_create: function() {
this._super();
this._workarounds();
},
//check the browser and version and run needed workarounds
_workarounds: function() {
var ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
os = null,
self = this;
//set the os we are working in if it dosent match one with workarounds return
if( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ){
os = "ios";
} else if( ua.indexOf( "Android" ) > -1 ){
os = "android";
} else {
return;
}
//check os version if it dosent match one with workarounds return
if( os === "ios" ) {
//iOS workarounds
self._bindScrollWorkaround();
} else if( os === "android" && wkversion && wkversion < 534 ) {
//Android 2.3 run all Android 2.3 workaround
self._bindScrollWorkaround();
self._bindListThumbWorkaround();
} else {
return;
}
},
//Utility class for checking header and footer positions relative to viewport
_viewportOffset: function() {
var $el = this.element,
header = $el.is( ".ui-header" ),
offset = Math.abs($el.offset().top - $.mobile.window.scrollTop());
if( !header ) {
offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight())-60;
}
return offset;
},
//bind events for _triggerRedraw() function
_bindScrollWorkaround: function() {
var self = this;
//bind to scrollstop and check if the toolbars are correctly positioned
this._on( $.mobile.window, { scrollstop: function() {
var viewportOffset = self._viewportOffset();
//check if the header is visible and if its in the right place
if( viewportOffset > 2 && self._visible) {
self._triggerRedraw();
}
}});
},
//this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3
//and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used
//the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar
//setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other
//platforms we scope this with the class ui-android-2x-fix
_bindListThumbWorkaround: function() {
this.element.closest(".ui-page").addClass( "ui-android-2x-fixed" );
},
//this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android
//and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers.
//this also addresses not on fixed toolbars page in docs
//adding 1px of padding to the bottom then removing it causes a "redraw"
//which positions the toolbars correctly (they will always be visually correct)
_triggerRedraw: function() {
var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) );
//trigger page redraw to fix incorrectly positioned fixed elements
$( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) +"px" );
//if the padding is reset with out a timeout the reposition will not occure.
//this is independant of JQM the browser seems to need the time to react.
setTimeout( function() {
$( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" );
}, 0 );
},
destroy: function() {
this._super();
//Remove the class we added to the page previously in android 2.x
this.element.closest(".ui-page-active").removeClass( "ui-android-2x-fix" );
}
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.panel", $.mobile.widget, {
options: {
classes: {
panel: "ui-panel",
panelOpen: "ui-panel-open",
panelClosed: "ui-panel-closed",
panelFixed: "ui-panel-fixed",
panelInner: "ui-panel-inner",
modal: "ui-panel-dismiss",
modalOpen: "ui-panel-dismiss-open",
pagePanel: "ui-page-panel",
pagePanelOpen: "ui-page-panel-open",
contentWrap: "ui-panel-content-wrap",
contentWrapOpen: "ui-panel-content-wrap-open",
contentWrapClosed: "ui-panel-content-wrap-closed",
contentFixedToolbar: "ui-panel-content-fixed-toolbar",
contentFixedToolbarOpen: "ui-panel-content-fixed-toolbar-open",
contentFixedToolbarClosed: "ui-panel-content-fixed-toolbar-closed",
animate: "ui-panel-animate"
},
animate: true,
theme: "c",
position: "left",
dismissible: true,
display: "reveal", //accepts reveal, push, overlay
initSelector: ":jqmData(role='panel')",
swipeClose: true,
positionFixed: false
},
_panelID: null,
_closeLink: null,
_page: null,
_modal: null,
_panelInner: null,
_wrapper: null,
_fixedToolbar: null,
_create: function() {
var self = this,
$el = self.element,
page = $el.closest( ":jqmData(role='page')" ),
_getPageTheme = function() {
var $theme = $.data( page[0], "mobilePage" ).options.theme,
$pageThemeClass = "ui-body-" + $theme;
return $pageThemeClass;
},
_getPanelInner = function() {
var $panelInner = $el.find( "." + self.options.classes.panelInner );
if ( $panelInner.length === 0 ) {
$panelInner = $el.children().wrapAll( '<div class="' + self.options.classes.panelInner + '" />' ).parent();
}
return $panelInner;
},
_getWrapper = function() {
var $wrapper = page.find( "." + self.options.classes.contentWrap );
if ( $wrapper.length === 0 ) {
$wrapper = page.children( ".ui-header:not(:jqmData(position='fixed')), .ui-content:not(:jqmData(role='popup')), .ui-footer:not(:jqmData(position='fixed'))" ).wrapAll( '<div class="' + self.options.classes.contentWrap + ' ' + _getPageTheme() + '" />' ).parent();
if ( $.support.cssTransform3d && !!self.options.animate ) {
$wrapper.addClass( self.options.classes.animate );
}
}
return $wrapper;
},
_getFixedToolbar = function() {
var $fixedToolbar = page.find( "." + self.options.classes.contentFixedToolbar );
if ( $fixedToolbar.length === 0 ) {
$fixedToolbar = page.find( ".ui-header:jqmData(position='fixed'), .ui-footer:jqmData(position='fixed')" ).addClass( self.options.classes.contentFixedToolbar );
if ( $.support.cssTransform3d && !!self.options.animate ) {
$fixedToolbar.addClass( self.options.classes.animate );
}
}
return $fixedToolbar;
};
// expose some private props to other methods
$.extend( this, {
_panelID: $el.attr( "id" ),
_closeLink: $el.find( ":jqmData(rel='close')" ),
_page: $el.closest( ":jqmData(role='page')" ),
_pageTheme: _getPageTheme(),
_panelInner: _getPanelInner(),
_wrapper: _getWrapper(),
_fixedToolbar: _getFixedToolbar()
});
self._addPanelClasses();
self._wrapper.addClass( this.options.classes.contentWrapClosed );
self._fixedToolbar.addClass( this.options.classes.contentFixedToolbarClosed );
// add class to page so we can set "overflow-x: hidden;" for it to fix Android zoom issue
self._page.addClass( self.options.classes.pagePanel );
// if animating, add the class to do so
if ( $.support.cssTransform3d && !!self.options.animate ) {
this.element.addClass( self.options.classes.animate );
}
self._bindUpdateLayout();
self._bindCloseEvents();
self._bindLinkListeners();
self._bindPageEvents();
if ( !!self.options.dismissible ) {
self._createModal();
}
self._bindSwipeEvents();
},
_createModal: function( options ) {
var self = this;
self._modal = $( "<div class='" + self.options.classes.modal + "' data-panelid='" + self._panelID + "'></div>" )
.on( "mousedown", function() {
self.close();
})
.appendTo( this._page );
},
_getPosDisplayClasses: function( prefix ) {
return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display;
},
_getPanelClasses: function() {
var panelClasses = this.options.classes.panel +
" " + this._getPosDisplayClasses( this.options.classes.panel ) +
" " + this.options.classes.panelClosed;
if ( this.options.theme ) {
panelClasses += " ui-body-" + this.options.theme;
}
if ( !!this.options.positionFixed ) {
panelClasses += " " + this.options.classes.panelFixed;
}
return panelClasses;
},
_addPanelClasses: function() {
this.element.addClass( this._getPanelClasses() );
},
_bindCloseEvents: function() {
var self = this;
self._closeLink.on( "click.panel" , function( e ) {
e.preventDefault();
self.close();
return false;
});
self.element.on( "click.panel" , "a:jqmData(ajax='false')", function( e ) {
self.close();
});
},
_positionPanel: function() {
var self = this,
panelInnerHeight = self._panelInner.outerHeight(),
expand = panelInnerHeight > $.mobile.getScreenHeight();
if ( expand || !self.options.positionFixed ) {
if ( expand ) {
self._unfixPanel();
$.mobile.resetActivePageHeight( panelInnerHeight );
}
self._scrollIntoView( panelInnerHeight );
} else {
self._fixPanel();
}
},
_scrollIntoView: function( panelInnerHeight ) {
if ( panelInnerHeight < $( window ).scrollTop() ) {
window.scrollTo( 0, 0 );
}
},
_bindFixListener: function() {
this._on( $( window ), { "throttledresize": "_positionPanel" });
},
_unbindFixListener: function() {
this._off( $( window ), "throttledresize" );
},
_unfixPanel: function() {
if ( !!this.options.positionFixed && $.support.fixedPosition ) {
this.element.removeClass( this.options.classes.panelFixed );
}
},
_fixPanel: function() {
if ( !!this.options.positionFixed && $.support.fixedPosition ) {
this.element.addClass( this.options.classes.panelFixed );
}
},
_bindUpdateLayout: function() {
var self = this;
self.element.on( "updatelayout", function( e ) {
if ( self._open ) {
self._positionPanel();
}
});
},
_bindLinkListeners: function() {
var self = this;
self._page.on( "click.panel" , "a", function( e ) {
if ( this.href.split( "#" )[ 1 ] === self._panelID && self._panelID !== undefined ) {
e.preventDefault();
var $link = $( this );
if ( ! $link.hasClass( "ui-link" ) ) {
$link.addClass( $.mobile.activeBtnClass );
self.element.one( "panelopen panelclose", function() {
$link.removeClass( $.mobile.activeBtnClass );
});
}
self.toggle();
return false;
}
});
},
_bindSwipeEvents: function() {
var self = this,
area = self._modal ? self.element.add( self._modal ) : self.element;
// on swipe, close the panel
if( !!self.options.swipeClose ) {
if ( self.options.position === "left" ) {
area.on( "swipeleft.panel", function( e ) {
self.close();
});
} else {
area.on( "swiperight.panel", function( e ) {
self.close();
});
}
}
},
_bindPageEvents: function() {
var self = this;
self._page
// Close the panel if another panel on the page opens
.on( "panelbeforeopen", function( e ) {
if ( self._open && e.target !== self.element[ 0 ] ) {
self.close();
}
})
// clean up open panels after page hide
.on( "pagehide", function( e ) {
if ( self._open ) {
self.close( true );
}
})
// on escape, close? might need to have a target check too...
.on( "keyup.panel", function( e ) {
if ( e.keyCode === 27 && self._open ) {
self.close();
}
});
},
// state storage of open or closed
_open: false,
_contentWrapOpenClasses: null,
_fixedToolbarOpenClasses: null,
_modalOpenClasses: null,
open: function( immediate ) {
if ( !this._open ) {
var self = this,
o = self.options,
_openPanel = function() {
self._page.off( "panelclose" );
self._page.jqmData( "panel", "open" );
if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
} else {
setTimeout( complete, 0 );
}
if ( self.options.theme && self.options.display !== "overlay" ) {
self._page
.removeClass( self._pageTheme )
.addClass( "ui-body-" + self.options.theme );
}
self.element.removeClass( o.classes.panelClosed ).addClass( o.classes.panelOpen );
self._positionPanel();
// Fix for IE7 min-height bug
if ( self.options.theme && self.options.display !== "overlay" ) {
self._wrapper.css( "min-height", self._page.css( "min-height" ) );
}
self._contentWrapOpenClasses = self._getPosDisplayClasses( o.classes.contentWrap );
self._wrapper
.removeClass( o.classes.contentWrapClosed )
.addClass( self._contentWrapOpenClasses + " " + o.classes.contentWrapOpen );
self._fixedToolbarOpenClasses = self._getPosDisplayClasses( o.classes.contentFixedToolbar );
self._fixedToolbar
.removeClass( o.classes.contentFixedToolbarClosed )
.addClass( self._fixedToolbarOpenClasses + " " + o.classes.contentFixedToolbarOpen );
self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen;
if ( self._modal ) {
self._modal.addClass( self._modalOpenClasses );
}
},
complete = function() {
self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
self._page.addClass( o.classes.pagePanelOpen );
self._bindFixListener();
self._trigger( "open" );
};
if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
immediate = true;
}
self._trigger( "beforeopen" );
if ( self._page.jqmData('panel') === "open" ) {
self._page.on( "panelclose", function() {
_openPanel();
});
} else {
_openPanel();
}
self._open = true;
}
},
close: function( immediate ) {
if ( this._open ) {
var o = this.options,
self = this,
_closePanel = function() {
if ( !immediate && $.support.cssTransform3d && !!o.animate ) {
self.element.add( self._wrapper ).on( self._transitionEndEvents, complete );
} else {
setTimeout( complete, 0 );
}
self._page.removeClass( o.classes.pagePanelOpen );
self.element.removeClass( o.classes.panelOpen );
self._wrapper.removeClass( o.classes.contentWrapOpen );
self._fixedToolbar.removeClass( o.classes.contentFixedToolbarOpen );
if ( self._modal ) {
self._modal.removeClass( self._modalOpenClasses );
}
},
complete = function() {
if ( self.options.theme && self.options.display !== "overlay" ) {
self._page.removeClass( "ui-body-" + self.options.theme ).addClass( self._pageTheme );
// reset fix for IE7 min-height bug
self._wrapper.css( "min-height", "" );
}
self.element.add( self._wrapper ).off( self._transitionEndEvents, complete );
self.element.addClass( o.classes.panelClosed );
self._wrapper
.removeClass( self._contentWrapOpenClasses )
.addClass( o.classes.contentWrapClosed );
self._fixedToolbar
.removeClass( self._fixedToolbarOpenClasses )
.addClass( o.classes.contentFixedToolbarClosed );
self._fixPanel();
self._unbindFixListener();
$.mobile.resetActivePageHeight();
self._page.jqmRemoveData( "panel" );
self._trigger( "close" );
};
if ( this.element.closest( ".ui-page-active" ).length < 0 ) {
immediate = true;
}
self._trigger( "beforeclose" );
_closePanel();
self._open = false;
}
},
toggle: function( options ) {
this[ this._open ? "close" : "open" ]();
},
_transitionEndEvents: "webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd",
_destroy: function() {
var classes = this.options.classes,
theme = this.options.theme,
hasOtherSiblingPanels = this.element.siblings( "." + classes.panel ).length;
// create
if ( !hasOtherSiblingPanels ) {
this._wrapper.children().unwrap();
this._page.find( "a" ).unbind( "panelopen panelclose" );
this._page.removeClass( classes.pagePanel );
if ( this._open ) {
this._page.jqmRemoveData( "panel" );
this._page.removeClass( classes.pagePanelOpen );
if ( theme ) {
this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
}
$.mobile.resetActivePageHeight();
}
} else if ( this._open ) {
this._wrapper.removeClass( classes.contentWrapOpen );
this._fixedToolbar.removeClass( classes.contentFixedToolbarOpen );
this._page.jqmRemoveData( "panel" );
this._page.removeClass( classes.pagePanelOpen );
if ( theme ) {
this._page.removeClass( "ui-body-" + theme ).addClass( this._pageTheme );
}
}
this._panelInner.children().unwrap();
this.element.removeClass( [ this._getPanelClasses(), classes.panelAnimate ].join( " " ) )
.off( "swipeleft.panel swiperight.panel" )
.off( "panelbeforeopen" )
.off( "panelhide" )
.off( "keyup.panel" )
.off( "updatelayout" );
this._closeLink.off( "click.panel" );
if ( this._modal ) {
this._modal.remove();
}
// open and close
this.element.off( this._transitionEndEvents )
.removeClass( [ classes.panelUnfixed, classes.panelClosed, classes.panelOpen ].join( " " ) );
}
});
//auto self-init widgets
$( document ).bind( "pagecreate create", function( e ) {
$.mobile.panel.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.widget( "mobile.table", $.mobile.widget, {
options: {
classes: {
table: "ui-table"
},
initSelector: ":jqmData(role='table')"
},
_create: function() {
var self = this;
self.refresh( true );
},
refresh: function (create) {
var self = this,
trs = this.element.find( "thead tr" );
if ( create ) {
this.element.addClass( this.options.classes.table );
}
// Expose headers and allHeaders properties on the widget
// headers references the THs within the first TR in the table
self.headers = this.element.find( "tr:eq(0)" ).children();
// allHeaders references headers, plus all THs in the thead, which may include several rows, or not
self.allHeaders = self.headers.add( trs.children() );
trs.each(function(){
var coltally = 0;
$( this ).children().each(function( i ){
var span = parseInt( $( this ).attr( "colspan" ), 10 ),
sel = ":nth-child(" + ( coltally + 1 ) + ")";
$( this )
.jqmData( "colstart", coltally + 1 );
if( span ){
for( var j = 0; j < span - 1; j++ ){
coltally++;
sel += ", :nth-child(" + ( coltally + 1 ) + ")";
}
}
if ( create === undefined ) {
$(this).jqmData("cells", "");
}
// Store "cells" data on header as a reference to all cells in the same column as this TH
$( this )
.jqmData( "cells", self.element.find( "tr" ).not( trs.eq(0) ).not( this ).children( sel ) );
coltally++;
});
});
// update table modes
if ( create === undefined ) {
this.element.trigger( 'refresh' );
}
}
});
//auto self-init widgets
$.mobile.document.bind( "pagecreate create", function( e ) {
$.mobile.table.prototype.enhanceWithin( e.target );
});
})( jQuery );
(function( $, undefined ) {
$.mobile.table.prototype.options.mode = "columntoggle";
$.mobile.table.prototype.options.columnBtnTheme = null;
$.mobile.table.prototype.options.columnPopupTheme = null;
$.mobile.table.prototype.options.columnBtnText = "Columns...";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
popup: "ui-table-columntoggle-popup",
columnBtn: "ui-table-columntoggle-btn",
priorityPrefix: "ui-table-priority-",
columnToggleTable: "ui-table-columntoggle"
}
);
$.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
var $table = $( this ),
self = $table.data( "mobile-table" ),
event = e.type,
o = self.options,
ns = $.mobile.ns,
id = ( $table.attr( "id" ) || o.classes.popup ) + "-popup", /* TODO BETTER FALLBACK ID HERE */
$menuButton,
$popup,
$menu,
$switchboard;
if ( o.mode !== "columntoggle" ) {
return;
}
if ( event !== "refresh" ) {
self.element.addClass( o.classes.columnToggleTable );
$menuButton = $( "<a href='#" + id + "' class='" + o.classes.columnBtn + "' data-" + ns + "rel='popup' data-" + ns + "mini='true'>" + o.columnBtnText + "</a>" ),
$popup = $( "<div data-" + ns + "role='popup' data-" + ns + "role='fieldcontain' class='" + o.classes.popup + "' id='" + id + "'></div>"),
$menu = $("<fieldset data-" + ns + "role='controlgroup'></fieldset>");
}
// create the hide/show toggles
self.headers.not( "td" ).each(function( i ) {
var priority = $( this ).jqmData( "priority" ),
$cells = $( this ).add( $( this ).jqmData( "cells" ) );
if ( priority ) {
$cells.addClass( o.classes.priorityPrefix + priority );
if ( event !== "refresh" ) {
$("<label><input type='checkbox' checked />" + $( this ).text() + "</label>" )
.appendTo( $menu )
.children( 0 )
.jqmData( "cells", $cells )
.checkboxradio({
theme: o.columnPopupTheme
});
} else {
$( '#' + id + ' fieldset div:eq(' + i +')').find('input').jqmData( 'cells', $cells );
}
}
});
if ( event !== "refresh" ) {
$menu.appendTo( $popup );
}
// bind change event listeners to inputs - TODO: move to a private method?
if ( $menu === undefined ) {
$switchboard = $('#' + id + ' fieldset');
} else {
$switchboard = $menu;
}
if ( event !== "refresh" ) {
$switchboard.on( "change", "input", function( e ){
if( this.checked ){
$( this ).jqmData( "cells" ).removeClass( "ui-table-cell-hidden" ).addClass( "ui-table-cell-visible" );
} else {
$( this ).jqmData( "cells" ).removeClass( "ui-table-cell-visible" ).addClass( "ui-table-cell-hidden" );
}
});
$menuButton
.insertBefore( $table )
.buttonMarkup({
theme: o.columnBtnTheme
});
$popup
.insertBefore( $table )
.popup();
}
// refresh method
self.update = function(){
$switchboard.find( "input" ).each( function(){
if (this.checked) {
this.checked = $( this ).jqmData( "cells" ).eq(0).css( "display" ) === "table-cell";
if (event === "refresh") {
$( this ).jqmData( "cells" ).addClass('ui-table-cell-visible');
}
} else {
$( this ).jqmData( "cells" ).addClass('ui-table-cell-hidden');
}
$( this ).checkboxradio( "refresh" );
});
};
$.mobile.window.on( "throttledresize", self.update );
self.update();
});
})( jQuery );
(function( $, undefined ) {
$.mobile.table.prototype.options.mode = "reflow";
$.mobile.table.prototype.options.classes = $.extend(
$.mobile.table.prototype.options.classes,
{
reflowTable: "ui-table-reflow",
cellLabels: "ui-table-cell-label"
}
);
$.mobile.document.delegate( ":jqmData(role='table')", "tablecreate refresh", function( e ) {
var $table = $( this ),
event = e.type,
self = $table.data( "mobile-table" ),
o = self.options;
// If it's not reflow mode, return here.
if( o.mode !== "reflow" ){
return;
}
if ( event !== "refresh" ) {
self.element.addClass( o.classes.reflowTable );
}
// get headers in reverse order so that top-level headers are appended last
var reverseHeaders = $( self.allHeaders.get().reverse() );
// create the hide/show toggles
reverseHeaders.each(function( i ){
var $cells = $( this ).jqmData( "cells" ),
colstart = $( this ).jqmData( "colstart" ),
hierarchyClass = $cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top",
text = $(this).text();
if( text !== "" ){
if( hierarchyClass ){
var iteration = parseInt( $( this ).attr( "colspan" ), 10 ),
filter = "";
if( iteration ){
filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")";
}
$cells.filter( filter ).prepend( "<b class='" + o.classes.cellLabels + hierarchyClass + "'>" + text + "</b>" );
}
else {
$cells.prepend( "<b class='" + o.classes.cellLabels + "'>" + text + "</b>" );
}
}
});
});
})( jQuery );
(function( $, window ) {
$.mobile.iosorientationfixEnabled = true;
// This fix addresses an iOS bug, so return early if the UA claims it's something else.
var ua = navigator.userAgent;
if( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ){
$.mobile.iosorientationfixEnabled = false;
return;
}
var zoom = $.mobile.zoom,
evt, x, y, z, aig;
function checkTilt( e ) {
evt = e.originalEvent;
aig = evt.accelerationIncludingGravity;
x = Math.abs( aig.x );
y = Math.abs( aig.y );
z = Math.abs( aig.z );
// If portrait orientation and in one of the danger zones
if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) {
if ( zoom.enabled ) {
zoom.disable();
}
} else if ( !zoom.enabled ) {
zoom.enable();
}
}
$.mobile.document.on( "mobileinit", function(){
if( $.mobile.iosorientationfixEnabled ){
$.mobile.window
.bind( "orientationchange.iosorientationfix", zoom.enable )
.bind( "devicemotion.iosorientationfix", checkTilt );
}
});
}( jQuery, this ));
(function( $, window, undefined ) {
var $html = $( "html" ),
$head = $( "head" ),
$window = $.mobile.window;
//remove initial build class (only present on first pageshow)
function hideRenderingClass() {
$html.removeClass( "ui-mobile-rendering" );
}
// trigger mobileinit event - useful hook for configuring $.mobile settings before they're used
$( window.document ).trigger( "mobileinit" );
// support conditions
// if device support condition(s) aren't met, leave things as they are -> a basic, usable experience,
// otherwise, proceed with the enhancements
if ( !$.mobile.gradeA() ) {
return;
}
// override ajaxEnabled on platforms that have known conflicts with hash history updates
// or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini)
if ( $.mobile.ajaxBlacklist ) {
$.mobile.ajaxEnabled = false;
}
// Add mobile, initial load "rendering" classes to docEl
$html.addClass( "ui-mobile ui-mobile-rendering" );
// This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire,
// this ensures the rendering class is removed after 5 seconds, so content is visible and accessible
setTimeout( hideRenderingClass, 5000 );
$.extend( $.mobile, {
// find and enhance the pages in the dom and transition to the first page.
initializePage: function() {
// find present pages
var path = $.mobile.path,
$pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ),
hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ),
hashPage = document.getElementById( hash );
// if no pages are found, create one with body's inner html
if ( !$pages.length ) {
$pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 );
}
// add dialogs, set data-url attrs
$pages.each(function() {
var $this = $( this );
// unless the data url is already set set it to the pathname
if ( !$this.jqmData( "url" ) ) {
$this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search );
}
});
// define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback)
$.mobile.firstPage = $pages.first();
// define page container
$.mobile.pageContainer = $.mobile.firstPage.parent().addClass( "ui-mobile-viewport" );
// alert listeners that the pagecontainer has been determined for binding
// to events triggered on it
$window.trigger( "pagecontainercreate" );
// cue page loading message
$.mobile.showPageLoadingMsg();
//remove initial build class (only present on first pageshow)
hideRenderingClass();
// if hashchange listening is disabled, there's no hash deeplink,
// the hash is not valid (contains more than one # or does not start with #)
// or there is no page with that hash, change to the first page in the DOM
// Remember, however, that the hash can also be a path!
if ( ! ( $.mobile.hashListeningEnabled &&
$.mobile.path.isHashValid( location.hash ) &&
( $( hashPage ).is( ':jqmData(role="page")' ) ||
$.mobile.path.isPath( hash ) ||
hash === $.mobile.dialogHashKey ) ) ) {
// Store the initial destination
if ( $.mobile.path.isHashValid( location.hash ) ) {
$.mobile.urlHistory.initialDst = hash.replace( "#", "" );
}
// make sure to set initial popstate state if it exists
// so that navigation back to the initial page works properly
if( $.event.special.navigate.isPushStateEnabled() ) {
$.mobile.navigate.navigator.squash( path.parseLocation().href );
}
$.mobile.changePage( $.mobile.firstPage, {
transition: "none",
reverse: true,
changeHash: false,
fromHashChange: true
});
} else {
// trigger hashchange or navigate to squash and record the correct
// history entry for an initial hash path
if( !$.event.special.navigate.isPushStateEnabled() ) {
$window.trigger( "hashchange", [true] );
} else {
// TODO figure out how to simplify this interaction with the initial history entry
// at the bottom js/navigate/navigate.js
$.mobile.navigate.history.stack = [];
$.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href );
}
}
}
});
// initialize events now, after mobileinit has occurred
$.mobile.navreadyDeferred.resolve();
// check which scrollTop value should be used by scrolling to 1 immediately at domready
// then check what the scroll top is. Android will report 0... others 1
// note that this initial scroll won't hide the address bar. It's just for the check.
$(function() {
window.scrollTo( 0, 1 );
// if defaultHomeScroll hasn't been set yet, see if scrollTop is 1
// it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar)
// so if it's 1, use 0 from now on
$.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1;
//dom-ready inits
if ( $.mobile.autoInitializePage ) {
$.mobile.initializePage();
}
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
if ( !$.support.cssPointerEvents ) {
// IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons
// by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser.
// https://github.com/jquery/jquery-mobile/issues/3558
$.mobile.document.delegate( ".ui-disabled", "vclick",
function( e ) {
e.preventDefault();
e.stopImmediatePropagation();
}
);
}
});
}( jQuery, this ));
}));
|
src/svg-icons/communication/no-sim.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationNoSim = (props) => (
<SvgIcon {...props}>
<path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/>
</SvgIcon>
);
CommunicationNoSim = pure(CommunicationNoSim);
CommunicationNoSim.displayName = 'CommunicationNoSim';
CommunicationNoSim.muiName = 'SvgIcon';
export default CommunicationNoSim;
|
ajax/libs/react-bootstrap/0.24.0/react-bootstrap.js | sajochiu/cdnjs | (function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReactBootstrap"] = factory(require("react"));
else
root["ReactBootstrap"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_16__) {
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 _interopRequireDefault = __webpack_require__(2)['default'];
var _interopRequireWildcard = __webpack_require__(18)['default'];
exports.__esModule = true;
var _Accordion2 = __webpack_require__(19);
var _Accordion3 = _interopRequireDefault(_Accordion2);
exports.Accordion = _Accordion3['default'];
var _Affix2 = __webpack_require__(29);
var _Affix3 = _interopRequireDefault(_Affix2);
exports.Affix = _Affix3['default'];
var _AffixMixin2 = __webpack_require__(30);
var _AffixMixin3 = _interopRequireDefault(_AffixMixin2);
exports.AffixMixin = _AffixMixin3['default'];
var _Alert2 = __webpack_require__(33);
var _Alert3 = _interopRequireDefault(_Alert2);
exports.Alert = _Alert3['default'];
var _Badge2 = __webpack_require__(34);
var _Badge3 = _interopRequireDefault(_Badge2);
exports.Badge = _Badge3['default'];
var _BootstrapMixin2 = __webpack_require__(21);
var _BootstrapMixin3 = _interopRequireDefault(_BootstrapMixin2);
exports.BootstrapMixin = _BootstrapMixin3['default'];
var _Button2 = __webpack_require__(35);
var _Button3 = _interopRequireDefault(_Button2);
exports.Button = _Button3['default'];
var _ButtonGroup2 = __webpack_require__(41);
var _ButtonGroup3 = _interopRequireDefault(_ButtonGroup2);
exports.ButtonGroup = _ButtonGroup3['default'];
var _ButtonInput2 = __webpack_require__(36);
var _ButtonInput3 = _interopRequireDefault(_ButtonInput2);
exports.ButtonInput = _ButtonInput3['default'];
var _ButtonToolbar2 = __webpack_require__(42);
var _ButtonToolbar3 = _interopRequireDefault(_ButtonToolbar2);
exports.ButtonToolbar = _ButtonToolbar3['default'];
var _Carousel2 = __webpack_require__(43);
var _Carousel3 = _interopRequireDefault(_Carousel2);
exports.Carousel = _Carousel3['default'];
var _CarouselItem2 = __webpack_require__(45);
var _CarouselItem3 = _interopRequireDefault(_CarouselItem2);
exports.CarouselItem = _CarouselItem3['default'];
var _Col2 = __webpack_require__(47);
var _Col3 = _interopRequireDefault(_Col2);
exports.Col = _Col3['default'];
var _CollapsibleMixin2 = __webpack_require__(48);
var _CollapsibleMixin3 = _interopRequireDefault(_CollapsibleMixin2);
exports.CollapsibleMixin = _CollapsibleMixin3['default'];
var _CollapsibleNav2 = __webpack_require__(52);
var _CollapsibleNav3 = _interopRequireDefault(_CollapsibleNav2);
exports.CollapsibleNav = _CollapsibleNav3['default'];
var _DropdownButton2 = __webpack_require__(56);
var _DropdownButton3 = _interopRequireDefault(_DropdownButton2);
exports.DropdownButton = _DropdownButton3['default'];
var _DropdownMenu2 = __webpack_require__(58);
var _DropdownMenu3 = _interopRequireDefault(_DropdownMenu2);
exports.DropdownMenu = _DropdownMenu3['default'];
var _DropdownStateMixin2 = __webpack_require__(57);
var _DropdownStateMixin3 = _interopRequireDefault(_DropdownStateMixin2);
exports.DropdownStateMixin = _DropdownStateMixin3['default'];
var _FadeMixin2 = __webpack_require__(59);
var _FadeMixin3 = _interopRequireDefault(_FadeMixin2);
exports.FadeMixin = _FadeMixin3['default'];
var _Glyphicon2 = __webpack_require__(44);
var _Glyphicon3 = _interopRequireDefault(_Glyphicon2);
exports.Glyphicon = _Glyphicon3['default'];
var _Grid2 = __webpack_require__(60);
var _Grid3 = _interopRequireDefault(_Grid2);
exports.Grid = _Grid3['default'];
var _Input2 = __webpack_require__(61);
var _Input3 = _interopRequireDefault(_Input2);
exports.Input = _Input3['default'];
var _Interpolate2 = __webpack_require__(64);
var _Interpolate3 = _interopRequireDefault(_Interpolate2);
exports.Interpolate = _Interpolate3['default'];
var _Jumbotron2 = __webpack_require__(65);
var _Jumbotron3 = _interopRequireDefault(_Jumbotron2);
exports.Jumbotron = _Jumbotron3['default'];
var _Label2 = __webpack_require__(66);
var _Label3 = _interopRequireDefault(_Label2);
exports.Label = _Label3['default'];
var _ListGroup2 = __webpack_require__(67);
var _ListGroup3 = _interopRequireDefault(_ListGroup2);
exports.ListGroup = _ListGroup3['default'];
var _ListGroupItem2 = __webpack_require__(68);
var _ListGroupItem3 = _interopRequireDefault(_ListGroupItem2);
exports.ListGroupItem = _ListGroupItem3['default'];
var _MenuItem2 = __webpack_require__(70);
var _MenuItem3 = _interopRequireDefault(_MenuItem2);
exports.MenuItem = _MenuItem3['default'];
var _Modal2 = __webpack_require__(71);
var _Modal3 = _interopRequireDefault(_Modal2);
exports.Modal = _Modal3['default'];
var _ModalHeader2 = __webpack_require__(75);
var _ModalHeader3 = _interopRequireDefault(_ModalHeader2);
exports.ModalHeader = _ModalHeader3['default'];
var _ModalTitle2 = __webpack_require__(1);
var _ModalTitle3 = _interopRequireDefault(_ModalTitle2);
exports.ModalTitle = _ModalTitle3['default'];
var _ModalBody2 = __webpack_require__(74);
var _ModalBody3 = _interopRequireDefault(_ModalBody2);
exports.ModalBody = _ModalBody3['default'];
var _ModalFooter2 = __webpack_require__(76);
var _ModalFooter3 = _interopRequireDefault(_ModalFooter2);
exports.ModalFooter = _ModalFooter3['default'];
var _Nav2 = __webpack_require__(77);
var _Nav3 = _interopRequireDefault(_Nav2);
exports.Nav = _Nav3['default'];
var _Navbar2 = __webpack_require__(78);
var _Navbar3 = _interopRequireDefault(_Navbar2);
exports.Navbar = _Navbar3['default'];
var _NavItem2 = __webpack_require__(79);
var _NavItem3 = _interopRequireDefault(_NavItem2);
exports.NavItem = _NavItem3['default'];
var _Overlay2 = __webpack_require__(80);
var _Overlay3 = _interopRequireDefault(_Overlay2);
exports.Overlay = _Overlay3['default'];
var _OverlayTrigger2 = __webpack_require__(84);
var _OverlayTrigger3 = _interopRequireDefault(_OverlayTrigger2);
exports.OverlayTrigger = _OverlayTrigger3['default'];
var _PageHeader2 = __webpack_require__(86);
var _PageHeader3 = _interopRequireDefault(_PageHeader2);
exports.PageHeader = _PageHeader3['default'];
var _PageItem2 = __webpack_require__(87);
var _PageItem3 = _interopRequireDefault(_PageItem2);
exports.PageItem = _PageItem3['default'];
var _Pager2 = __webpack_require__(88);
var _Pager3 = _interopRequireDefault(_Pager2);
exports.Pager = _Pager3['default'];
var _Pagination2 = __webpack_require__(89);
var _Pagination3 = _interopRequireDefault(_Pagination2);
exports.Pagination = _Pagination3['default'];
var _Panel2 = __webpack_require__(92);
var _Panel3 = _interopRequireDefault(_Panel2);
exports.Panel = _Panel3['default'];
var _PanelGroup2 = __webpack_require__(20);
var _PanelGroup3 = _interopRequireDefault(_PanelGroup2);
exports.PanelGroup = _PanelGroup3['default'];
var _Popover2 = __webpack_require__(93);
var _Popover3 = _interopRequireDefault(_Popover2);
exports.Popover = _Popover3['default'];
var _ProgressBar2 = __webpack_require__(94);
var _ProgressBar3 = _interopRequireDefault(_ProgressBar2);
exports.ProgressBar = _ProgressBar3['default'];
var _Row2 = __webpack_require__(95);
var _Row3 = _interopRequireDefault(_Row2);
exports.Row = _Row3['default'];
var _SafeAnchor2 = __webpack_require__(69);
var _SafeAnchor3 = _interopRequireDefault(_SafeAnchor2);
exports.SafeAnchor = _SafeAnchor3['default'];
var _SplitButton2 = __webpack_require__(96);
var _SplitButton3 = _interopRequireDefault(_SplitButton2);
exports.SplitButton = _SplitButton3['default'];
var _styleMaps2 = __webpack_require__(22);
var _styleMaps3 = _interopRequireDefault(_styleMaps2);
exports.styleMaps = _styleMaps3['default'];
var _SubNav2 = __webpack_require__(97);
var _SubNav3 = _interopRequireDefault(_SubNav2);
exports.SubNav = _SubNav3['default'];
var _TabbedArea2 = __webpack_require__(98);
var _TabbedArea3 = _interopRequireDefault(_TabbedArea2);
exports.TabbedArea = _TabbedArea3['default'];
var _Table2 = __webpack_require__(99);
var _Table3 = _interopRequireDefault(_Table2);
exports.Table = _Table3['default'];
var _TabPane2 = __webpack_require__(100);
var _TabPane3 = _interopRequireDefault(_TabPane2);
exports.TabPane = _TabPane3['default'];
var _Thumbnail2 = __webpack_require__(101);
var _Thumbnail3 = _interopRequireDefault(_Thumbnail2);
exports.Thumbnail = _Thumbnail3['default'];
var _Tooltip2 = __webpack_require__(102);
var _Tooltip3 = _interopRequireDefault(_Tooltip2);
exports.Tooltip = _Tooltip3['default'];
var _Well2 = __webpack_require__(103);
var _Well3 = _interopRequireDefault(_Well2);
exports.Well = _Well3['default'];
var _Portal2 = __webpack_require__(72);
var _Portal3 = _interopRequireDefault(_Portal2);
exports.Portal = _Portal3['default'];
var _Position2 = __webpack_require__(81);
var _Position3 = _interopRequireDefault(_Position2);
exports.Position = _Position3['default'];
var _Collapse2 = __webpack_require__(53);
var _Collapse3 = _interopRequireDefault(_Collapse2);
exports.Collapse = _Collapse3['default'];
var _Collapse4 = _interopRequireDefault(_Collapse2);
exports.Fade = _Collapse4['default'];
var _FormControls2 = __webpack_require__(62);
var _FormControls = _interopRequireWildcard(_FormControls2);
exports.FormControls = _FormControls;
var _utils2 = __webpack_require__(104);
var _utils = _interopRequireWildcard(_utils2);
exports.utils = _utils;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var ModalTitle = (function (_React$Component) {
_inherits(ModalTitle, _React$Component);
function ModalTitle() {
_classCallCheck(this, ModalTitle);
_React$Component.apply(this, arguments);
}
ModalTitle.prototype.render = function render() {
return _react2['default'].createElement(
'h4',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, this.props.modalClassName) }),
this.props.children
);
};
return ModalTitle;
})(_react2['default'].Component);
ModalTitle.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: _react2['default'].PropTypes.string
};
ModalTitle.defaultProps = {
modalClassName: 'modal-title'
};
exports['default'] = ModalTitle;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
"use strict";
exports["default"] = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
exports.__esModule = true;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var _Object$create = __webpack_require__(4)["default"];
exports["default"] = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = _Object$create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) subClass.__proto__ = superClass;
};
exports.__esModule = true;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(5), __esModule: true };
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(6);
module.exports = function create(P, D){
return $.create(P, D);
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = typeof self != 'undefined' ? self : Function('return this')()
, core = {}
, defineProperty = Object.defineProperty
, hasOwnProperty = {}.hasOwnProperty
, ceil = Math.ceil
, floor = Math.floor
, max = Math.max
, min = Math.min;
// The engine works fine with descriptors? Thank's IE8 for his funny defineProperty.
var DESC = !!function(){
try {
return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2;
} catch(e){ /* empty */ }
}();
var hide = createDefiner(1);
// 7.1.4 ToInteger
function toInteger(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
}
function desc(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
}
function simpleSet(object, key, value){
object[key] = value;
return object;
}
function createDefiner(bitmap){
return DESC ? function(object, key, value){
return $.setDesc(object, key, desc(bitmap, value));
} : simpleSet;
}
function isObject(it){
return it !== null && (typeof it == 'object' || typeof it == 'function');
}
function isFunction(it){
return typeof it == 'function';
}
function assertDefined(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
}
var $ = module.exports = __webpack_require__(7)({
g: global,
core: core,
html: global.document && document.documentElement,
// http://jsperf.com/core-js-isobject
isObject: isObject,
isFunction: isFunction,
that: function(){
return this;
},
// 7.1.4 ToInteger
toInteger: toInteger,
// 7.1.15 ToLength
toLength: function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
},
toIndex: function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
},
has: function(it, key){
return hasOwnProperty.call(it, key);
},
create: Object.create,
getProto: Object.getPrototypeOf,
DESC: DESC,
desc: desc,
getDesc: Object.getOwnPropertyDescriptor,
setDesc: defineProperty,
setDescs: Object.defineProperties,
getKeys: Object.keys,
getNames: Object.getOwnPropertyNames,
getSymbols: Object.getOwnPropertySymbols,
assertDefined: assertDefined,
// Dummy, fix for not array-like ES3 string in es5 module
ES5Object: Object,
toObject: function(it){
return $.ES5Object(assertDefined(it));
},
hide: hide,
def: createDefiner(0),
set: global.Symbol ? simpleSet : hide,
each: [].forEach
});
/* eslint-disable no-undef */
if(typeof __e != 'undefined')__e = core;
if(typeof __g != 'undefined')__g = global;
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = function($){
$.FW = false;
$.path = $.core;
return $;
};
/***/ },
/* 8 */
/***/ function(module, exports) {
"use strict";
exports["default"] = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
exports.__esModule = true;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var _Object$assign = __webpack_require__(10)["default"];
exports["default"] = _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;
};
exports.__esModule = true;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(11), __esModule: true };
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(12);
module.exports = __webpack_require__(6).core.Object.assign;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $def = __webpack_require__(13);
$def($def.S, 'Object', {assign: __webpack_require__(14)});
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(6)
, global = $.g
, core = $.core
, isFunction = $.isFunction;
function ctx(fn, that){
return function(){
return fn.apply(that, arguments);
};
}
// type bitmap
$def.F = 1; // forced
$def.G = 2; // global
$def.S = 4; // static
$def.P = 8; // proto
$def.B = 16; // bind
$def.W = 32; // wrap
function $def(type, name, source){
var key, own, out, exp
, isGlobal = type & $def.G
, isProto = type & $def.P
, target = isGlobal ? global : type & $def.S
? global[name] : (global[name] || {}).prototype
, exports = isGlobal ? core : core[name] || (core[name] = {});
if(isGlobal)source = name;
for(key in source){
// contains in native
own = !(type & $def.F) && target && key in target;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
if(isGlobal && !isFunction(target[key]))exp = source[key];
// bind timers to global for call from export context
else if(type & $def.B && own)exp = ctx(out, global);
// wrap global constructors for prevent change them in library
else if(type & $def.W && target[key] == out)!function(C){
exp = function(param){
return this instanceof C ? new C(param) : C(param);
};
exp.prototype = C.prototype;
}(out);
else exp = isProto && isFunction(out) ? ctx(Function.call, out) : out;
// export
exports[key] = exp;
if(isProto)(exports.prototype || (exports.prototype = {}))[key] = out;
}
}
module.exports = $def;
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(6)
, enumKeys = __webpack_require__(15);
// 19.1.2.1 Object.assign(target, source, ...)
/* eslint-disable no-unused-vars */
module.exports = Object.assign || function assign(target, source){
/* eslint-enable no-unused-vars */
var T = Object($.assertDefined(target))
, l = arguments.length
, i = 1;
while(l > i){
var S = $.ES5Object(arguments[i++])
, keys = enumKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)T[key = keys[j++]] = S[key];
}
return T;
};
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(6);
module.exports = function(it){
var keys = $.getKeys(it)
, getDesc = $.getDesc
, getSymbols = $.getSymbols;
if(getSymbols)$.each.call(getSymbols(it), function(key){
if(getDesc(it, key).enumerable)keys.push(key);
});
return keys;
};
/***/ },
/* 16 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_16__;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2015 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
(function () {
'use strict';
function classNames () {
var classes = '';
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if ('string' === argType || 'number' === argType) {
classes += ' ' + arg;
} else if (Array.isArray(arg)) {
classes += ' ' + classNames.apply(null, arg);
} else if ('object' === argType) {
for (var key in arg) {
if (arg.hasOwnProperty(key) && arg[key]) {
classes += ' ' + key;
}
}
}
}
return classes.substr(1);
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true){
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ },
/* 18 */
/***/ function(module, exports) {
"use strict";
exports["default"] = function (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;
}
};
exports.__esModule = true;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _PanelGroup = __webpack_require__(20);
var _PanelGroup2 = _interopRequireDefault(_PanelGroup);
var Accordion = _react2['default'].createClass({
displayName: 'Accordion',
render: function render() {
return _react2['default'].createElement(
_PanelGroup2['default'],
_extends({}, this.props, { accordion: true }),
this.props.children
);
}
});
exports['default'] = Accordion;
module.exports = exports['default'];
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/* eslint react/prop-types: [2, {ignore: "bsStyle"}] */
/* BootstrapMixin contains `bsStyle` type validation */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var PanelGroup = _react2['default'].createClass({
displayName: 'PanelGroup',
mixins: [_BootstrapMixin2['default']],
propTypes: {
accordion: _react2['default'].PropTypes.bool,
activeKey: _react2['default'].PropTypes.any,
className: _react2['default'].PropTypes.string,
children: _react2['default'].PropTypes.node,
defaultActiveKey: _react2['default'].PropTypes.any,
onSelect: _react2['default'].PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'panel-group'
};
},
getInitialState: function getInitialState() {
var defaultActiveKey = this.props.defaultActiveKey;
return {
activeKey: defaultActiveKey
};
},
render: function render() {
var classes = this.getBsClassSet();
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes), onSelect: null }),
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderPanel)
);
},
renderPanel: function renderPanel(child, index) {
var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey;
var props = {
bsStyle: child.props.bsStyle || this.props.bsStyle,
key: child.key ? child.key : index,
ref: child.ref
};
if (this.props.accordion) {
props.collapsible = true;
props.expanded = child.props.eventKey === activeKey;
props.onSelect = this.handleSelect;
}
return _react.cloneElement(child, props);
},
shouldComponentUpdate: function shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleSelect: function handleSelect(e, key) {
e.preventDefault();
if (this.props.onSelect) {
this._isChanging = true;
this.props.onSelect(key);
this._isChanging = false;
}
if (this.state.activeKey === key) {
key = null;
}
this.setState({
activeKey: key
});
}
});
exports['default'] = PanelGroup;
module.exports = exports['default'];
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _styleMaps = __webpack_require__(22);
var _styleMaps2 = _interopRequireDefault(_styleMaps);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var BootstrapMixin = {
propTypes: {
/**
* bootstrap className
* @private
*/
bsClass: _utilsCustomPropTypes2['default'].keyOf(_styleMaps2['default'].CLASSES),
/**
* Style variants
* @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")}
*/
bsStyle: _utilsCustomPropTypes2['default'].keyOf(_styleMaps2['default'].STYLES),
/**
* Size variants
* @type {("xsmall"|"small"|"medium"|"large")}
*/
bsSize: _utilsCustomPropTypes2['default'].keyOf(_styleMaps2['default'].SIZES)
},
getBsClassSet: function getBsClassSet() {
var classes = {};
var bsClass = this.props.bsClass && _styleMaps2['default'].CLASSES[this.props.bsClass];
if (bsClass) {
classes[bsClass] = true;
var prefix = bsClass + '-';
var bsSize = this.props.bsSize && _styleMaps2['default'].SIZES[this.props.bsSize];
if (bsSize) {
classes[prefix + bsSize] = true;
}
var bsStyle = this.props.bsStyle && _styleMaps2['default'].STYLES[this.props.bsStyle];
if (this.props.bsStyle) {
classes[prefix + bsStyle] = true;
}
}
return classes;
},
prefixClass: function prefixClass(subClass) {
return _styleMaps2['default'].CLASSES[this.props.bsClass] + '-' + subClass;
}
};
exports['default'] = BootstrapMixin;
module.exports = exports['default'];
/***/ },
/* 22 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var styleMaps = {
CLASSES: {
'alert': 'alert',
'button': 'btn',
'button-group': 'btn-group',
'button-toolbar': 'btn-toolbar',
'column': 'col',
'input-group': 'input-group',
'form': 'form',
'glyphicon': 'glyphicon',
'label': 'label',
'thumbnail': 'thumbnail',
'list-group-item': 'list-group-item',
'panel': 'panel',
'panel-group': 'panel-group',
'pagination': 'pagination',
'progress-bar': 'progress-bar',
'nav': 'nav',
'navbar': 'navbar',
'modal': 'modal',
'row': 'row',
'well': 'well'
},
STYLES: {
'default': 'default',
'primary': 'primary',
'success': 'success',
'info': 'info',
'warning': 'warning',
'danger': 'danger',
'link': 'link',
'inline': 'inline',
'tabs': 'tabs',
'pills': 'pills'
},
addStyle: function addStyle(name) {
styleMaps.STYLES[name] = name;
},
SIZES: {
'large': 'lg',
'medium': 'md',
'small': 'sm',
'xsmall': 'xs'
},
GLYPHS: ['asterisk', 'plus', 'euro', 'eur', 'minus', 'cloud', 'envelope', 'pencil', 'glass', 'music', 'search', 'heart', 'star', 'star-empty', 'user', 'film', 'th-large', 'th', 'th-list', 'ok', 'remove', 'zoom-in', 'zoom-out', 'off', 'signal', 'cog', 'trash', 'home', 'file', 'time', 'road', 'download-alt', 'download', 'upload', 'inbox', 'play-circle', 'repeat', 'refresh', 'list-alt', 'lock', 'flag', 'headphones', 'volume-off', 'volume-down', 'volume-up', 'qrcode', 'barcode', 'tag', 'tags', 'book', 'bookmark', 'print', 'camera', 'font', 'bold', 'italic', 'text-height', 'text-width', 'align-left', 'align-center', 'align-right', 'align-justify', 'list', 'indent-left', 'indent-right', 'facetime-video', 'picture', 'map-marker', 'adjust', 'tint', 'edit', 'share', 'check', 'move', 'step-backward', 'fast-backward', 'backward', 'play', 'pause', 'stop', 'forward', 'fast-forward', 'step-forward', 'eject', 'chevron-left', 'chevron-right', 'plus-sign', 'minus-sign', 'remove-sign', 'ok-sign', 'question-sign', 'info-sign', 'screenshot', 'remove-circle', 'ok-circle', 'ban-circle', 'arrow-left', 'arrow-right', 'arrow-up', 'arrow-down', 'share-alt', 'resize-full', 'resize-small', 'exclamation-sign', 'gift', 'leaf', 'fire', 'eye-open', 'eye-close', 'warning-sign', 'plane', 'calendar', 'random', 'comment', 'magnet', 'chevron-up', 'chevron-down', 'retweet', 'shopping-cart', 'folder-close', 'folder-open', 'resize-vertical', 'resize-horizontal', 'hdd', 'bullhorn', 'bell', 'certificate', 'thumbs-up', 'thumbs-down', 'hand-right', 'hand-left', 'hand-up', 'hand-down', 'circle-arrow-right', 'circle-arrow-left', 'circle-arrow-up', 'circle-arrow-down', 'globe', 'wrench', 'tasks', 'filter', 'briefcase', 'fullscreen', 'dashboard', 'paperclip', 'heart-empty', 'link', 'phone', 'pushpin', 'usd', 'gbp', 'sort', 'sort-by-alphabet', 'sort-by-alphabet-alt', 'sort-by-order', 'sort-by-order-alt', 'sort-by-attributes', 'sort-by-attributes-alt', 'unchecked', 'expand', 'collapse-down', 'collapse-up', 'log-in', 'flash', 'log-out', 'new-window', 'record', 'save', 'open', 'saved', 'import', 'export', 'send', 'floppy-disk', 'floppy-saved', 'floppy-remove', 'floppy-save', 'floppy-open', 'credit-card', 'transfer', 'cutlery', 'header', 'compressed', 'earphone', 'phone-alt', 'tower', 'stats', 'sd-video', 'hd-video', 'subtitles', 'sound-stereo', 'sound-dolby', 'sound-5-1', 'sound-6-1', 'sound-7-1', 'copyright-mark', 'registration-mark', 'cloud-download', 'cloud-upload', 'tree-conifer', 'tree-deciduous', 'cd', 'save-file', 'open-file', 'level-up', 'copy', 'paste', 'alert', 'equalizer', 'king', 'queen', 'pawn', 'bishop', 'knight', 'baby-formula', 'tent', 'blackboard', 'bed', 'apple', 'erase', 'hourglass', 'lamp', 'duplicate', 'piggy-bank', 'scissors', 'bitcoin', 'yen', 'ruble', 'scale', 'ice-lolly', 'ice-lolly-tasted', 'education', 'option-horizontal', 'option-vertical', 'menu-hamburger', 'modal-window', 'oil', 'grain', 'sunglasses', 'text-size', 'text-color', 'text-background', 'object-align-top', 'object-align-bottom', 'object-align-horizontal', 'object-align-left', 'object-align-vertical', 'object-align-right', 'triangle-right', 'triangle-left', 'triangle-bottom', 'triangle-top', 'console', 'superscript', 'subscript', 'menu-left', 'menu-right', 'menu-down', 'menu-up']
};
exports['default'] = styleMaps;
module.exports = exports['default'];
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _Object$keys = __webpack_require__(24)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var ANONYMOUS = '<<anonymous>>';
var CustomPropTypes = {
isRequiredForA11y: function isRequiredForA11y(propType) {
return function (props, propName, componentName) {
if (props[propName] === null) {
return new Error('The prop `' + propName + '` is required to make ' + componentName + ' accessible ' + 'for users using assistive technologies such as screen readers `');
}
return propType(props, propName, componentName);
};
},
/**
* Checks whether a prop provides a DOM element
*
* The element can be provided in two forms:
* - Directly passed
* - Or passed an object that has a `render` method
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
mountable: createMountableChecker(),
/**
* Checks whether a prop provides a type of element.
*
* The type of element can be provided in two forms:
* - tag name (string)
* - a return value of React.createClass(...)
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
elementType: createElementTypeChecker(),
/**
* Checks whether a prop matches a key of an associated object
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
keyOf: createKeyOfChecker,
/**
* Checks if only one of the listed properties is in use. An error is given
* if multiple have a value
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
singlePropFrom: createSinglePropFromChecker,
all: all
};
function errMsg(props, propName, componentName, msgContinuation) {
return 'Invalid prop \'' + propName + '\' of value \'' + props[propName] + '\'' + (' supplied to \'' + componentName + '\'' + msgContinuation);
}
/**
* Create chain-able isRequired validator
*
* Largely copied directly from:
* https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94
*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
if (isRequired) {
return new Error('Required prop \'' + propName + '\' was not specified in \'' + componentName + '\'.');
}
} else {
return validate(props, propName, componentName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createMountableChecker() {
function validate(props, propName, componentName) {
if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) {
return new Error(errMsg(props, propName, componentName, ', expected a DOM element or an object that has a `render` method'));
}
}
return createChainableTypeChecker(validate);
}
function createKeyOfChecker(obj) {
function validate(props, propName, componentName) {
var propValue = props[propName];
if (!obj.hasOwnProperty(propValue)) {
var valuesString = JSON.stringify(_Object$keys(obj));
return new Error(errMsg(props, propName, componentName, ', expected one of ' + valuesString + '.'));
}
}
return createChainableTypeChecker(validate);
}
function createSinglePropFromChecker(arrOfProps) {
function validate(props, propName, componentName) {
var usedPropCount = arrOfProps.map(function (listedProp) {
return props[listedProp];
}).reduce(function (acc, curr) {
return acc + (curr !== undefined ? 1 : 0);
}, 0);
if (usedPropCount > 1) {
var first = arrOfProps[0];
var others = arrOfProps.slice(1);
var message = others.join(', ') + ' and ' + first;
return new Error('Invalid prop \'' + propName + '\', only one of the following ' + ('may be provided: ' + message));
}
}
return validate;
}
function all(propTypes) {
if (propTypes === undefined) {
throw new Error('No validations provided');
}
if (!(propTypes instanceof Array)) {
throw new Error('Invalid argument must be an array');
}
if (propTypes.length === 0) {
throw new Error('No validations provided');
}
return function (props, propName, componentName) {
for (var i = 0; i < propTypes.length; i++) {
var result = propTypes[i](props, propName, componentName);
if (result !== undefined && result !== null) {
return result;
}
}
};
}
function createElementTypeChecker() {
function validate(props, propName, componentName) {
var errBeginning = errMsg(props, propName, componentName, '. Expected an Element `type`');
if (typeof props[propName] !== 'function') {
if (_react2['default'].isValidElement(props[propName])) {
return new Error(errBeginning + ', not an actual Element');
}
if (typeof props[propName] !== 'string') {
return new Error(errBeginning + ' such as a tag name or return value of React.createClass(...)');
}
}
}
return createChainableTypeChecker(validate);
}
exports['default'] = CustomPropTypes;
module.exports = exports['default'];
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(25), __esModule: true };
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(26);
module.exports = __webpack_require__(6).core.Object.keys;
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
var $ = __webpack_require__(6)
, $def = __webpack_require__(13)
, isObject = $.isObject
, toObject = $.toObject;
$.each.call(('freeze,seal,preventExtensions,isFrozen,isSealed,isExtensible,' +
'getOwnPropertyDescriptor,getPrototypeOf,keys,getOwnPropertyNames').split(',')
, function(KEY, ID){
var fn = ($.core.Object || {})[KEY] || Object[KEY]
, forced = 0
, method = {};
method[KEY] = ID == 0 ? function freeze(it){
return isObject(it) ? fn(it) : it;
} : ID == 1 ? function seal(it){
return isObject(it) ? fn(it) : it;
} : ID == 2 ? function preventExtensions(it){
return isObject(it) ? fn(it) : it;
} : ID == 3 ? function isFrozen(it){
return isObject(it) ? fn(it) : true;
} : ID == 4 ? function isSealed(it){
return isObject(it) ? fn(it) : true;
} : ID == 5 ? function isExtensible(it){
return isObject(it) ? fn(it) : false;
} : ID == 6 ? function getOwnPropertyDescriptor(it, key){
return fn(toObject(it), key);
} : ID == 7 ? function getPrototypeOf(it){
return fn(Object($.assertDefined(it)));
} : ID == 8 ? function keys(it){
return fn(toObject(it));
} : __webpack_require__(27).get;
try {
fn('z');
} catch(e){
forced = 1;
}
$def($def.S + $def.F * forced, 'Object', method);
});
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var $ = __webpack_require__(6)
, toString = {}.toString
, getNames = $.getNames;
var windowNames = typeof window == 'object' && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
function getWindowNames(it){
try {
return getNames(it);
} catch(e){
return windowNames.slice();
}
}
module.exports.get = function getOwnPropertyNames(it){
if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it);
return getNames($.toObject(it));
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
/**
* Maps children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The mapFunction provided index will be normalised to the components mapped,
* so an invalid component would not increase the index.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapValidComponents(children, func, context) {
var index = 0;
return _react2['default'].Children.map(children, function (child) {
if (_react2['default'].isValidElement(child)) {
var lastIndex = index;
index++;
return func.call(context, child, lastIndex);
}
return child;
});
}
/**
* Iterates through children that are typically specified as `props.children`,
* but only iterates over children that are "valid components".
*
* The provided forEachFunc(child, index) will be called for each
* leaf child with the index reflecting the position relative to "valid components".
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc.
* @param {*} forEachContext Context for forEachContext.
*/
function forEachValidComponents(children, func, context) {
var index = 0;
return _react2['default'].Children.forEach(children, function (child) {
if (_react2['default'].isValidElement(child)) {
func.call(context, child, index);
index++;
}
});
}
/**
* Count the number of "valid components" in the Children container.
*
* @param {?*} children Children tree container.
* @returns {number}
*/
function numberOfValidComponents(children) {
var count = 0;
_react2['default'].Children.forEach(children, function (child) {
if (_react2['default'].isValidElement(child)) {
count++;
}
});
return count;
}
/**
* Determine if the Child container has one or more "valid components".
*
* @param {?*} children Children tree container.
* @returns {boolean}
*/
function hasValidComponent(children) {
var hasValid = false;
_react2['default'].Children.forEach(children, function (child) {
if (!hasValid && _react2['default'].isValidElement(child)) {
hasValid = true;
}
});
return hasValid;
}
exports['default'] = {
map: mapValidComponents,
forEach: forEachValidComponents,
numberOf: numberOfValidComponents,
hasValidComponent: hasValidComponent
};
module.exports = exports['default'];
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _AffixMixin = __webpack_require__(30);
var _AffixMixin2 = _interopRequireDefault(_AffixMixin);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var Affix = _react2['default'].createClass({
displayName: 'Affix',
statics: {
domUtils: _utilsDomUtils2['default']
},
mixins: [_AffixMixin2['default']],
render: function render() {
var holderStyle = { top: this.state.affixPositionTop };
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, this.state.affixClass),
style: holderStyle }),
this.props.children
);
}
});
exports['default'] = Affix;
module.exports = exports['default'];
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsEventListener = __webpack_require__(32);
var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener);
var AffixMixin = {
propTypes: {
offset: _react2['default'].PropTypes.number,
offsetTop: _react2['default'].PropTypes.number,
offsetBottom: _react2['default'].PropTypes.number
},
getInitialState: function getInitialState() {
return {
affixClass: 'affix-top'
};
},
getPinnedOffset: function getPinnedOffset(DOMNode) {
if (this.pinnedOffset) {
return this.pinnedOffset;
}
DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, '');
DOMNode.className += DOMNode.className.length ? ' affix' : 'affix';
this.pinnedOffset = _utilsDomUtils2['default'].getOffset(DOMNode).top - window.pageYOffset;
return this.pinnedOffset;
},
checkPosition: function checkPosition() {
var DOMNode = undefined,
scrollHeight = undefined,
scrollTop = undefined,
position = undefined,
offsetTop = undefined,
offsetBottom = undefined,
affix = undefined,
affixType = undefined,
affixPositionTop = undefined;
// TODO: or not visible
if (!this.isMounted()) {
return;
}
DOMNode = _react2['default'].findDOMNode(this);
scrollHeight = document.documentElement.offsetHeight;
scrollTop = window.pageYOffset;
position = _utilsDomUtils2['default'].getOffset(DOMNode);
if (this.affixed === 'top') {
position.top += scrollTop;
}
offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset;
offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset;
if (offsetTop == null && offsetBottom == null) {
return;
}
if (offsetTop == null) {
offsetTop = 0;
}
if (offsetBottom == null) {
offsetBottom = 0;
}
if (this.unpin != null && scrollTop + this.unpin <= position.top) {
affix = false;
} else if (offsetBottom != null && position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom) {
affix = 'bottom';
} else if (offsetTop != null && scrollTop <= offsetTop) {
affix = 'top';
} else {
affix = false;
}
if (this.affixed === affix) {
return;
}
if (this.unpin != null) {
DOMNode.style.top = '';
}
affixType = 'affix' + (affix ? '-' + affix : '');
this.affixed = affix;
this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null;
if (affix === 'bottom') {
DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom');
affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - _utilsDomUtils2['default'].getOffset(DOMNode).top;
}
this.setState({
affixClass: affixType,
affixPositionTop: affixPositionTop
});
},
checkPositionWithEventLoop: function checkPositionWithEventLoop() {
setTimeout(this.checkPosition, 0);
},
componentDidMount: function componentDidMount() {
this._onWindowScrollListener = _utilsEventListener2['default'].listen(window, 'scroll', this.checkPosition);
this._onDocumentClickListener = _utilsEventListener2['default'].listen(_utilsDomUtils2['default'].ownerDocument(this), 'click', this.checkPositionWithEventLoop);
},
componentWillUnmount: function componentWillUnmount() {
if (this._onWindowScrollListener) {
this._onWindowScrollListener.remove();
}
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
},
componentDidUpdate: function componentDidUpdate(prevProps, prevState) {
if (prevState.affixClass === this.state.affixClass) {
this.checkPositionWithEventLoop();
}
}
};
exports['default'] = AffixMixin;
module.exports = exports['default'];
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var canUseDom = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Get elements owner document
*
* @param {ReactComponent|HTMLElement} componentOrElement
* @returns {HTMLElement}
*/
function ownerDocument(componentOrElement) {
var elem = _react2['default'].findDOMNode(componentOrElement);
return elem && elem.ownerDocument || document;
}
function ownerWindow(componentOrElement) {
var doc = ownerDocument(componentOrElement);
return doc.defaultView ? doc.defaultView : doc.parentWindow;
}
/**
* get the active element, safe in IE
* @return {HTMLElement}
*/
function getActiveElement(componentOrElement) {
var doc = ownerDocument(componentOrElement);
try {
return doc.activeElement || doc.body;
} catch (e) {
return doc.body;
}
}
/**
* Shortcut to compute element style
*
* @param {HTMLElement} elem
* @returns {CssStyle}
*/
function getComputedStyles(elem) {
return ownerDocument(elem).defaultView.getComputedStyle(elem, null);
}
/**
* Get elements offset
*
* TODO: REMOVE JQUERY!
*
* @param {HTMLElement} DOMNode
* @returns {{top: number, left: number}}
*/
function getOffset(DOMNode) {
if (window.jQuery) {
return window.jQuery(DOMNode).offset();
}
var docElem = ownerDocument(DOMNode).documentElement;
var box = { top: 0, left: 0 };
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if (typeof DOMNode.getBoundingClientRect !== 'undefined') {
box = DOMNode.getBoundingClientRect();
}
return {
top: box.top + window.pageYOffset - docElem.clientTop,
left: box.left + window.pageXOffset - docElem.clientLeft
};
}
/**
* Get elements position
*
* TODO: REMOVE JQUERY!
*
* @param {HTMLElement} elem
* @param {HTMLElement?} offsetParent
* @returns {{top: number, left: number}}
*/
function getPosition(elem, offsetParent) {
var offset = undefined,
parentOffset = undefined;
if (window.jQuery) {
if (!offsetParent) {
return window.jQuery(elem).position();
}
offset = window.jQuery(elem).offset();
parentOffset = window.jQuery(offsetParent).offset();
// Get element offset relative to offsetParent
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if (getComputedStyles(elem).position === 'fixed') {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
if (!offsetParent) {
// Get *real* offsetParent
offsetParent = offsetParentFunc(elem);
}
// Get correct offsets
offset = getOffset(elem);
if (offsetParent.nodeName !== 'HTML') {
parentOffset = getOffset(offsetParent);
}
// Add offsetParent borders
parentOffset.top += parseInt(getComputedStyles(offsetParent).borderTopWidth, 10);
parentOffset.left += parseInt(getComputedStyles(offsetParent).borderLeftWidth, 10);
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - parseInt(getComputedStyles(elem).marginTop, 10),
left: offset.left - parentOffset.left - parseInt(getComputedStyles(elem).marginLeft, 10)
};
}
/**
* Get parent element
*
* @param {HTMLElement?} elem
* @returns {HTMLElement}
*/
function offsetParentFunc(elem) {
var docElem = ownerDocument(elem).documentElement;
var offsetParent = elem.offsetParent || docElem;
while (offsetParent && (offsetParent.nodeName !== 'HTML' && getComputedStyles(offsetParent).position === 'static')) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
}
/**
* Cross browser .contains() polyfill
* @param {HTMLElement} elem
* @param {HTMLElement} inner
* @return {bool}
*/
function contains(elem, inner) {
function ie8Contains(root, node) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
return elem && elem.contains ? elem.contains(inner) : elem && elem.compareDocumentPosition ? elem === inner || !!(elem.compareDocumentPosition(inner) & 16) : ie8Contains(elem, inner);
}
exports['default'] = {
canUseDom: canUseDom,
contains: contains,
ownerWindow: ownerWindow,
ownerDocument: ownerDocument,
getComputedStyles: getComputedStyles,
getOffset: getOffset,
getPosition: getPosition,
activeElement: getActiveElement,
offsetParent: offsetParentFunc
};
module.exports = exports['default'];
/***/ },
/* 32 */
/***/ function(module, exports) {
/**
* Copyright 2013-2014 Facebook, Inc.
*
* This file contains a modified version of:
* https://github.com/facebook/react/blob/v0.12.0/src/vendor/stubs/EventListener.js
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* TODO: remove in favour of solution provided by:
* https://github.com/facebook/react/issues/285
*/
/**
* Does not take into account specific nature of platform.
*/
'use strict';
exports.__esModule = true;
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function listen(target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function remove() {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function remove() {
target.detachEvent('on' + eventType, callback);
}
};
}
}
};
exports['default'] = EventListener;
module.exports = exports['default'];
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var Alert = _react2['default'].createClass({
displayName: 'Alert',
mixins: [_BootstrapMixin2['default']],
propTypes: {
onDismiss: _react2['default'].PropTypes.func,
dismissAfter: _react2['default'].PropTypes.number,
closeLabel: _react2['default'].PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'alert',
bsStyle: 'info',
closeLabel: 'Close Alert'
};
},
renderDismissButton: function renderDismissButton() {
return _react2['default'].createElement(
'button',
{
type: 'button',
className: 'close',
'aria-label': this.props.closeLabel,
onClick: this.props.onDismiss },
_react2['default'].createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
);
},
render: function render() {
var classes = this.getBsClassSet();
var isDismissable = !!this.props.onDismiss;
classes['alert-dismissable'] = isDismissable;
return _react2['default'].createElement(
'div',
_extends({}, this.props, { role: 'alert', className: _classnames2['default'](this.props.className, classes) }),
isDismissable ? this.renderDismissButton() : null,
this.props.children
);
},
componentDidMount: function componentDidMount() {
if (this.props.dismissAfter && this.props.onDismiss) {
this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter);
}
},
componentWillUnmount: function componentWillUnmount() {
clearTimeout(this.dismissTimer);
}
});
exports['default'] = Alert;
module.exports = exports['default'];
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var Badge = _react2['default'].createClass({
displayName: 'Badge',
propTypes: {
pullRight: _react2['default'].PropTypes.bool
},
hasContent: function hasContent() {
return _utilsValidComponentChildren2['default'].hasValidComponent(this.props.children) || _react2['default'].Children.count(this.props.children) > 1 || typeof this.props.children === 'string' || typeof this.props.children === 'number';
},
render: function render() {
var classes = {
'pull-right': this.props.pullRight,
'badge': this.hasContent()
};
return _react2['default'].createElement(
'span',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = Badge;
module.exports = exports['default'];
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var _ButtonInput = __webpack_require__(36);
var _ButtonInput2 = _interopRequireDefault(_ButtonInput);
var Button = _react2['default'].createClass({
displayName: 'Button',
mixins: [_BootstrapMixin2['default']],
propTypes: {
active: _react2['default'].PropTypes.bool,
disabled: _react2['default'].PropTypes.bool,
block: _react2['default'].PropTypes.bool,
navItem: _react2['default'].PropTypes.bool,
navDropdown: _react2['default'].PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: _utilsCustomPropTypes2['default'].elementType,
href: _react2['default'].PropTypes.string,
target: _react2['default'].PropTypes.string,
/**
* Defines HTML button type Attribute
* @type {("button"|"reset"|"submit")}
*/
type: _react2['default'].PropTypes.oneOf(_ButtonInput2['default'].types)
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'button',
bsStyle: 'default'
};
},
render: function render() {
var classes = this.props.navDropdown ? {} : this.getBsClassSet();
var renderFuncName = undefined;
classes = _extends({
active: this.props.active,
'btn-block': this.props.block
}, classes);
if (this.props.navItem) {
return this.renderNavItem(classes);
}
renderFuncName = this.props.href || this.props.target || this.props.navDropdown ? 'renderAnchor' : 'renderButton';
return this[renderFuncName](classes);
},
renderAnchor: function renderAnchor(classes) {
var Component = this.props.componentClass || 'a';
var href = this.props.href || '#';
classes.disabled = this.props.disabled;
return _react2['default'].createElement(
Component,
_extends({}, this.props, {
href: href,
className: _classnames2['default'](this.props.className, classes),
role: 'button' }),
this.props.children
);
},
renderButton: function renderButton(classes) {
var Component = this.props.componentClass || 'button';
return _react2['default'].createElement(
Component,
_extends({}, this.props, {
type: this.props.type || 'button',
className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
},
renderNavItem: function renderNavItem(classes) {
var liClasses = {
active: this.props.active
};
return _react2['default'].createElement(
'li',
{ className: _classnames2['default'](liClasses) },
this.renderAnchor(classes)
);
}
});
exports['default'] = Button;
module.exports = exports['default'];
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _Button = __webpack_require__(35);
var _Button2 = _interopRequireDefault(_Button);
var _FormGroup = __webpack_require__(38);
var _FormGroup2 = _interopRequireDefault(_FormGroup);
var _InputBase2 = __webpack_require__(39);
var _InputBase3 = _interopRequireDefault(_InputBase2);
var _utilsChildrenValueInputValidation = __webpack_require__(40);
var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation);
var ButtonInput = (function (_InputBase) {
_inherits(ButtonInput, _InputBase);
function ButtonInput() {
_classCallCheck(this, ButtonInput);
_InputBase.apply(this, arguments);
}
ButtonInput.prototype.renderFormGroup = function renderFormGroup(children) {
var _props = this.props;
var bsStyle = _props.bsStyle;
var value = _props.value;
var other = _objectWithoutProperties(_props, ['bsStyle', 'value']);
return _react2['default'].createElement(
_FormGroup2['default'],
other,
children
);
};
ButtonInput.prototype.renderInput = function renderInput() {
var _props2 = this.props;
var children = _props2.children;
var value = _props2.value;
var other = _objectWithoutProperties(_props2, ['children', 'value']);
var val = children ? children : value;
return _react2['default'].createElement(_Button2['default'], _extends({}, other, { componentClass: 'input', ref: 'input', key: 'input', value: val }));
};
return ButtonInput;
})(_InputBase3['default']);
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: _react2['default'].PropTypes.oneOf(ButtonInput.types),
bsStyle: function bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: _utilsChildrenValueInputValidation2['default'],
value: _utilsChildrenValueInputValidation2['default']
};
exports['default'] = ButtonInput;
module.exports = exports['default'];
/***/ },
/* 37 */
/***/ function(module, exports) {
"use strict";
exports["default"] = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
exports.__esModule = true;
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var FormGroup = (function (_React$Component) {
_inherits(FormGroup, _React$Component);
function FormGroup() {
_classCallCheck(this, FormGroup);
_React$Component.apply(this, arguments);
}
FormGroup.prototype.render = function render() {
var classes = {
'form-group': !this.props.standalone,
'form-group-lg': !this.props.standalone && this.props.bsSize === 'large',
'form-group-sm': !this.props.standalone && this.props.bsSize === 'small',
'has-feedback': this.props.hasFeedback,
'has-success': this.props.bsStyle === 'success',
'has-warning': this.props.bsStyle === 'warning',
'has-error': this.props.bsStyle === 'error'
};
return _react2['default'].createElement(
'div',
{ className: _classnames2['default'](classes, this.props.groupClassName) },
this.props.children
);
};
return FormGroup;
})(_react2['default'].Component);
FormGroup.defaultProps = {
standalone: false
};
FormGroup.propTypes = {
standalone: _react2['default'].PropTypes.bool,
hasFeedback: _react2['default'].PropTypes.bool,
bsSize: function bsSize(props) {
if (props.standalone && props.bsSize !== undefined) {
return new Error('bsSize will not be used when `standalone` is set.');
}
return _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']).apply(null, arguments);
},
bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']),
groupClassName: _react2['default'].PropTypes.string
};
exports['default'] = FormGroup;
module.exports = exports['default'];
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _FormGroup = __webpack_require__(38);
var _FormGroup2 = _interopRequireDefault(_FormGroup);
var InputBase = (function (_React$Component) {
_inherits(InputBase, _React$Component);
function InputBase() {
_classCallCheck(this, InputBase);
_React$Component.apply(this, arguments);
}
InputBase.prototype.getInputDOMNode = function getInputDOMNode() {
return _react2['default'].findDOMNode(this.refs.input);
};
InputBase.prototype.getValue = function getValue() {
if (this.props.type === 'static') {
return this.props.value;
} else if (this.props.type) {
if (this.props.type === 'select' && this.props.multiple) {
return this.getSelectedOptions();
} else {
return this.getInputDOMNode().value;
}
} else {
throw 'Cannot use getValue without specifying input type.';
}
};
InputBase.prototype.getChecked = function getChecked() {
return this.getInputDOMNode().checked;
};
InputBase.prototype.getSelectedOptions = function getSelectedOptions() {
var values = [];
Array.prototype.forEach.call(this.getInputDOMNode().getElementsByTagName('option'), function (option) {
if (option.selected) {
var value = option.getAttribute('value') || option.innerHtml;
values.push(value);
}
});
return values;
};
InputBase.prototype.isCheckboxOrRadio = function isCheckboxOrRadio() {
return this.props.type === 'checkbox' || this.props.type === 'radio';
};
InputBase.prototype.isFile = function isFile() {
return this.props.type === 'file';
};
InputBase.prototype.renderInputGroup = function renderInputGroup(children) {
var addonBefore = this.props.addonBefore ? _react2['default'].createElement(
'span',
{ className: 'input-group-addon', key: 'addonBefore' },
this.props.addonBefore
) : null;
var addonAfter = this.props.addonAfter ? _react2['default'].createElement(
'span',
{ className: 'input-group-addon', key: 'addonAfter' },
this.props.addonAfter
) : null;
var buttonBefore = this.props.buttonBefore ? _react2['default'].createElement(
'span',
{ className: 'input-group-btn' },
this.props.buttonBefore
) : null;
var buttonAfter = this.props.buttonAfter ? _react2['default'].createElement(
'span',
{ className: 'input-group-btn' },
this.props.buttonAfter
) : null;
var inputGroupClassName = undefined;
switch (this.props.bsSize) {
case 'small':
inputGroupClassName = 'input-group-sm';break;
case 'large':
inputGroupClassName = 'input-group-lg';break;
}
return addonBefore || addonAfter || buttonBefore || buttonAfter ? _react2['default'].createElement(
'div',
{ className: _classnames2['default'](inputGroupClassName, 'input-group'), key: 'input-group' },
addonBefore,
buttonBefore,
children,
addonAfter,
buttonAfter
) : children;
};
InputBase.prototype.renderIcon = function renderIcon() {
var classes = {
'glyphicon': true,
'form-control-feedback': true,
'glyphicon-ok': this.props.bsStyle === 'success',
'glyphicon-warning-sign': this.props.bsStyle === 'warning',
'glyphicon-remove': this.props.bsStyle === 'error'
};
return this.props.hasFeedback ? _react2['default'].createElement('span', { className: _classnames2['default'](classes), key: 'icon' }) : null;
};
InputBase.prototype.renderHelp = function renderHelp() {
return this.props.help ? _react2['default'].createElement(
'span',
{ className: 'help-block', key: 'help' },
this.props.help
) : null;
};
InputBase.prototype.renderCheckboxAndRadioWrapper = function renderCheckboxAndRadioWrapper(children) {
var classes = {
'checkbox': this.props.type === 'checkbox',
'radio': this.props.type === 'radio'
};
return _react2['default'].createElement(
'div',
{ className: _classnames2['default'](classes), key: 'checkboxRadioWrapper' },
children
);
};
InputBase.prototype.renderWrapper = function renderWrapper(children) {
return this.props.wrapperClassName ? _react2['default'].createElement(
'div',
{ className: this.props.wrapperClassName, key: 'wrapper' },
children
) : children;
};
InputBase.prototype.renderLabel = function renderLabel(children) {
var classes = {
'control-label': !this.isCheckboxOrRadio()
};
classes[this.props.labelClassName] = this.props.labelClassName;
return this.props.label ? _react2['default'].createElement(
'label',
{ htmlFor: this.props.id, className: _classnames2['default'](classes), key: 'label' },
children,
this.props.label
) : children;
};
InputBase.prototype.renderInput = function renderInput() {
if (!this.props.type) {
return this.props.children;
}
switch (this.props.type) {
case 'select':
return _react2['default'].createElement(
'select',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control'), ref: 'input', key: 'input' }),
this.props.children
);
case 'textarea':
return _react2['default'].createElement('textarea', _extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control'), ref: 'input', key: 'input' }));
case 'static':
return _react2['default'].createElement(
'p',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control-static'), ref: 'input', key: 'input' }),
this.props.value
);
}
var className = this.isCheckboxOrRadio() || this.isFile() ? '' : 'form-control';
return _react2['default'].createElement('input', _extends({}, this.props, { className: _classnames2['default'](this.props.className, className), ref: 'input', key: 'input' }));
};
InputBase.prototype.renderFormGroup = function renderFormGroup(children) {
return _react2['default'].createElement(
_FormGroup2['default'],
this.props,
children
);
};
InputBase.prototype.renderChildren = function renderChildren() {
return !this.isCheckboxOrRadio() ? [this.renderLabel(), this.renderWrapper([this.renderInputGroup(this.renderInput()), this.renderIcon(), this.renderHelp()])] : this.renderWrapper([this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())), this.renderHelp()]);
};
InputBase.prototype.render = function render() {
var children = this.renderChildren();
return this.renderFormGroup(children);
};
return InputBase;
})(_react2['default'].Component);
InputBase.propTypes = {
type: _react2['default'].PropTypes.string,
label: _react2['default'].PropTypes.node,
help: _react2['default'].PropTypes.node,
addonBefore: _react2['default'].PropTypes.node,
addonAfter: _react2['default'].PropTypes.node,
buttonBefore: _react2['default'].PropTypes.node,
buttonAfter: _react2['default'].PropTypes.node,
bsSize: _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']),
bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']),
hasFeedback: _react2['default'].PropTypes.bool,
id: _react2['default'].PropTypes.string,
groupClassName: _react2['default'].PropTypes.string,
wrapperClassName: _react2['default'].PropTypes.string,
labelClassName: _react2['default'].PropTypes.string,
multiple: _react2['default'].PropTypes.bool,
disabled: _react2['default'].PropTypes.bool,
value: _react2['default'].PropTypes.any
};
exports['default'] = InputBase;
module.exports = exports['default'];
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
exports['default'] = valueValidation;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _CustomPropTypes = __webpack_require__(23);
var propList = ['children', 'value'];
var typeList = [_react2['default'].PropTypes.number, _react2['default'].PropTypes.string];
function valueValidation(props, propName, componentName) {
var error = _CustomPropTypes.singlePropFrom(propList)(props, propName, componentName);
if (!error) {
var oneOfType = _react2['default'].PropTypes.oneOfType(typeList);
error = oneOfType(props, propName, componentName);
}
return error;
}
module.exports = exports['default'];
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var ButtonGroup = _react2['default'].createClass({
displayName: 'ButtonGroup',
mixins: [_BootstrapMixin2['default']],
propTypes: {
vertical: _react2['default'].PropTypes.bool,
justified: _react2['default'].PropTypes.bool,
/**
* Display block buttons, only useful when used with the "vertical" prop.
* @type {bool}
*/
block: _utilsCustomPropTypes2['default'].all([_react2['default'].PropTypes.bool, function (props, propName, componentName) {
if (props.block && !props.vertical) {
return new Error('The block property requires the vertical property to be set to have any effect');
}
}])
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'button-group'
};
},
render: function render() {
var classes = this.getBsClassSet();
classes['btn-group'] = !this.props.vertical;
classes['btn-group-vertical'] = this.props.vertical;
classes['btn-group-justified'] = this.props.justified;
classes['btn-block'] = this.props.block;
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = ButtonGroup;
module.exports = exports['default'];
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var ButtonToolbar = _react2['default'].createClass({
displayName: 'ButtonToolbar',
mixins: [_BootstrapMixin2['default']],
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'button-toolbar'
};
},
render: function render() {
var classes = this.getBsClassSet();
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
role: 'toolbar',
className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = ButtonToolbar;
module.exports = exports['default'];
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _Glyphicon = __webpack_require__(44);
var _Glyphicon2 = _interopRequireDefault(_Glyphicon);
var Carousel = _react2['default'].createClass({
displayName: 'Carousel',
mixins: [_BootstrapMixin2['default']],
propTypes: {
slide: _react2['default'].PropTypes.bool,
indicators: _react2['default'].PropTypes.bool,
interval: _react2['default'].PropTypes.number,
controls: _react2['default'].PropTypes.bool,
pauseOnHover: _react2['default'].PropTypes.bool,
wrap: _react2['default'].PropTypes.bool,
onSelect: _react2['default'].PropTypes.func,
onSlideEnd: _react2['default'].PropTypes.func,
activeIndex: _react2['default'].PropTypes.number,
defaultActiveIndex: _react2['default'].PropTypes.number,
direction: _react2['default'].PropTypes.oneOf(['prev', 'next']),
prevIcon: _react2['default'].PropTypes.node,
nextIcon: _react2['default'].PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
slide: true,
interval: 5000,
pauseOnHover: true,
wrap: true,
indicators: true,
controls: true,
prevIcon: _react2['default'].createElement(_Glyphicon2['default'], { glyph: 'chevron-left' }),
nextIcon: _react2['default'].createElement(_Glyphicon2['default'], { glyph: 'chevron-right' })
};
},
getInitialState: function getInitialState() {
return {
activeIndex: this.props.defaultActiveIndex == null ? 0 : this.props.defaultActiveIndex,
previousActiveIndex: null,
direction: null
};
},
getDirection: function getDirection(prevIndex, index) {
if (prevIndex === index) {
return null;
}
return prevIndex > index ? 'prev' : 'next';
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
var activeIndex = this.getActiveIndex();
if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) {
clearTimeout(this.timeout);
this.setState({
previousActiveIndex: activeIndex,
direction: nextProps.direction != null ? nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex)
});
}
},
componentDidMount: function componentDidMount() {
this.waitForNext();
},
componentWillUnmount: function componentWillUnmount() {
clearTimeout(this.timeout);
},
next: function next(e) {
if (e) {
e.preventDefault();
}
var index = this.getActiveIndex() + 1;
var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children);
if (index > count - 1) {
if (!this.props.wrap) {
return;
}
index = 0;
}
this.handleSelect(index, 'next');
},
prev: function prev(e) {
if (e) {
e.preventDefault();
}
var index = this.getActiveIndex() - 1;
if (index < 0) {
if (!this.props.wrap) {
return;
}
index = _utilsValidComponentChildren2['default'].numberOf(this.props.children) - 1;
}
this.handleSelect(index, 'prev');
},
pause: function pause() {
this.isPaused = true;
clearTimeout(this.timeout);
},
play: function play() {
this.isPaused = false;
this.waitForNext();
},
waitForNext: function waitForNext() {
if (!this.isPaused && this.props.slide && this.props.interval && this.props.activeIndex == null) {
this.timeout = setTimeout(this.next, this.props.interval);
}
},
handleMouseOver: function handleMouseOver() {
if (this.props.pauseOnHover) {
this.pause();
}
},
handleMouseOut: function handleMouseOut() {
if (this.isPaused) {
this.play();
}
},
render: function render() {
var classes = {
carousel: true,
slide: this.props.slide
};
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, classes),
onMouseOver: this.handleMouseOver,
onMouseOut: this.handleMouseOut }),
this.props.indicators ? this.renderIndicators() : null,
_react2['default'].createElement(
'div',
{ className: 'carousel-inner', ref: 'inner' },
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderItem)
),
this.props.controls ? this.renderControls() : null
);
},
renderPrev: function renderPrev() {
return _react2['default'].createElement(
'a',
{ className: 'left carousel-control', href: '#prev', key: 0, onClick: this.prev },
this.props.prevIcon
);
},
renderNext: function renderNext() {
return _react2['default'].createElement(
'a',
{ className: 'right carousel-control', href: '#next', key: 1, onClick: this.next },
this.props.nextIcon
);
},
renderControls: function renderControls() {
if (!this.props.wrap) {
var activeIndex = this.getActiveIndex();
var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children);
return [activeIndex !== 0 ? this.renderPrev() : null, activeIndex !== count - 1 ? this.renderNext() : null];
}
return [this.renderPrev(), this.renderNext()];
},
renderIndicator: function renderIndicator(child, index) {
var className = index === this.getActiveIndex() ? 'active' : null;
return _react2['default'].createElement('li', {
key: index,
className: className,
onClick: this.handleSelect.bind(this, index, null) });
},
renderIndicators: function renderIndicators() {
var indicators = [];
_utilsValidComponentChildren2['default'].forEach(this.props.children, function (child, index) {
indicators.push(this.renderIndicator(child, index),
// Force whitespace between indicator elements, bootstrap
// requires this for correct spacing of elements.
' ');
}, this);
return _react2['default'].createElement(
'ol',
{ className: 'carousel-indicators' },
indicators
);
},
getActiveIndex: function getActiveIndex() {
return this.props.activeIndex != null ? this.props.activeIndex : this.state.activeIndex;
},
handleItemAnimateOutEnd: function handleItemAnimateOutEnd() {
this.setState({
previousActiveIndex: null,
direction: null
}, function () {
this.waitForNext();
if (this.props.onSlideEnd) {
this.props.onSlideEnd();
}
});
},
renderItem: function renderItem(child, index) {
var activeIndex = this.getActiveIndex();
var isActive = index === activeIndex;
var isPreviousActive = this.state.previousActiveIndex != null && this.state.previousActiveIndex === index && this.props.slide;
return _react.cloneElement(child, {
active: isActive,
ref: child.ref,
key: child.key ? child.key : index,
index: index,
animateOut: isPreviousActive,
animateIn: isActive && this.state.previousActiveIndex != null && this.props.slide,
direction: this.state.direction,
onAnimateOutEnd: isPreviousActive ? this.handleItemAnimateOutEnd : null
});
},
handleSelect: function handleSelect(index, direction) {
clearTimeout(this.timeout);
var previousActiveIndex = this.getActiveIndex();
direction = direction || this.getDirection(previousActiveIndex, index);
if (this.props.onSelect) {
this.props.onSelect(index, direction);
}
if (this.props.activeIndex == null && index !== previousActiveIndex) {
if (this.state.previousActiveIndex != null) {
// If currently animating don't activate the new index.
// TODO: look into queuing this canceled call and
// animating after the current animation has ended.
return;
}
this.setState({
activeIndex: index,
previousActiveIndex: previousActiveIndex,
direction: direction
});
}
}
});
exports['default'] = Carousel;
module.exports = exports['default'];
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _styleMaps = __webpack_require__(22);
var _styleMaps2 = _interopRequireDefault(_styleMaps);
var Glyphicon = _react2['default'].createClass({
displayName: 'Glyphicon',
mixins: [_BootstrapMixin2['default']],
propTypes: {
glyph: _react2['default'].PropTypes.oneOf(_styleMaps2['default'].GLYPHS).isRequired
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'glyphicon'
};
},
render: function render() {
var classes = this.getBsClassSet();
classes['glyphicon-' + this.props.glyph] = true;
return _react2['default'].createElement(
'span',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = Glyphicon;
module.exports = exports['default'];
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsTransitionEvents = __webpack_require__(46);
var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents);
var CarouselItem = _react2['default'].createClass({
displayName: 'CarouselItem',
propTypes: {
direction: _react2['default'].PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: _react2['default'].PropTypes.func,
active: _react2['default'].PropTypes.bool,
animateIn: _react2['default'].PropTypes.bool,
animateOut: _react2['default'].PropTypes.bool,
caption: _react2['default'].PropTypes.node,
index: _react2['default'].PropTypes.number
},
getInitialState: function getInitialState() {
return {
direction: null
};
},
getDefaultProps: function getDefaultProps() {
return {
animation: true
};
},
handleAnimateOutEnd: function handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate: function componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
_utilsTransitionEvents2['default'].addEndEventListener(_react2['default'].findDOMNode(this), this.handleAnimateOutEnd);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation: function startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
},
render: function render() {
var classes = {
item: true,
active: this.props.active && !this.props.animateIn || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.children,
this.props.caption ? this.renderCaption() : null
);
},
renderCaption: function renderCaption() {
return _react2['default'].createElement(
'div',
{ className: 'carousel-caption' },
this.props.caption
);
}
});
exports['default'] = CarouselItem;
module.exports = exports['default'];
/***/ },
/* 46 */
/***/ function(module, exports) {
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This file contains a modified version of:
* https://github.com/facebook/react/blob/v0.12.0/src/addons/transitions/ReactTransitionEvents.js
*
* This source code is licensed under the BSD-style license found here:
* https://github.com/facebook/react/blob/v0.12.0/LICENSE
* An additional grant of patent rights can be found here:
* https://github.com/facebook/react/blob/v0.12.0/PATENTS
*/
'use strict';
exports.__esModule = true;
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function addEndEventListener(node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function removeEndEventListener(node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
exports['default'] = ReactTransitionEvents;
module.exports = exports['default'];
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _Object$keys = __webpack_require__(24)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _styleMaps = __webpack_require__(22);
var _styleMaps2 = _interopRequireDefault(_styleMaps);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Col = _react2['default'].createClass({
displayName: 'Col',
propTypes: {
/**
* The number of columns you wish to span
*
* for Extra small devices Phones (<768px)
*
* class-prefix `col-xs-`
*/
xs: _react2['default'].PropTypes.number,
/**
* The number of columns you wish to span
*
* for Small devices Tablets (≥768px)
*
* class-prefix `col-sm-`
*/
sm: _react2['default'].PropTypes.number,
/**
* The number of columns you wish to span
*
* for Medium devices Desktops (≥992px)
*
* class-prefix `col-md-`
*/
md: _react2['default'].PropTypes.number,
/**
* The number of columns you wish to span
*
* for Large devices Desktops (≥1200px)
*
* class-prefix `col-lg-`
*/
lg: _react2['default'].PropTypes.number,
/**
* Move columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-offset-`
*/
xsOffset: _react2['default'].PropTypes.number,
/**
* Move columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-offset-`
*/
smOffset: _react2['default'].PropTypes.number,
/**
* Move columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-offset-`
*/
mdOffset: _react2['default'].PropTypes.number,
/**
* Move columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-offset-`
*/
lgOffset: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-push-`
*/
xsPush: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-push-`
*/
smPush: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-push-`
*/
mdPush: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-push-`
*/
lgPush: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Extra small devices Phones
*
* class-prefix `col-xs-pull-`
*/
xsPull: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Small devices Tablets
*
* class-prefix `col-sm-pull-`
*/
smPull: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Medium devices Desktops
*
* class-prefix `col-md-pull-`
*/
mdPull: _react2['default'].PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Large devices Desktops
*
* class-prefix `col-lg-pull-`
*/
lgPull: _react2['default'].PropTypes.number,
/**
* You can use a custom element for this component
*/
componentClass: _utilsCustomPropTypes2['default'].elementType
},
getDefaultProps: function getDefaultProps() {
return {
componentClass: 'div'
};
},
render: function render() {
var ComponentClass = this.props.componentClass;
var classes = {};
_Object$keys(_styleMaps2['default'].SIZES).forEach(function (key) {
var size = _styleMaps2['default'].SIZES[key];
var prop = size;
var classPart = size + '-';
if (this.props[prop]) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Offset';
classPart = size + '-offset-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Push';
classPart = size + '-push-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Pull';
classPart = size + '-pull-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
}, this);
return _react2['default'].createElement(
ComponentClass,
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = Col;
module.exports = exports['default'];
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsTransitionEvents = __webpack_require__(46);
var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents);
var _utilsDeprecationWarning = __webpack_require__(49);
var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning);
var warned = false;
var CollapsibleMixin = {
propTypes: {
defaultExpanded: _react2['default'].PropTypes.bool,
expanded: _react2['default'].PropTypes.bool
},
getInitialState: function getInitialState() {
var defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : this.props.expanded != null ? this.props.expanded : false;
return {
expanded: defaultExpanded,
collapsing: false
};
},
componentWillMount: function componentWillMount() {
if (!warned) {
_utilsDeprecationWarning2['default']('CollapsibleMixin', 'Collapse Component');
warned = true;
}
},
componentWillUpdate: function componentWillUpdate(nextProps, nextState) {
var willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded;
if (willExpanded === this.isExpanded()) {
return;
}
// if the expanded state is being toggled, ensure node has a dimension value
// this is needed for the animation to work and needs to be set before
// the collapsing class is applied (after collapsing is applied the in class
// is removed and the node's dimension will be wrong)
var node = this.getCollapsibleDOMNode();
var dimension = this.dimension();
var value = '0';
if (!willExpanded) {
value = this.getCollapsibleDimensionValue();
}
node.style[dimension] = value + 'px';
this._afterWillUpdate();
},
componentDidUpdate: function componentDidUpdate(prevProps, prevState) {
// check if expanded is being toggled; if so, set collapsing
this._checkToggleCollapsing(prevProps, prevState);
// check if collapsing was turned on; if so, start animation
this._checkStartAnimation();
},
// helps enable test stubs
_afterWillUpdate: function _afterWillUpdate() {},
_checkStartAnimation: function _checkStartAnimation() {
if (!this.state.collapsing) {
return;
}
var node = this.getCollapsibleDOMNode();
var dimension = this.dimension();
var value = this.getCollapsibleDimensionValue();
// setting the dimension here starts the transition animation
var result = undefined;
if (this.isExpanded()) {
result = value + 'px';
} else {
result = '0px';
}
node.style[dimension] = result;
},
_checkToggleCollapsing: function _checkToggleCollapsing(prevProps, prevState) {
var wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded;
var isExpanded = this.isExpanded();
if (wasExpanded !== isExpanded) {
if (wasExpanded) {
this._handleCollapse();
} else {
this._handleExpand();
}
}
},
_handleExpand: function _handleExpand() {
var _this = this;
var node = this.getCollapsibleDOMNode();
var dimension = this.dimension();
var complete = function complete() {
_this._removeEndEventListener(node, complete);
// remove dimension value - this ensures the collapsible item can grow
// in dimension after initial display (such as an image loading)
node.style[dimension] = '';
_this.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
_handleCollapse: function _handleCollapse() {
var _this2 = this;
var node = this.getCollapsibleDOMNode();
var complete = function complete() {
_this2._removeEndEventListener(node, complete);
_this2.setState({
collapsing: false
});
};
this._addEndEventListener(node, complete);
this.setState({
collapsing: true
});
},
// helps enable test stubs
_addEndEventListener: function _addEndEventListener(node, complete) {
_utilsTransitionEvents2['default'].addEndEventListener(node, complete);
},
// helps enable test stubs
_removeEndEventListener: function _removeEndEventListener(node, complete) {
_utilsTransitionEvents2['default'].removeEndEventListener(node, complete);
},
dimension: function dimension() {
return typeof this.getCollapsibleDimension === 'function' ? this.getCollapsibleDimension() : 'height';
},
isExpanded: function isExpanded() {
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
getCollapsibleClassSet: function getCollapsibleClassSet(className) {
var classes = {};
if (typeof className === 'string') {
className.split(' ').forEach(function (subClasses) {
if (subClasses) {
classes[subClasses] = true;
}
});
}
classes.collapsing = this.state.collapsing;
classes.collapse = !this.state.collapsing;
classes['in'] = this.isExpanded() && !this.state.collapsing;
return classes;
}
};
exports['default'] = CollapsibleMixin;
module.exports = exports['default'];
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
exports['default'] = deprecationWarning;
var _reactLibWarning = __webpack_require__(50);
var _reactLibWarning2 = _interopRequireDefault(_reactLibWarning);
function deprecationWarning(oldname, newname, link) {
var message = oldname + ' is deprecated. Use ' + newname + ' instead.';
if (link) {
message += '\nYou can read more about it at ' + link;
}
_reactLibWarning2['default'](false, message);
}
module.exports = exports['default'];
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule warning
*/
"use strict";
var emptyFunction = __webpack_require__(51);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (true) {
warning = function(condition, format ) {for (var args=[],$__0=2,$__1=arguments.length;$__0<$__1;$__0++) args.push(arguments[$__0]);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || /^[s\W]*$/.test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];});
console.warn(message);
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/***/ },
/* 51 */
/***/ 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 emptyFunction
*/
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() {}
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function() { return this; };
emptyFunction.thatReturnsArgument = function(arg) { return arg; };
module.exports = emptyFunction;
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _Collapse = __webpack_require__(53);
var _Collapse2 = _interopRequireDefault(_Collapse);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var CollapsibleNav = _react2['default'].createClass({
displayName: 'CollapsibleNav',
mixins: [_BootstrapMixin2['default']],
propTypes: {
onSelect: _react2['default'].PropTypes.func,
activeHref: _react2['default'].PropTypes.string,
activeKey: _react2['default'].PropTypes.any,
collapsible: _react2['default'].PropTypes.bool,
expanded: _react2['default'].PropTypes.bool,
eventKey: _react2['default'].PropTypes.any
},
render: function render() {
/*
* this.props.collapsible is set in NavBar when an eventKey is supplied.
*/
var classes = this.props.collapsible ? 'navbar-collapse' : null;
var renderChildren = this.props.collapsible ? this.renderCollapsibleNavChildren : this.renderChildren;
var nav = _react2['default'].createElement(
'div',
{ eventKey: this.props.eventKey, className: _classnames2['default'](this.props.className, classes) },
_utilsValidComponentChildren2['default'].map(this.props.children, renderChildren)
);
if (this.props.collapsible) {
return _react2['default'].createElement(
_Collapse2['default'],
{ 'in': this.props.expanded },
nav
);
} else {
return nav;
}
},
getChildActiveProp: function getChildActiveProp(child) {
if (child.props.active) {
return true;
}
if (this.props.activeKey != null) {
if (child.props.eventKey === this.props.activeKey) {
return true;
}
}
if (this.props.activeHref != null) {
if (child.props.href === this.props.activeHref) {
return true;
}
}
return child.props.active;
},
renderChildren: function renderChildren(child, index) {
var key = child.key ? child.key : index;
return _react.cloneElement(child, {
activeKey: this.props.activeKey,
activeHref: this.props.activeHref,
ref: 'nocollapse_' + key,
key: key,
navItem: true
});
},
renderCollapsibleNavChildren: function renderCollapsibleNavChildren(child, index) {
var key = child.key ? child.key : index;
return _react.cloneElement(child, {
active: this.getChildActiveProp(child),
activeKey: this.props.activeKey,
activeHref: this.props.activeHref,
onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect),
ref: 'collapsible_' + key,
key: key,
navItem: true
});
}
});
exports['default'] = CollapsibleNav;
module.exports = exports['default'];
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _Transition = __webpack_require__(54);
var _Transition2 = _interopRequireDefault(_Transition);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var capitalize = function capitalize(str) {
return str[0].toUpperCase() + str.substr(1);
};
// reading a dimension prop will cause the browser to recalculate,
// which will let our animations work
var triggerBrowserReflow = function triggerBrowserReflow(node) {
return node.offsetHeight;
}; //eslint-disable-line no-unused-expressions
var MARGINS = {
height: ['marginTop', 'marginBottom'],
width: ['marginLeft', 'marginRight']
};
function getDimensionValue(dimension, elem) {
var value = elem['offset' + capitalize(dimension)];
var computedStyles = _utilsDomUtils2['default'].getComputedStyles(elem);
var margins = MARGINS[dimension];
return value + parseInt(computedStyles[margins[0]], 10) + parseInt(computedStyles[margins[1]], 10);
}
var Collapse = (function (_React$Component) {
_inherits(Collapse, _React$Component);
function Collapse(props, context) {
_classCallCheck(this, Collapse);
_React$Component.call(this, props, context);
this.onEnterListener = this.handleEnter.bind(this);
this.onEnteringListener = this.handleEntering.bind(this);
this.onEnteredListener = this.handleEntered.bind(this);
this.onExitListener = this.handleExit.bind(this);
this.onExitingListener = this.handleExiting.bind(this);
}
Collapse.prototype.render = function render() {
var enter = _utilsCreateChainedFunction2['default'](this.onEnterListener, this.props.onEnter);
var entering = _utilsCreateChainedFunction2['default'](this.onEnteringListener, this.props.onEntering);
var entered = _utilsCreateChainedFunction2['default'](this.onEnteredListener, this.props.onEntered);
var exit = _utilsCreateChainedFunction2['default'](this.onExitListener, this.props.onExit);
var exiting = _utilsCreateChainedFunction2['default'](this.onExitingListener, this.props.onExiting);
return _react2['default'].createElement(
_Transition2['default'],
_extends({
ref: 'transition'
}, this.props, {
'aria-expanded': this.props['in'],
className: this._dimension() === 'width' ? 'width' : '',
exitedClassName: 'collapse',
exitingClassName: 'collapsing',
enteredClassName: 'collapse in',
enteringClassName: 'collapsing',
onEnter: enter,
onEntering: entering,
onEntered: entered,
onExit: exit,
onExiting: exiting,
onExited: this.props.onExited
}),
this.props.children
);
};
/* -- Expanding -- */
Collapse.prototype.handleEnter = function handleEnter(elem) {
var dimension = this._dimension();
elem.style[dimension] = '0';
};
Collapse.prototype.handleEntering = function handleEntering(elem) {
var dimension = this._dimension();
elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
};
Collapse.prototype.handleEntered = function handleEntered(elem) {
var dimension = this._dimension();
elem.style[dimension] = null;
};
/* -- Collapsing -- */
Collapse.prototype.handleExit = function handleExit(elem) {
var dimension = this._dimension();
elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px';
};
Collapse.prototype.handleExiting = function handleExiting(elem) {
var dimension = this._dimension();
triggerBrowserReflow(elem);
elem.style[dimension] = '0';
};
Collapse.prototype._dimension = function _dimension() {
return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension;
};
//for testing
Collapse.prototype._getTransitionInstance = function _getTransitionInstance() {
return this.refs.transition;
};
Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) {
return elem['scroll' + capitalize(dimension)] + 'px';
};
return Collapse;
})(_react2['default'].Component);
// Explicitly copied from Transition for doc generation.
// TODO: Remove duplication once #977 is resolved.
Collapse.propTypes = {
/**
* Show the component; triggers the expand or collapse animation
*/
'in': _react2['default'].PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is collapsed
*/
unmountOnExit: _react2['default'].PropTypes.bool,
/**
* Run the expand animation when the component mounts, if it is initially
* shown
*/
transitionAppear: _react2['default'].PropTypes.bool,
/**
* Duration of the collapse animation in milliseconds, to ensure that
* finishing callbacks are fired even if the original browser transition end
* events are canceled
*/
duration: _react2['default'].PropTypes.number,
/**
* Callback fired before the component expands
*/
onEnter: _react2['default'].PropTypes.func,
/**
* Callback fired after the component starts to expand
*/
onEntering: _react2['default'].PropTypes.func,
/**
* Callback fired after the component has expanded
*/
onEntered: _react2['default'].PropTypes.func,
/**
* Callback fired before the component collapses
*/
onExit: _react2['default'].PropTypes.func,
/**
* Callback fired after the component starts to collapse
*/
onExiting: _react2['default'].PropTypes.func,
/**
* Callback fired after the component has collapsed
*/
onExited: _react2['default'].PropTypes.func,
/**
* The dimension used when collapsing, or a function that returns the
* dimension
*
* _Note: Bootstrap only partially supports 'width'!
* You will need to supply your own CSS animation for the `.width` CSS class._
*/
dimension: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.oneOf(['height', 'width']), _react2['default'].PropTypes.func]),
/**
* Function that returns the height or width of the animating DOM node
*
* Allows for providing some custom logic for how much the Collapse component
* should animate in its specified dimension. Called with the current
* dimension prop value and the DOM node.
*/
getDimensionValue: _react2['default'].PropTypes.func
};
Collapse.defaultProps = {
'in': false,
duration: 300,
unmountOnExit: false,
transitionAppear: false,
dimension: 'height',
getDimensionValue: getDimensionValue
};
exports['default'] = Collapse;
module.exports = exports['default'];
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _Object$keys = __webpack_require__(24)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsTransitionEvents = __webpack_require__(46);
var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var UNMOUNTED = 0;
exports.UNMOUNTED = UNMOUNTED;
var EXITED = 1;
exports.EXITED = EXITED;
var ENTERING = 2;
exports.ENTERING = ENTERING;
var ENTERED = 3;
exports.ENTERED = ENTERED;
var EXITING = 4;
exports.EXITING = EXITING;
var Transition = (function (_React$Component) {
_inherits(Transition, _React$Component);
function Transition(props, context) {
_classCallCheck(this, Transition);
_React$Component.call(this, props, context);
var initialStatus = undefined;
if (props['in']) {
// Start enter transition in componentDidMount.
initialStatus = props.transitionAppear ? EXITED : ENTERED;
} else {
initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED;
}
this.state = { status: initialStatus };
this.nextCallback = null;
}
Transition.prototype.componentDidMount = function componentDidMount() {
if (this.props.transitionAppear && this.props['in']) {
this.performEnter(this.props);
}
};
Transition.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var status = this.state.status;
if (nextProps['in']) {
if (status === EXITING) {
this.performEnter(nextProps);
} else if (this.props.unmountOnExit) {
if (status === UNMOUNTED) {
// Start enter transition in componentDidUpdate.
this.setState({ status: EXITED });
}
} else if (status === EXITED) {
this.performEnter(nextProps);
}
// Otherwise we're already entering or entered.
} else {
if (status === ENTERING || status === ENTERED) {
this.performExit(nextProps);
}
// Otherwise we're already exited or exiting.
}
};
Transition.prototype.componentDidUpdate = function componentDidUpdate() {
if (this.props.unmountOnExit && this.state.status === EXITED) {
// EXITED is always a transitional state to either ENTERING or UNMOUNTED
// when using unmountOnExit.
if (this.props['in']) {
this.performEnter(this.props);
} else {
this.setState({ status: UNMOUNTED });
}
}
};
Transition.prototype.componentWillUnmount = function componentWillUnmount() {
this.cancelNextCallback();
};
Transition.prototype.performEnter = function performEnter(props) {
var _this = this;
this.cancelNextCallback();
var node = _react2['default'].findDOMNode(this);
// Not this.props, because we might be about to receive new props.
props.onEnter(node);
this.safeSetState({ status: ENTERING }, function () {
_this.props.onEntering(node);
_this.onTransitionEnd(node, function () {
_this.safeSetState({ status: ENTERED }, function () {
_this.props.onEntered(node);
});
});
});
};
Transition.prototype.performExit = function performExit(props) {
var _this2 = this;
this.cancelNextCallback();
var node = _react2['default'].findDOMNode(this);
// Not this.props, because we might be about to receive new props.
props.onExit(node);
this.safeSetState({ status: EXITING }, function () {
_this2.props.onExiting(node);
_this2.onTransitionEnd(node, function () {
_this2.safeSetState({ status: EXITED }, function () {
_this2.props.onExited(node);
});
});
});
};
Transition.prototype.cancelNextCallback = function cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
};
Transition.prototype.safeSetState = function safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
this.setState(nextState, this.setNextCallback(callback));
};
Transition.prototype.setNextCallback = function setNextCallback(callback) {
var _this3 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this3.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
active = false;
};
return this.nextCallback;
};
Transition.prototype.onTransitionEnd = function onTransitionEnd(node, handler) {
this.setNextCallback(handler);
if (node) {
_utilsTransitionEvents2['default'].addEndEventListener(node, this.nextCallback);
setTimeout(this.nextCallback, this.props.duration);
} else {
setTimeout(this.nextCallback, 0);
}
};
Transition.prototype.render = function render() {
var status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
var _props = this.props;
var children = _props.children;
var className = _props.className;
var childProps = _objectWithoutProperties(_props, ['children', 'className']);
_Object$keys(Transition.propTypes).forEach(function (key) {
return delete childProps[key];
});
var transitionClassName = undefined;
if (status === EXITED) {
transitionClassName = this.props.exitedClassName;
} else if (status === ENTERING) {
transitionClassName = this.props.enteringClassName;
} else if (status === ENTERED) {
transitionClassName = this.props.enteredClassName;
} else if (status === EXITING) {
transitionClassName = this.props.exitingClassName;
}
var child = _react2['default'].Children.only(children);
return _react2['default'].cloneElement(child, _extends({}, childProps, {
className: _classnames2['default'](child.props.className, className, transitionClassName)
}));
};
return Transition;
})(_react2['default'].Component);
Transition.propTypes = {
/**
* Show the component; triggers the enter or exit animation
*/
'in': _react2['default'].PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is not shown
*/
unmountOnExit: _react2['default'].PropTypes.bool,
/**
* Run the enter animation when the component mounts, if it is initially
* shown
*/
transitionAppear: _react2['default'].PropTypes.bool,
/**
* Duration of the animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
duration: _react2['default'].PropTypes.number,
/**
* CSS class or classes applied when the component is exited
*/
exitedClassName: _react2['default'].PropTypes.string,
/**
* CSS class or classes applied while the component is exiting
*/
exitingClassName: _react2['default'].PropTypes.string,
/**
* CSS class or classes applied when the component is entered
*/
enteredClassName: _react2['default'].PropTypes.string,
/**
* CSS class or classes applied while the component is entering
*/
enteringClassName: _react2['default'].PropTypes.string,
/**
* Callback fired before the "entering" classes are applied
*/
onEnter: _react2['default'].PropTypes.func,
/**
* Callback fired after the "entering" classes are applied
*/
onEntering: _react2['default'].PropTypes.func,
/**
* Callback fired after the "enter" classes are applied
*/
onEntered: _react2['default'].PropTypes.func,
/**
* Callback fired before the "exiting" classes are applied
*/
onExit: _react2['default'].PropTypes.func,
/**
* Callback fired after the "exiting" classes are applied
*/
onExiting: _react2['default'].PropTypes.func,
/**
* Callback fired after the "exited" classes are applied
*/
onExited: _react2['default'].PropTypes.func
};
// Name the function so it is clearer in the documentation
function noop() {}
Transition.defaultProps = {
'in': false,
duration: 300,
unmountOnExit: false,
transitionAppear: false,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
exports['default'] = Transition;
/***/ },
/* 55 */
/***/ function(module, exports) {
/**
* Safe chained function
*
* Will only create a new function if needed,
* otherwise will pass back existing functions or null.
*
* @param {function} functions to chain
* @returns {function|null}
*/
'use strict';
exports.__esModule = true;
function createChainedFunction() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
return funcs.filter(function (f) {
return f != null;
}).reduce(function (acc, f) {
if (typeof f !== 'function') {
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
}
if (acc === null) {
return f;
}
return function chainedFunction() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
acc.apply(this, args);
f.apply(this, args);
};
}, null);
}
exports['default'] = createChainedFunction;
module.exports = exports['default'];
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
/* eslint react/prop-types: [2, {ignore: "bsSize"}] */
/* BootstrapMixin contains `bsSize` type validation */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _DropdownStateMixin = __webpack_require__(57);
var _DropdownStateMixin2 = _interopRequireDefault(_DropdownStateMixin);
var _Button = __webpack_require__(35);
var _Button2 = _interopRequireDefault(_Button);
var _ButtonGroup = __webpack_require__(41);
var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup);
var _DropdownMenu = __webpack_require__(58);
var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var DropdownButton = _react2['default'].createClass({
displayName: 'DropdownButton',
mixins: [_BootstrapMixin2['default'], _DropdownStateMixin2['default']],
propTypes: {
pullRight: _react2['default'].PropTypes.bool,
dropup: _react2['default'].PropTypes.bool,
title: _react2['default'].PropTypes.node,
href: _react2['default'].PropTypes.string,
id: _react2['default'].PropTypes.string,
onClick: _react2['default'].PropTypes.func,
onSelect: _react2['default'].PropTypes.func,
navItem: _react2['default'].PropTypes.bool,
noCaret: _react2['default'].PropTypes.bool,
buttonClassName: _react2['default'].PropTypes.string,
className: _react2['default'].PropTypes.string,
children: _react2['default'].PropTypes.node
},
render: function render() {
var renderMethod = this.props.navItem ? 'renderNavItem' : 'renderButtonGroup';
var caret = this.props.noCaret ? null : _react2['default'].createElement('span', { className: 'caret' });
return this[renderMethod]([_react2['default'].createElement(
_Button2['default'],
_extends({}, this.props, {
ref: 'dropdownButton',
className: _classnames2['default']('dropdown-toggle', this.props.buttonClassName),
onClick: _utilsCreateChainedFunction2['default'](this.props.onClick, this.handleDropdownClick),
key: 0,
navDropdown: this.props.navItem,
navItem: null,
title: null,
pullRight: null,
dropup: null }),
this.props.title,
' ',
caret
), _react2['default'].createElement(
_DropdownMenu2['default'],
{
ref: 'menu',
'aria-labelledby': this.props.id,
pullRight: this.props.pullRight,
key: 1 },
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderMenuItem)
)]);
},
renderButtonGroup: function renderButtonGroup(children) {
var groupClasses = {
'open': this.state.open,
'dropup': this.props.dropup
};
return _react2['default'].createElement(
_ButtonGroup2['default'],
{
bsSize: this.props.bsSize,
className: _classnames2['default'](this.props.className, groupClasses) },
children
);
},
renderNavItem: function renderNavItem(children) {
var classes = {
'dropdown': true,
'open': this.state.open,
'dropup': this.props.dropup
};
return _react2['default'].createElement(
'li',
{ className: _classnames2['default'](this.props.className, classes) },
children
);
},
renderMenuItem: function renderMenuItem(child, index) {
// Only handle the option selection if an onSelect prop has been set on the
// component or it's child, this allows a user not to pass an onSelect
// handler and have the browser preform the default action.
var handleOptionSelect = this.props.onSelect || child.props.onSelect ? this.handleOptionSelect : null;
return _react.cloneElement(child, {
// Capture onSelect events
onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, handleOptionSelect),
key: child.key ? child.key : index
});
},
handleDropdownClick: function handleDropdownClick(e) {
e.preventDefault();
this.setDropdownState(!this.state.open);
},
handleOptionSelect: function handleOptionSelect(key) {
if (this.props.onSelect) {
this.props.onSelect(key);
}
this.setDropdownState(false);
}
});
exports['default'] = DropdownButton;
module.exports = exports['default'];
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsEventListener = __webpack_require__(32);
var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener);
/**
* Checks whether a node is within
* a root nodes tree
*
* @param {DOMElement} node
* @param {DOMElement} root
* @returns {boolean}
*/
function isNodeInRoot(node, root) {
while (node) {
if (node === root) {
return true;
}
node = node.parentNode;
}
return false;
}
var DropdownStateMixin = {
getInitialState: function getInitialState() {
return {
open: false
};
},
setDropdownState: function setDropdownState(newState, onStateChangeComplete) {
if (newState) {
this.bindRootCloseHandlers();
} else {
this.unbindRootCloseHandlers();
}
this.setState({
open: newState
}, onStateChangeComplete);
},
handleDocumentKeyUp: function handleDocumentKeyUp(e) {
if (e.keyCode === 27) {
this.setDropdownState(false);
}
},
handleDocumentClick: function handleDocumentClick(e) {
// If the click originated from within this component
// don't do anything.
// e.srcElement is required for IE8 as e.target is undefined
var target = e.target || e.srcElement;
if (isNodeInRoot(target, _react2['default'].findDOMNode(this))) {
return;
}
this.setDropdownState(false);
},
bindRootCloseHandlers: function bindRootCloseHandlers() {
var doc = _utilsDomUtils2['default'].ownerDocument(this);
this._onDocumentClickListener = _utilsEventListener2['default'].listen(doc, 'click', this.handleDocumentClick);
this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp);
},
unbindRootCloseHandlers: function unbindRootCloseHandlers() {
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
if (this._onDocumentKeyupListener) {
this._onDocumentKeyupListener.remove();
}
},
componentWillUnmount: function componentWillUnmount() {
this.unbindRootCloseHandlers();
}
};
exports['default'] = DropdownStateMixin;
module.exports = exports['default'];
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var DropdownMenu = _react2['default'].createClass({
displayName: 'DropdownMenu',
propTypes: {
pullRight: _react2['default'].PropTypes.bool,
onSelect: _react2['default'].PropTypes.func
},
render: function render() {
var classes = {
'dropdown-menu': true,
'dropdown-menu-right': this.props.pullRight
};
return _react2['default'].createElement(
'ul',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, classes),
role: 'menu' }),
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderMenuItem)
);
},
renderMenuItem: function renderMenuItem(child, index) {
return _react.cloneElement(child, {
// Capture onSelect events
onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect),
// Force special props to be transferred
key: child.key ? child.key : index
});
}
});
exports['default'] = DropdownMenu;
module.exports = exports['default'];
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsDeprecationWarning = __webpack_require__(49);
var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning);
// TODO: listen for onTransitionEnd to remove el
function getElementsAndSelf(root, classes) {
var els = root.querySelectorAll('.' + classes.join('.'));
els = [].map.call(els, function (e) {
return e;
});
for (var i = 0; i < classes.length; i++) {
if (!root.className.match(new RegExp('\\b' + classes[i] + '\\b'))) {
return els;
}
}
els.unshift(root);
return els;
}
var warned = false;
exports['default'] = {
componentWillMount: function componentWillMount() {
if (!warned) {
_utilsDeprecationWarning2['default']('FadeMixin', 'Fade Component');
warned = true;
}
},
_fadeIn: function _fadeIn() {
var els = undefined;
if (this.isMounted()) {
els = getElementsAndSelf(_react2['default'].findDOMNode(this), ['fade']);
if (els.length) {
els.forEach(function (el) {
el.className += ' in';
});
}
}
},
_fadeOut: function _fadeOut() {
var els = getElementsAndSelf(this._fadeOutEl, ['fade', 'in']);
if (els.length) {
els.forEach(function (el) {
el.className = el.className.replace(/\bin\b/, '');
});
}
setTimeout(this._handleFadeOutEnd, 300);
},
_handleFadeOutEnd: function _handleFadeOutEnd() {
if (this._fadeOutEl && this._fadeOutEl.parentNode) {
this._fadeOutEl.parentNode.removeChild(this._fadeOutEl);
}
},
componentDidMount: function componentDidMount() {
if (document.querySelectorAll) {
// Firefox needs delay for transition to be triggered
setTimeout(this._fadeIn, 20);
}
},
componentWillUnmount: function componentWillUnmount() {
var els = getElementsAndSelf(_react2['default'].findDOMNode(this), ['fade']);
var container = this.props.container && _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body;
if (els.length) {
this._fadeOutEl = document.createElement('div');
container.appendChild(this._fadeOutEl);
this._fadeOutEl.appendChild(_react2['default'].findDOMNode(this).cloneNode(true));
// Firefox needs delay for transition to be triggered
setTimeout(this._fadeOut, 20);
}
}
};
module.exports = exports['default'];
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Grid = _react2['default'].createClass({
displayName: 'Grid',
propTypes: {
/**
* Turn any fixed-width grid layout into a full-width layout by this property.
*
* Adds `container-fluid` class.
*/
fluid: _react2['default'].PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: _utilsCustomPropTypes2['default'].elementType
},
getDefaultProps: function getDefaultProps() {
return {
componentClass: 'div'
};
},
render: function render() {
var ComponentClass = this.props.componentClass;
var className = this.props.fluid ? 'container-fluid' : 'container';
return _react2['default'].createElement(
ComponentClass,
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, className) }),
this.props.children
);
}
});
exports['default'] = Grid;
module.exports = exports['default'];
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
var _interopRequireWildcard = __webpack_require__(18)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _InputBase2 = __webpack_require__(39);
var _InputBase3 = _interopRequireDefault(_InputBase2);
var _FormControls = __webpack_require__(62);
var FormControls = _interopRequireWildcard(_FormControls);
var _utilsDeprecationWarning = __webpack_require__(49);
var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning);
var Input = (function (_InputBase) {
_inherits(Input, _InputBase);
function Input() {
_classCallCheck(this, Input);
_InputBase.apply(this, arguments);
}
Input.prototype.render = function render() {
if (this.props.type === 'static') {
// eslint-disable-line react/prop-types
_utilsDeprecationWarning2['default']('Input type=static', 'StaticText');
return _react2['default'].createElement(FormControls.Static, this.props);
}
return _InputBase.prototype.render.call(this);
};
return Input;
})(_InputBase3['default']);
Input.propTypes = {
type: _react2['default'].PropTypes.string
};
exports['default'] = Input;
module.exports = exports['default'];
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _Static2 = __webpack_require__(63);
var _Static3 = _interopRequireDefault(_Static2);
exports.Static = _Static3['default'];
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _InputBase2 = __webpack_require__(39);
var _InputBase3 = _interopRequireDefault(_InputBase2);
var _utilsChildrenValueInputValidation = __webpack_require__(40);
var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation);
var Static = (function (_InputBase) {
_inherits(Static, _InputBase);
function Static() {
_classCallCheck(this, Static);
_InputBase.apply(this, arguments);
}
Static.prototype.getValue = function getValue() {
var _props = this.props;
var children = _props.children;
var value = _props.value;
return children ? children : value;
};
Static.prototype.renderInput = function renderInput() {
return _react2['default'].createElement(
'p',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'form-control-static'), ref: 'input', key: 'input' }),
this.getValue()
);
};
return Static;
})(_InputBase3['default']);
Static.propTypes = {
value: _utilsChildrenValueInputValidation2['default'],
children: _utilsChildrenValueInputValidation2['default']
};
exports['default'] = Static;
module.exports = exports['default'];
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
// https://www.npmjs.org/package/react-interpolate-component
// TODO: Drop this in favor of es6 string interpolation
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var REGEXP = /\%\((.+?)\)s/;
var Interpolate = _react2['default'].createClass({
displayName: 'Interpolate',
propTypes: {
component: _react2['default'].PropTypes.node,
format: _react2['default'].PropTypes.string,
unsafe: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return { component: 'span' };
},
render: function render() {
var format = _utilsValidComponentChildren2['default'].hasValidComponent(this.props.children) || typeof this.props.children === 'string' ? this.props.children : this.props.format;
var parent = this.props.component;
var unsafe = this.props.unsafe === true;
var props = _extends({}, this.props);
delete props.children;
delete props.format;
delete props.component;
delete props.unsafe;
if (unsafe) {
var content = format.split(REGEXP).reduce(function (memo, match, index) {
var html = undefined;
if (index % 2 === 0) {
html = match;
} else {
html = props[match];
delete props[match];
}
if (_react2['default'].isValidElement(html)) {
throw new Error('cannot interpolate a React component into unsafe text');
}
memo += html;
return memo;
}, '');
props.dangerouslySetInnerHTML = { __html: content };
return _react2['default'].createElement(parent, props);
} else {
var kids = format.split(REGEXP).reduce(function (memo, match, index) {
var child = undefined;
if (index % 2 === 0) {
if (match.length === 0) {
return memo;
}
child = match;
} else {
child = props[match];
delete props[match];
}
memo.push(child);
return memo;
}, []);
return _react2['default'].createElement(parent, props, kids);
}
}
});
exports['default'] = Interpolate;
module.exports = exports['default'];
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Jumbotron = _react2['default'].createClass({
displayName: 'Jumbotron',
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: _utilsCustomPropTypes2['default'].elementType
},
getDefaultProps: function getDefaultProps() {
return { componentClass: 'div' };
},
render: function render() {
var ComponentClass = this.props.componentClass;
return _react2['default'].createElement(
ComponentClass,
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'jumbotron') }),
this.props.children
);
}
});
exports['default'] = Jumbotron;
module.exports = exports['default'];
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var Label = _react2['default'].createClass({
displayName: 'Label',
mixins: [_BootstrapMixin2['default']],
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render: function render() {
var classes = this.getBsClassSet();
return _react2['default'].createElement(
'span',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = Label;
module.exports = exports['default'];
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var ListGroup = (function (_React$Component) {
_inherits(ListGroup, _React$Component);
function ListGroup() {
_classCallCheck(this, ListGroup);
_React$Component.apply(this, arguments);
}
ListGroup.prototype.render = function render() {
var _this = this;
var items = _utilsValidComponentChildren2['default'].map(this.props.children, function (item, index) {
return _react.cloneElement(item, { key: item.key ? item.key : index });
});
var childrenAnchors = false;
if (!this.props.children) {
return this.renderDiv(items);
} else {
_react2['default'].Children.forEach(this.props.children, function (child) {
if (_this.isAnchor(child.props)) {
childrenAnchors = true;
}
});
}
if (childrenAnchors) {
return this.renderDiv(items);
} else {
return this.renderUL(items);
}
};
ListGroup.prototype.isAnchor = function isAnchor(props) {
return props.href || props.onClick;
};
ListGroup.prototype.renderUL = function renderUL(items) {
var listItems = _utilsValidComponentChildren2['default'].map(items, function (item, index) {
return _react.cloneElement(item, { listItem: true });
});
return _react2['default'].createElement(
'ul',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, 'list-group') }),
listItems
);
};
ListGroup.prototype.renderDiv = function renderDiv(items) {
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, 'list-group') }),
items
);
};
return ListGroup;
})(_react2['default'].Component);
ListGroup.propTypes = {
className: _react2['default'].PropTypes.string,
id: _react2['default'].PropTypes.string
};
exports['default'] = ListGroup;
module.exports = exports['default'];
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var ListGroupItem = _react2['default'].createClass({
displayName: 'ListGroupItem',
mixins: [_BootstrapMixin2['default']],
propTypes: {
bsStyle: _react2['default'].PropTypes.oneOf(['danger', 'info', 'success', 'warning']),
className: _react2['default'].PropTypes.string,
active: _react2['default'].PropTypes.any,
disabled: _react2['default'].PropTypes.any,
header: _react2['default'].PropTypes.node,
listItem: _react2['default'].PropTypes.bool,
onClick: _react2['default'].PropTypes.func,
eventKey: _react2['default'].PropTypes.any,
href: _react2['default'].PropTypes.string,
target: _react2['default'].PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'list-group-item'
};
},
render: function render() {
var classes = this.getBsClassSet();
classes.active = this.props.active;
classes.disabled = this.props.disabled;
if (this.props.href || this.props.onClick) {
return this.renderAnchor(classes);
} else if (this.props.listItem) {
return this.renderLi(classes);
} else {
return this.renderSpan(classes);
}
},
renderLi: function renderLi(classes) {
return _react2['default'].createElement(
'li',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.header ? this.renderStructuredContent() : this.props.children
);
},
renderAnchor: function renderAnchor(classes) {
return _react2['default'].createElement(
_SafeAnchor2['default'],
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, classes)
}),
this.props.header ? this.renderStructuredContent() : this.props.children
);
},
renderSpan: function renderSpan(classes) {
return _react2['default'].createElement(
'span',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.header ? this.renderStructuredContent() : this.props.children
);
},
renderStructuredContent: function renderStructuredContent() {
var header = undefined;
if (_react2['default'].isValidElement(this.props.header)) {
header = _react.cloneElement(this.props.header, {
key: 'header',
className: _classnames2['default'](this.props.header.props.className, 'list-group-item-heading')
});
} else {
header = _react2['default'].createElement(
'h4',
{ key: 'header', className: 'list-group-item-heading' },
this.props.header
);
}
var content = _react2['default'].createElement(
'p',
{ key: 'content', className: 'list-group-item-text' },
this.props.children
);
return [header, content];
}
});
exports['default'] = ListGroupItem;
module.exports = exports['default'];
/***/ },
/* 69 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
/**
* Note: This is intended as a stop-gap for accessibility concerns that the
* Bootstrap CSS does not address as they have styled anchors and not buttons
* in many cases.
*/
var SafeAnchor = (function (_React$Component) {
_inherits(SafeAnchor, _React$Component);
function SafeAnchor(props) {
_classCallCheck(this, SafeAnchor);
_React$Component.call(this, props);
this.handleClick = this.handleClick.bind(this);
}
SafeAnchor.prototype.handleClick = function handleClick(event) {
if (this.props.href === undefined) {
event.preventDefault();
}
};
SafeAnchor.prototype.render = function render() {
return _react2['default'].createElement('a', _extends({ role: this.props.href ? undefined : 'button'
}, this.props, {
onClick: _utilsCreateChainedFunction2['default'](this.props.onClick, this.handleClick),
href: this.props.href || '' }));
};
return SafeAnchor;
})(_react2['default'].Component);
exports['default'] = SafeAnchor;
SafeAnchor.propTypes = {
href: _react2['default'].PropTypes.string,
onClick: _react2['default'].PropTypes.func
};
module.exports = exports['default'];
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var MenuItem = _react2['default'].createClass({
displayName: 'MenuItem',
propTypes: {
header: _react2['default'].PropTypes.bool,
divider: _react2['default'].PropTypes.bool,
href: _react2['default'].PropTypes.string,
title: _react2['default'].PropTypes.string,
target: _react2['default'].PropTypes.string,
onSelect: _react2['default'].PropTypes.func,
eventKey: _react2['default'].PropTypes.any,
active: _react2['default'].PropTypes.bool,
disabled: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
active: false
};
},
handleClick: function handleClick(e) {
if (this.props.disabled) {
e.preventDefault();
return;
}
if (this.props.onSelect) {
e.preventDefault();
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
},
renderAnchor: function renderAnchor() {
return _react2['default'].createElement(
_SafeAnchor2['default'],
{ onClick: this.handleClick, href: this.props.href, target: this.props.target, title: this.props.title, tabIndex: '-1' },
this.props.children
);
},
render: function render() {
var classes = {
'dropdown-header': this.props.header,
'divider': this.props.divider,
'active': this.props.active,
'disabled': this.props.disabled
};
var children = null;
if (this.props.header) {
children = this.props.children;
} else if (!this.props.divider) {
children = this.renderAnchor();
}
return _react2['default'].createElement(
'li',
_extends({}, this.props, { role: 'presentation', title: null, href: null,
className: _classnames2['default'](this.props.className, classes) }),
children
);
}
});
exports['default'] = MenuItem;
module.exports = exports['default'];
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable react/prop-types */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsEventListener = __webpack_require__(32);
var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener);
var _Portal = __webpack_require__(72);
var _Portal2 = _interopRequireDefault(_Portal);
var _Fade = __webpack_require__(73);
var _Fade2 = _interopRequireDefault(_Fade);
var _ModalBody = __webpack_require__(74);
var _ModalBody2 = _interopRequireDefault(_ModalBody);
var _ModalHeader = __webpack_require__(75);
var _ModalHeader2 = _interopRequireDefault(_ModalHeader);
var _ModalTitle = __webpack_require__(1);
var _ModalTitle2 = _interopRequireDefault(_ModalTitle);
var _ModalFooter = __webpack_require__(76);
var _ModalFooter2 = _interopRequireDefault(_ModalFooter);
/**
* Gets the correct clientHeight of the modal container
* when the body/window/document you need to use the docElement clientHeight
* @param {HTMLElement} container
* @param {ReactElement|HTMLElement} context
* @return {Number}
*/
function containerClientHeight(container, context) {
var doc = _utilsDomUtils2['default'].ownerDocument(context);
return container === doc.body || container === doc.documentElement ? doc.documentElement.clientHeight : container.clientHeight;
}
function getContainer(context) {
return context.props.container && _react2['default'].findDOMNode(context.props.container) || _utilsDomUtils2['default'].ownerDocument(context).body;
}
var currentFocusListener = undefined;
/**
* Firefox doesn't have a focusin event so using capture is easiest way to get bubbling
* IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8
*
* We only allow one Listener at a time to avoid stack overflows
*
* @param {ReactElement|HTMLElement} context
* @param {Function} handler
*/
function onFocus(context, handler) {
var doc = _utilsDomUtils2['default'].ownerDocument(context);
var useFocusin = !doc.addEventListener;
var remove = undefined;
if (currentFocusListener) {
currentFocusListener.remove();
}
if (useFocusin) {
document.attachEvent('onfocusin', handler);
remove = function () {
return document.detachEvent('onfocusin', handler);
};
} else {
document.addEventListener('focus', handler, true);
remove = function () {
return document.removeEventListener('focus', handler, true);
};
}
currentFocusListener = { remove: remove };
return currentFocusListener;
}
var scrollbarSize = undefined;
function getScrollbarSize() {
if (scrollbarSize !== undefined) {
return scrollbarSize;
}
var scrollDiv = document.createElement('div');
scrollDiv.style.position = 'absolute';
scrollDiv.style.top = '-9999px';
scrollDiv.style.width = '50px';
scrollDiv.style.height = '50px';
scrollDiv.style.overflow = 'scroll';
document.body.appendChild(scrollDiv);
scrollbarSize = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
scrollDiv = null;
return scrollbarSize;
}
var ModalMarkup = _react2['default'].createClass({
displayName: 'ModalMarkup',
mixins: [_BootstrapMixin2['default']],
propTypes: {
/**
* Include a backdrop component. Specify 'static' for a backdrop that doesn't trigger an "onHide" when clicked.
*/
backdrop: _react2['default'].PropTypes.oneOf(['static', true, false]),
/**
* Close the modal when escape key is pressed
*/
keyboard: _react2['default'].PropTypes.bool,
/**
* Open and close the Modal with a slide and fade animation.
*/
animation: _react2['default'].PropTypes.bool,
/**
* A Callback fired when the header closeButton or non-static backdrop is clicked.
* @type {function}
* @required
*/
onHide: _react2['default'].PropTypes.func.isRequired,
/**
* A css class to apply to the Modal dialog DOM node.
*/
dialogClassName: _react2['default'].PropTypes.string,
/**
* When `true` The modal will automatically shift focus to itself when it opens, and replace it to the last focused element when it closes.
* Generally this should never be set to false as it makes the Modal less accessible to assistive technologies, like screen-readers.
*/
autoFocus: _react2['default'].PropTypes.bool,
/**
* When `true` The modal will prevent focus from leaving the Modal while open.
* Consider leaving the default value here, as it is necessary to make the Modal work well with assistive technologies,
* such as screen readers.
*/
enforceFocus: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'modal',
backdrop: true,
keyboard: true,
animation: true,
closeButton: true,
autoFocus: true,
enforceFocus: true
};
},
getInitialState: function getInitialState() {
return {};
},
render: function render() {
var state = this.state;
var modalStyle = _extends({}, state.dialogStyles, { display: 'block' });
var dialogClasses = this.getBsClassSet();
delete dialogClasses.modal;
dialogClasses['modal-dialog'] = true;
var classes = {
modal: true,
'in': this.props.show && !this.props.animation
};
var modal = _react2['default'].createElement(
'div',
_extends({}, this.props, {
title: null,
tabIndex: '-1',
role: 'dialog',
style: modalStyle,
className: _classnames2['default'](this.props.className, classes),
onClick: this.props.backdrop === true ? this.handleBackdropClick : null,
ref: 'modal' }),
_react2['default'].createElement(
'div',
{ className: _classnames2['default'](this.props.dialogClassName, dialogClasses) },
_react2['default'].createElement(
'div',
{ className: 'modal-content', role: 'document' },
this.renderContent()
)
)
);
return this.props.backdrop ? this.renderBackdrop(modal, state.backdropStyles) : modal;
},
renderContent: function renderContent() {
var _this = this;
return _react2['default'].Children.map(this.props.children, function (child) {
// TODO: use context in 0.14
if (child.type.__isModalHeader) {
return _react.cloneElement(child, {
onHide: _utilsCreateChainedFunction2['default'](_this.props.onHide, child.props.onHide)
});
}
return child;
});
},
renderBackdrop: function renderBackdrop(modal) {
var animation = this.props.animation;
var duration = Modal.BACKDROP_TRANSITION_DURATION; //eslint-disable-line no-use-before-define
var backdrop = _react2['default'].createElement('div', { ref: 'backdrop',
className: _classnames2['default']('modal-backdrop', { 'in': this.props.show && !animation }),
onClick: this.handleBackdropClick
});
return _react2['default'].createElement(
'div',
null,
animation ? _react2['default'].createElement(
_Fade2['default'],
{ transitionAppear: true, 'in': this.props.show, duration: duration },
backdrop
) : backdrop,
modal
);
},
iosClickHack: function iosClickHack() {
// IOS only allows click events to be delegated to the document on elements
// it considers 'clickable' - anchors, buttons, etc. We fake a click handler on the
// DOM nodes themselves. Remove if handled by React: https://github.com/facebook/react/issues/1169
_react2['default'].findDOMNode(this.refs.modal).onclick = function () {};
_react2['default'].findDOMNode(this.refs.backdrop).onclick = function () {};
},
componentWillMount: function componentWillMount() {
this.checkForFocus();
},
componentDidMount: function componentDidMount() {
var _this2 = this;
var doc = _utilsDomUtils2['default'].ownerDocument(this);
var win = _utilsDomUtils2['default'].ownerWindow(this);
this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp);
this._onWindowResizeListener = _utilsEventListener2['default'].listen(win, 'resize', this.handleWindowResize);
if (this.props.enforceFocus) {
this._onFocusinListener = onFocus(this, this.enforceFocus);
}
var container = getContainer(this);
container.className += container.className.length ? ' modal-open' : 'modal-open';
this._containerIsOverflowing = container.scrollHeight > containerClientHeight(container, this);
this._originalPadding = container.style.paddingRight;
if (this._containerIsOverflowing) {
container.style.paddingRight = parseInt(this._originalPadding || 0, 10) + getScrollbarSize() + 'px';
}
if (this.props.backdrop) {
this.iosClickHack();
}
this.setState(this._getStyles(), //eslint-disable-line react/no-did-mount-set-state
function () {
return _this2.focusModalContent();
});
},
componentDidUpdate: function componentDidUpdate(prevProps) {
if (this.props.backdrop && this.props.backdrop !== prevProps.backdrop) {
this.iosClickHack();
this.setState(this._getStyles()); //eslint-disable-line react/no-did-update-set-state
}
if (this.props.container !== prevProps.container) {
var container = getContainer(this);
this._containerIsOverflowing = container.scrollHeight > containerClientHeight(container, this);
}
},
componentWillUnmount: function componentWillUnmount() {
this._onDocumentKeyupListener.remove();
this._onWindowResizeListener.remove();
if (this._onFocusinListener) {
this._onFocusinListener.remove();
}
var container = getContainer(this);
container.style.paddingRight = this._originalPadding;
container.className = container.className.replace(/ ?modal-open/, '');
this.restoreLastFocus();
},
handleBackdropClick: function handleBackdropClick(e) {
if (e.target !== e.currentTarget) {
return;
}
this.props.onHide();
},
handleDocumentKeyUp: function handleDocumentKeyUp(e) {
if (this.props.keyboard && e.keyCode === 27) {
this.props.onHide();
}
},
handleWindowResize: function handleWindowResize() {
this.setState(this._getStyles());
},
checkForFocus: function checkForFocus() {
if (_utilsDomUtils2['default'].canUseDom) {
try {
this.lastFocus = document.activeElement;
} catch (e) {} // eslint-disable-line no-empty
}
},
focusModalContent: function focusModalContent() {
var modalContent = _react2['default'].findDOMNode(this.refs.modal);
var current = _utilsDomUtils2['default'].activeElement(this);
var focusInModal = current && _utilsDomUtils2['default'].contains(modalContent, current);
if (this.props.autoFocus && !focusInModal) {
this.lastFocus = current;
modalContent.focus();
}
},
restoreLastFocus: function restoreLastFocus() {
if (this.lastFocus) {
this.lastFocus.focus();
this.lastFocus = null;
}
},
enforceFocus: function enforceFocus() {
if (!this.isMounted()) {
return;
}
var active = _utilsDomUtils2['default'].activeElement(this);
var modal = _react2['default'].findDOMNode(this.refs.modal);
if (modal !== active && !_utilsDomUtils2['default'].contains(modal, active)) {
modal.focus();
}
},
_getStyles: function _getStyles() {
if (!_utilsDomUtils2['default'].canUseDom) {
return {};
}
var node = _react2['default'].findDOMNode(this.refs.modal);
var scrollHt = node.scrollHeight;
var container = getContainer(this);
var containerIsOverflowing = this._containerIsOverflowing;
var modalIsOverflowing = scrollHt > containerClientHeight(container, this);
return {
dialogStyles: {
paddingRight: containerIsOverflowing && !modalIsOverflowing ? getScrollbarSize() : void 0,
paddingLeft: !containerIsOverflowing && modalIsOverflowing ? getScrollbarSize() : void 0
}
};
}
});
var Modal = _react2['default'].createClass({
displayName: 'Modal',
propTypes: _extends({}, _Portal2['default'].propTypes, ModalMarkup.propTypes),
getDefaultProps: function getDefaultProps() {
return {
show: false,
animation: true
};
},
render: function render() {
var _props = this.props;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['children']);
var show = !!props.show;
var modal = _react2['default'].createElement(
ModalMarkup,
_extends({}, props, { ref: 'modal' }),
children
);
return _react2['default'].createElement(
_Portal2['default'],
{ container: props.container },
props.animation ? _react2['default'].createElement(
_Fade2['default'],
{
'in': show,
transitionAppear: show,
duration: Modal.TRANSITION_DURATION,
unmountOnExit: true
},
modal
) : show && modal
);
}
});
Modal.Body = _ModalBody2['default'];
Modal.Header = _ModalHeader2['default'];
Modal.Title = _ModalTitle2['default'];
Modal.Footer = _ModalFooter2['default'];
Modal.TRANSITION_DURATION = 300;
Modal.BACKDROP_TRANSITION_DURATION = 150;
exports['default'] = Modal;
module.exports = exports['default'];
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable react/prop-types */
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var Portal = _react2['default'].createClass({
displayName: 'Portal',
propTypes: {
/**
* The DOM Node that the Component will render it's children into
*/
container: _utilsCustomPropTypes2['default'].mountable
},
componentDidMount: function componentDidMount() {
this._renderOverlay();
},
componentDidUpdate: function componentDidUpdate() {
this._renderOverlay();
},
componentWillUnmount: function componentWillUnmount() {
this._unrenderOverlay();
this._unmountOverlayTarget();
},
_mountOverlayTarget: function _mountOverlayTarget() {
if (!this._overlayTarget) {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode().appendChild(this._overlayTarget);
}
},
_unmountOverlayTarget: function _unmountOverlayTarget() {
if (this._overlayTarget) {
this.getContainerDOMNode().removeChild(this._overlayTarget);
this._overlayTarget = null;
}
},
_renderOverlay: function _renderOverlay() {
var overlay = !this.props.children ? null : _react2['default'].Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this._mountOverlayTarget();
this._overlayInstance = _react2['default'].render(overlay, this._overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this._unrenderOverlay();
this._unmountOverlayTarget();
}
},
_unrenderOverlay: function _unrenderOverlay() {
if (this._overlayTarget) {
_react2['default'].unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
}
},
render: function render() {
return null;
},
getOverlayDOMNode: function getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this._overlayInstance) {
if (this._overlayInstance.getWrappedDOMNode) {
return this._overlayInstance.getWrappedDOMNode();
} else {
return _react2['default'].findDOMNode(this._overlayInstance);
}
}
return null;
},
getContainerDOMNode: function getContainerDOMNode() {
return _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body;
}
});
exports['default'] = Portal;
module.exports = exports['default'];
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _Transition = __webpack_require__(54);
var _Transition2 = _interopRequireDefault(_Transition);
var Fade = (function (_React$Component) {
_inherits(Fade, _React$Component);
function Fade() {
_classCallCheck(this, Fade);
_React$Component.apply(this, arguments);
}
Fade.prototype.render = function render() {
return _react2['default'].createElement(
_Transition2['default'],
_extends({}, this.props, {
className: 'fade',
enteredClassName: 'in',
enteringClassName: 'in'
}),
this.props.children
);
};
return Fade;
})(_react2['default'].Component);
// Explicitly copied from Transition for doc generation.
// TODO: Remove duplication once #977 is resolved.
Fade.propTypes = {
/**
* Show the component; triggers the fade in or fade out animation
*/
'in': _react2['default'].PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is faded out
*/
unmountOnExit: _react2['default'].PropTypes.bool,
/**
* Run the fade in animation when the component mounts, if it is initially
* shown
*/
transitionAppear: _react2['default'].PropTypes.bool,
/**
* Duration of the fade animation in milliseconds, to ensure that finishing
* callbacks are fired even if the original browser transition end events are
* canceled
*/
duration: _react2['default'].PropTypes.number,
/**
* Callback fired before the component fades in
*/
onEnter: _react2['default'].PropTypes.func,
/**
* Callback fired after the component starts to fade in
*/
onEntering: _react2['default'].PropTypes.func,
/**
* Callback fired after the has component faded in
*/
onEntered: _react2['default'].PropTypes.func,
/**
* Callback fired before the component fades out
*/
onExit: _react2['default'].PropTypes.func,
/**
* Callback fired after the component starts to fade out
*/
onExiting: _react2['default'].PropTypes.func,
/**
* Callback fired after the component has faded out
*/
onExited: _react2['default'].PropTypes.func
};
Fade.defaultProps = {
'in': false,
duration: 300,
unmountOnExit: false,
transitionAppear: false
};
exports['default'] = Fade;
module.exports = exports['default'];
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var ModalBody = (function (_React$Component) {
_inherits(ModalBody, _React$Component);
function ModalBody() {
_classCallCheck(this, ModalBody);
_React$Component.apply(this, arguments);
}
ModalBody.prototype.render = function render() {
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, this.props.modalClassName) }),
this.props.children
);
};
return ModalBody;
})(_react2['default'].Component);
ModalBody.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: _react2['default'].PropTypes.string
};
ModalBody.defaultProps = {
modalClassName: 'modal-body'
};
exports['default'] = ModalBody;
module.exports = exports['default'];
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var ModalHeader = (function (_React$Component) {
_inherits(ModalHeader, _React$Component);
function ModalHeader() {
_classCallCheck(this, ModalHeader);
_React$Component.apply(this, arguments);
}
ModalHeader.prototype.render = function render() {
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, this.props.modalClassName)
}),
this.props.closeButton && _react2['default'].createElement(
'button',
{
className: 'close',
'aria-label': this.props['aria-label'] || 'Close',
onClick: this.props.onHide
},
_react2['default'].createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
),
this.props.children
);
};
return ModalHeader;
})(_react2['default'].Component);
//used in liue of parent contexts right now to auto wire the close button
ModalHeader.__isModalHeader = true;
ModalHeader.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: _react2['default'].PropTypes.string,
/**
* Specify whether the Component should contain a close button
*/
closeButton: _react2['default'].PropTypes.bool,
/**
* A Callback fired when the close button is clicked. If used directly inside a Modal component, the onHide will automatically
* be propagated up to the parent Modal `onHide`.
*/
onHide: _react2['default'].PropTypes.func
};
ModalHeader.defaultProps = {
modalClassName: 'modal-header',
closeButton: false
};
exports['default'] = ModalHeader;
module.exports = exports['default'];
//eslint-disable-line react/prop-types
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var ModalFooter = (function (_React$Component) {
_inherits(ModalFooter, _React$Component);
function ModalFooter() {
_classCallCheck(this, ModalFooter);
_React$Component.apply(this, arguments);
}
ModalFooter.prototype.render = function render() {
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, this.props.modalClassName) }),
this.props.children
);
};
return ModalFooter;
})(_react2['default'].Component);
ModalFooter.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: _react2['default'].PropTypes.string
};
ModalFooter.defaultProps = {
modalClassName: 'modal-footer'
};
exports['default'] = ModalFooter;
module.exports = exports['default'];
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _Collapse = __webpack_require__(53);
var _Collapse2 = _interopRequireDefault(_Collapse);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var Nav = _react2['default'].createClass({
displayName: 'Nav',
mixins: [_BootstrapMixin2['default']],
propTypes: {
activeHref: _react2['default'].PropTypes.string,
activeKey: _react2['default'].PropTypes.any,
bsStyle: _react2['default'].PropTypes.oneOf(['tabs', 'pills']),
stacked: _react2['default'].PropTypes.bool,
justified: _react2['default'].PropTypes.bool,
onSelect: _react2['default'].PropTypes.func,
collapsible: _react2['default'].PropTypes.bool,
/**
* CSS classes for the wrapper `nav` element
*/
className: _react2['default'].PropTypes.string,
/**
* HTML id for the wrapper `nav` element
*/
id: _react2['default'].PropTypes.string,
/**
* CSS classes for the inner `ul` element
*/
ulClassName: _react2['default'].PropTypes.string,
/**
* HTML id for the inner `ul` element
*/
ulId: _react2['default'].PropTypes.string,
expanded: _react2['default'].PropTypes.bool,
navbar: _react2['default'].PropTypes.bool,
eventKey: _react2['default'].PropTypes.any,
pullRight: _react2['default'].PropTypes.bool,
right: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'nav',
expanded: true
};
},
render: function render() {
var classes = this.props.collapsible ? 'navbar-collapse' : null;
if (this.props.navbar && !this.props.collapsible) {
return this.renderUl();
}
return _react2['default'].createElement(
_Collapse2['default'],
{ 'in': this.props.expanded },
_react2['default'].createElement(
'nav',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.renderUl()
)
);
},
renderUl: function renderUl() {
var classes = this.getBsClassSet();
classes['nav-stacked'] = this.props.stacked;
classes['nav-justified'] = this.props.justified;
classes['navbar-nav'] = this.props.navbar;
classes['pull-right'] = this.props.pullRight;
classes['navbar-right'] = this.props.right;
return _react2['default'].createElement(
'ul',
_extends({}, this.props, {
role: this.props.bsStyle === 'tabs' ? 'tablist' : null,
className: _classnames2['default'](this.props.ulClassName, classes),
id: this.props.ulId,
ref: 'ul'
}),
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderNavItem)
);
},
getChildActiveProp: function getChildActiveProp(child) {
if (child.props.active) {
return true;
}
if (this.props.activeKey != null) {
if (child.props.eventKey === this.props.activeKey) {
return true;
}
}
if (this.props.activeHref != null) {
if (child.props.href === this.props.activeHref) {
return true;
}
}
return child.props.active;
},
renderNavItem: function renderNavItem(child, index) {
return _react.cloneElement(child, {
role: this.props.bsStyle === 'tabs' ? 'tab' : null,
active: this.getChildActiveProp(child),
activeKey: this.props.activeKey,
activeHref: this.props.activeHref,
onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect),
key: child.key ? child.key : index,
navItem: true
});
}
});
exports['default'] = Nav;
module.exports = exports['default'];
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Navbar = _react2['default'].createClass({
displayName: 'Navbar',
mixins: [_BootstrapMixin2['default']],
propTypes: {
fixedTop: _react2['default'].PropTypes.bool,
fixedBottom: _react2['default'].PropTypes.bool,
staticTop: _react2['default'].PropTypes.bool,
inverse: _react2['default'].PropTypes.bool,
fluid: _react2['default'].PropTypes.bool,
role: _react2['default'].PropTypes.string,
/**
* You can use a custom element for this component
*/
componentClass: _utilsCustomPropTypes2['default'].elementType,
brand: _react2['default'].PropTypes.node,
toggleButton: _react2['default'].PropTypes.node,
toggleNavKey: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]),
onToggle: _react2['default'].PropTypes.func,
navExpanded: _react2['default'].PropTypes.bool,
defaultNavExpanded: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'navbar',
bsStyle: 'default',
role: 'navigation',
componentClass: 'nav'
};
},
getInitialState: function getInitialState() {
return {
navExpanded: this.props.defaultNavExpanded
};
},
shouldComponentUpdate: function shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleToggle: function handleToggle() {
if (this.props.onToggle) {
this._isChanging = true;
this.props.onToggle();
this._isChanging = false;
}
this.setState({
navExpanded: !this.state.navExpanded
});
},
isNavExpanded: function isNavExpanded() {
return this.props.navExpanded != null ? this.props.navExpanded : this.state.navExpanded;
},
render: function render() {
var classes = this.getBsClassSet();
var ComponentClass = this.props.componentClass;
classes['navbar-fixed-top'] = this.props.fixedTop;
classes['navbar-fixed-bottom'] = this.props.fixedBottom;
classes['navbar-static-top'] = this.props.staticTop;
classes['navbar-inverse'] = this.props.inverse;
return _react2['default'].createElement(
ComponentClass,
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
_react2['default'].createElement(
'div',
{ className: this.props.fluid ? 'container-fluid' : 'container' },
this.props.brand || this.props.toggleButton || this.props.toggleNavKey != null ? this.renderHeader() : null,
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderChild)
)
);
},
renderChild: function renderChild(child, index) {
return _react.cloneElement(child, {
navbar: true,
collapsible: this.props.toggleNavKey != null && this.props.toggleNavKey === child.props.eventKey,
expanded: this.props.toggleNavKey != null && this.props.toggleNavKey === child.props.eventKey && this.isNavExpanded(),
key: child.key ? child.key : index
});
},
renderHeader: function renderHeader() {
var brand = undefined;
if (this.props.brand) {
if (_react2['default'].isValidElement(this.props.brand)) {
brand = _react.cloneElement(this.props.brand, {
className: _classnames2['default'](this.props.brand.props.className, 'navbar-brand')
});
} else {
brand = _react2['default'].createElement(
'span',
{ className: 'navbar-brand' },
this.props.brand
);
}
}
return _react2['default'].createElement(
'div',
{ className: 'navbar-header' },
brand,
this.props.toggleButton || this.props.toggleNavKey != null ? this.renderToggleButton() : null
);
},
renderToggleButton: function renderToggleButton() {
var children = undefined;
if (_react2['default'].isValidElement(this.props.toggleButton)) {
return _react.cloneElement(this.props.toggleButton, {
className: _classnames2['default'](this.props.toggleButton.props.className, 'navbar-toggle'),
onClick: _utilsCreateChainedFunction2['default'](this.handleToggle, this.props.toggleButton.props.onClick)
});
}
children = this.props.toggleButton != null ? this.props.toggleButton : [_react2['default'].createElement(
'span',
{ className: 'sr-only', key: 0 },
'Toggle navigation'
), _react2['default'].createElement('span', { className: 'icon-bar', key: 1 }), _react2['default'].createElement('span', { className: 'icon-bar', key: 2 }), _react2['default'].createElement('span', { className: 'icon-bar', key: 3 })];
return _react2['default'].createElement(
'button',
{ className: 'navbar-toggle', type: 'button', onClick: this.handleToggle },
children
);
}
});
exports['default'] = Navbar;
module.exports = exports['default'];
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var NavItem = _react2['default'].createClass({
displayName: 'NavItem',
mixins: [_BootstrapMixin2['default']],
propTypes: {
linkId: _react2['default'].PropTypes.string,
onSelect: _react2['default'].PropTypes.func,
active: _react2['default'].PropTypes.bool,
disabled: _react2['default'].PropTypes.bool,
href: _react2['default'].PropTypes.string,
role: _react2['default'].PropTypes.string,
title: _react2['default'].PropTypes.node,
eventKey: _react2['default'].PropTypes.any,
target: _react2['default'].PropTypes.string,
'aria-controls': _react2['default'].PropTypes.string
},
render: function render() {
var _props = this.props;
var role = _props.role;
var linkId = _props.linkId;
var disabled = _props.disabled;
var active = _props.active;
var href = _props.href;
var title = _props.title;
var target = _props.target;
var children = _props.children;
var ariaControls = _props['aria-controls'];
var props = _objectWithoutProperties(_props, ['role', 'linkId', 'disabled', 'active', 'href', 'title', 'target', 'children', 'aria-controls']);
var classes = {
active: active,
disabled: disabled
};
var linkProps = {
role: role,
href: href,
title: title,
target: target,
id: linkId,
onClick: this.handleClick
};
if (!role && href === '#') {
linkProps.role = 'button';
}
return _react2['default'].createElement(
'li',
_extends({}, props, { role: 'presentation', className: _classnames2['default'](props.className, classes) }),
_react2['default'].createElement(
_SafeAnchor2['default'],
_extends({}, linkProps, { 'aria-selected': active, 'aria-controls': ariaControls }),
children
)
);
},
handleClick: function handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
exports['default'] = NavItem;
module.exports = exports['default'];
// eslint-disable-line react/prop-types
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable object-shorthand, react/prop-types */
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _Portal = __webpack_require__(72);
var _Portal2 = _interopRequireDefault(_Portal);
var _Position = __webpack_require__(81);
var _Position2 = _interopRequireDefault(_Position);
var _RootCloseWrapper = __webpack_require__(83);
var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var _Fade = __webpack_require__(73);
var _Fade2 = _interopRequireDefault(_Fade);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var Overlay = (function (_React$Component) {
_inherits(Overlay, _React$Component);
function Overlay(props, context) {
_classCallCheck(this, Overlay);
_React$Component.call(this, props, context);
this.state = { exited: !props.show };
this.onHiddenListener = this.handleHidden.bind(this);
}
Overlay.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (nextProps.show) {
this.setState({ exited: false });
} else if (!nextProps.animation) {
// Otherwise let handleHidden take care of marking exited.
this.setState({ exited: true });
}
};
Overlay.prototype.render = function render() {
var _props = this.props;
var container = _props.container;
var containerPadding = _props.containerPadding;
var target = _props.target;
var placement = _props.placement;
var rootClose = _props.rootClose;
var children = _props.children;
var Transition = _props.animation;
var props = _objectWithoutProperties(_props, ['container', 'containerPadding', 'target', 'placement', 'rootClose', 'children', 'animation']);
if (Transition === true) {
Transition = _Fade2['default'];
}
// Don't un-render the overlay while it's transitioning out.
var mountOverlay = props.show || Transition && !this.state.exited;
if (!mountOverlay) {
// Don't bother showing anything if we don't have to.
return null;
}
var child = children;
// Position is be inner-most because it adds inline styles into the child,
// which the other wrappers don't forward correctly.
child = _react2['default'].createElement(
_Position2['default'],
{ container: container, containerPadding: containerPadding, target: target, placement: placement },
child
);
if (Transition) {
// This animates the child node by injecting props, so it must precede
// anything that adds a wrapping div.
child = _react2['default'].createElement(
Transition,
{
'in': props.show,
transitionAppear: true,
onExited: this.onHiddenListener
},
child
);
} else {
child = _react.cloneElement(child, { className: _classnames2['default']('in', child.className) });
}
// This goes after everything else because it adds a wrapping div.
if (rootClose) {
child = _react2['default'].createElement(
_RootCloseWrapper2['default'],
{ onRootClose: props.onHide },
child
);
}
return _react2['default'].createElement(
_Portal2['default'],
{ container: container },
child
);
};
Overlay.prototype.handleHidden = function handleHidden() {
this.setState({ exited: true });
};
return Overlay;
})(_react2['default'].Component);
Overlay.propTypes = _extends({}, _Portal2['default'].propTypes, _Position2['default'].propTypes, {
/**
* Set the visibility of the Overlay
*/
show: _react2['default'].PropTypes.bool,
/**
* Specify whether the overlay should trigger onHide when the user clicks outside the overlay
*/
rootClose: _react2['default'].PropTypes.bool,
/**
* A Callback fired by the Overlay when it wishes to be hidden.
*/
onHide: _react2['default'].PropTypes.func,
/**
* Use animation
*/
animation: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.bool, _utilsCustomPropTypes2['default'].elementType])
});
Overlay.defaultProps = {
animation: _Fade2['default']
};
exports['default'] = Overlay;
module.exports = exports['default'];
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsOverlayPositionUtils = __webpack_require__(82);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Position = (function (_React$Component) {
_inherits(Position, _React$Component);
function Position(props, context) {
_classCallCheck(this, Position);
_React$Component.call(this, props, context);
this.state = {
positionLeft: null,
positionTop: null,
arrowOffsetLeft: null,
arrowOffsetTop: null
};
this._needsFlush = false;
this._lastTarget = null;
}
Position.prototype.componentDidMount = function componentDidMount() {
this.updatePosition();
};
Position.prototype.componentWillReceiveProps = function componentWillReceiveProps() {
this._needsFlush = true;
};
Position.prototype.componentDidUpdate = function componentDidUpdate() {
if (this._needsFlush) {
this._needsFlush = false;
this.updatePosition();
}
};
Position.prototype.componentWillUnmount = function componentWillUnmount() {
// Probably not necessary, but just in case holding a reference to the
// target causes problems somewhere.
this._lastTarget = null;
};
Position.prototype.render = function render() {
var _props = this.props;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['children']);
var _state = this.state;
var positionLeft = _state.positionLeft;
var positionTop = _state.positionTop;
var arrowPosition = _objectWithoutProperties(_state, ['positionLeft', 'positionTop']);
var child = _react2['default'].Children.only(children);
return _react.cloneElement(child, _extends({}, props, arrowPosition, {
positionTop: positionTop,
positionLeft: positionLeft,
style: _extends({}, child.props.style, {
left: positionLeft,
top: positionTop
})
}));
};
Position.prototype.getTargetSafe = function getTargetSafe() {
if (!this.props.target) {
return null;
}
var target = this.props.target(this.props);
if (!target) {
// This is so we can just use === check below on all falsy targets.
return null;
}
return target;
};
Position.prototype.updatePosition = function updatePosition() {
var target = this.getTargetSafe();
if (target === this._lastTarget) {
return;
}
this._lastTarget = target;
if (!target) {
this.setState({
positionLeft: null,
positionTop: null,
arrowOffsetLeft: null,
arrowOffsetTop: null
});
return;
}
var overlay = _react2['default'].findDOMNode(this);
var container = _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body;
this.setState(_utilsOverlayPositionUtils.calcOverlayPosition(this.props.placement, overlay, target, container, this.props.containerPadding));
};
return Position;
})(_react2['default'].Component);
Position.propTypes = {
/**
* Function mapping props to DOM node the component is positioned next to
*/
target: _react2['default'].PropTypes.func,
/**
* "offsetParent" of the component
*/
container: _utilsCustomPropTypes2['default'].mountable,
/**
* Minimum spacing in pixels between container border and component border
*/
containerPadding: _react2['default'].PropTypes.number,
/**
* How to position the component relative to the target
*/
placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left'])
};
Position.defaultProps = {
containerPadding: 0,
placement: 'right'
};
exports['default'] = Position;
module.exports = exports['default'];
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _domUtils = __webpack_require__(31);
var _domUtils2 = _interopRequireDefault(_domUtils);
var utils = {
getContainerDimensions: function getContainerDimensions(containerNode) {
var width = undefined,
height = undefined,
scroll = undefined;
if (containerNode.tagName === 'BODY') {
width = window.innerWidth;
height = window.innerHeight;
scroll = _domUtils2['default'].ownerDocument(containerNode).documentElement.scrollTop || containerNode.scrollTop;
} else {
width = containerNode.offsetWidth;
height = containerNode.offsetHeight;
scroll = containerNode.scrollTop;
}
return { width: width, height: height, scroll: scroll };
},
getPosition: function getPosition(target, container) {
var offset = container.tagName === 'BODY' ? _domUtils2['default'].getOffset(target) : _domUtils2['default'].getPosition(target, container);
return _extends({}, offset, { // eslint-disable-line object-shorthand
height: target.offsetHeight,
width: target.offsetWidth
});
},
calcOverlayPosition: function calcOverlayPosition(placement, overlayNode, target, container, padding) {
var childOffset = utils.getPosition(target, container);
var overlayHeight = overlayNode.offsetHeight;
var overlayWidth = overlayNode.offsetWidth;
var positionLeft = undefined,
positionTop = undefined,
arrowOffsetLeft = undefined,
arrowOffsetTop = undefined;
if (placement === 'left' || placement === 'right') {
positionTop = childOffset.top + (childOffset.height - overlayHeight) / 2;
if (placement === 'left') {
positionLeft = childOffset.left - overlayWidth;
} else {
positionLeft = childOffset.left + childOffset.width;
}
var topDelta = getTopDelta(positionTop, overlayHeight, container, padding);
positionTop += topDelta;
arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%';
arrowOffsetLeft = null;
} else if (placement === 'top' || placement === 'bottom') {
positionLeft = childOffset.left + (childOffset.width - overlayWidth) / 2;
if (placement === 'top') {
positionTop = childOffset.top - overlayHeight;
} else {
positionTop = childOffset.top + childOffset.height;
}
var leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding);
positionLeft += leftDelta;
arrowOffsetLeft = 50 * (1 - 2 * leftDelta / overlayWidth) + '%';
arrowOffsetTop = null;
} else {
throw new Error('calcOverlayPosition(): No such placement of "' + placement + '" found.');
}
return { positionLeft: positionLeft, positionTop: positionTop, arrowOffsetLeft: arrowOffsetLeft, arrowOffsetTop: arrowOffsetTop };
}
};
function getTopDelta(top, overlayHeight, container, padding) {
var containerDimensions = utils.getContainerDimensions(container);
var containerScroll = containerDimensions.scroll;
var containerHeight = containerDimensions.height;
var topEdgeOffset = top - padding - containerScroll;
var bottomEdgeOffset = top + padding - containerScroll + overlayHeight;
if (topEdgeOffset < 0) {
return -topEdgeOffset;
} else if (bottomEdgeOffset > containerHeight) {
return containerHeight - bottomEdgeOffset;
} else {
return 0;
}
}
function getLeftDelta(left, overlayWidth, container, padding) {
var containerDimensions = utils.getContainerDimensions(container);
var containerWidth = containerDimensions.width;
var leftEdgeOffset = left - padding;
var rightEdgeOffset = left + padding + overlayWidth;
if (leftEdgeOffset < 0) {
return -leftEdgeOffset;
} else if (rightEdgeOffset > containerWidth) {
return containerWidth - rightEdgeOffset;
} else {
return 0;
}
}
exports['default'] = utils;
module.exports = exports['default'];
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsDomUtils = __webpack_require__(31);
var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils);
var _utilsEventListener = __webpack_require__(32);
var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener);
// TODO: Merge this logic with dropdown logic once #526 is done.
// TODO: Consider using an ES6 symbol here, once we use babel-runtime.
var CLICK_WAS_INSIDE = '__click_was_inside';
function suppressRootClose(event) {
// Tag the native event to prevent the root close logic on document click.
// This seems safer than using event.nativeEvent.stopImmediatePropagation(),
// which is only supported in IE >= 9.
event.nativeEvent[CLICK_WAS_INSIDE] = true;
}
var RootCloseWrapper = (function (_React$Component) {
_inherits(RootCloseWrapper, _React$Component);
function RootCloseWrapper(props) {
_classCallCheck(this, RootCloseWrapper);
_React$Component.call(this, props);
this.handleDocumentClick = this.handleDocumentClick.bind(this);
this.handleDocumentKeyUp = this.handleDocumentKeyUp.bind(this);
}
RootCloseWrapper.prototype.bindRootCloseHandlers = function bindRootCloseHandlers() {
var doc = _utilsDomUtils2['default'].ownerDocument(this);
this._onDocumentClickListener = _utilsEventListener2['default'].listen(doc, 'click', this.handleDocumentClick);
this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp);
};
RootCloseWrapper.prototype.handleDocumentClick = function handleDocumentClick(e) {
// This is now the native event.
if (e[CLICK_WAS_INSIDE]) {
return;
}
this.props.onRootClose();
};
RootCloseWrapper.prototype.handleDocumentKeyUp = function handleDocumentKeyUp(e) {
if (e.keyCode === 27) {
this.props.onRootClose();
}
};
RootCloseWrapper.prototype.unbindRootCloseHandlers = function unbindRootCloseHandlers() {
if (this._onDocumentClickListener) {
this._onDocumentClickListener.remove();
}
if (this._onDocumentKeyupListener) {
this._onDocumentKeyupListener.remove();
}
};
RootCloseWrapper.prototype.componentDidMount = function componentDidMount() {
this.bindRootCloseHandlers();
};
RootCloseWrapper.prototype.render = function render() {
// Wrap the child in a new element, so the child won't have to handle
// potentially combining multiple onClick listeners.
return _react2['default'].createElement(
'div',
{ onClick: suppressRootClose },
_react2['default'].Children.only(this.props.children)
);
};
RootCloseWrapper.prototype.getWrappedDOMNode = function getWrappedDOMNode() {
// We can't use a ref to identify the wrapped child, since we might be
// stealing the ref from the owner, but we know exactly the DOM structure
// that will be rendered, so we can just do this to get the child's DOM
// node for doing size calculations in OverlayMixin.
return _react2['default'].findDOMNode(this).children[0];
};
RootCloseWrapper.prototype.componentWillUnmount = function componentWillUnmount() {
this.unbindRootCloseHandlers();
};
return RootCloseWrapper;
})(_react2['default'].Component);
exports['default'] = RootCloseWrapper;
RootCloseWrapper.propTypes = {
onRootClose: _react2['default'].PropTypes.func.isRequired
};
module.exports = exports['default'];
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
/*eslint-disable react/prop-types */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var _utilsCreateContextWrapper = __webpack_require__(85);
var _utilsCreateContextWrapper2 = _interopRequireDefault(_utilsCreateContextWrapper);
var _Overlay = __webpack_require__(80);
var _Overlay2 = _interopRequireDefault(_Overlay);
var _reactLibWarning = __webpack_require__(50);
var _reactLibWarning2 = _interopRequireDefault(_reactLibWarning);
/**
* Check if value one is inside or equal to the of value
*
* @param {string} one
* @param {string|array} of
* @returns {boolean}
*/
function isOneOf(one, of) {
if (Array.isArray(of)) {
return of.indexOf(one) >= 0;
}
return one === of;
}
var OverlayTrigger = _react2['default'].createClass({
displayName: 'OverlayTrigger',
propTypes: _extends({}, _Overlay2['default'].propTypes, {
/**
* Specify which action or actions trigger Overlay visibility
*/
trigger: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.oneOf(['click', 'hover', 'focus']), _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.oneOf(['click', 'hover', 'focus']))]),
/**
* A millisecond delay amount to show and hide the Overlay once triggered
*/
delay: _react2['default'].PropTypes.number,
/**
* A millisecond delay amount before showing the Overlay once triggered.
*/
delayShow: _react2['default'].PropTypes.number,
/**
* A millisecond delay amount before hiding the Overlay once triggered.
*/
delayHide: _react2['default'].PropTypes.number,
/**
* The initial visibility state of the Overlay, for more nuanced visibility controll consider
* using the Overlay component directly.
*/
defaultOverlayShown: _react2['default'].PropTypes.bool,
/**
* An element or text to overlay next to the target.
*/
overlay: _react2['default'].PropTypes.node.isRequired,
/**
* @private
*/
onBlur: _react2['default'].PropTypes.func,
/**
* @private
*/
onClick: _react2['default'].PropTypes.func,
/**
* @private
*/
onFocus: _react2['default'].PropTypes.func,
/**
* @private
*/
onMouseEnter: _react2['default'].PropTypes.func,
/**
* @private
*/
onMouseLeave: _react2['default'].PropTypes.func,
//override specific overlay props
/**
* @private
*/
target: function target() {},
/**
* @private
*/
onHide: function onHide() {},
/**
* @private
*/
show: function show() {}
}),
getDefaultProps: function getDefaultProps() {
return {
trigger: ['hover', 'focus']
};
},
getInitialState: function getInitialState() {
return {
isOverlayShown: this.props.defaultOverlayShown == null ? false : this.props.defaultOverlayShown
};
},
show: function show() {
this.setState({
isOverlayShown: true
});
},
hide: function hide() {
this.setState({
isOverlayShown: false
});
},
toggle: function toggle() {
if (this.state.isOverlayShown) {
this.hide();
} else {
this.show();
}
},
componentDidMount: function componentDidMount() {
this._mountNode = document.createElement('div');
_react2['default'].render(this._overlay, this._mountNode);
},
componentWillUnmount: function componentWillUnmount() {
_react2['default'].unmountComponentAtNode(this._mountNode);
this._mountNode = null;
clearTimeout(this._hoverDelay);
},
componentDidUpdate: function componentDidUpdate() {
_react2['default'].render(this._overlay, this._mountNode);
},
getOverlayTarget: function getOverlayTarget() {
return _react2['default'].findDOMNode(this);
},
getOverlay: function getOverlay() {
var props = {
show: this.state.isOverlayShown,
onHide: this.hide,
rootClose: this.props.rootClose,
animation: this.props.animation,
target: this.getOverlayTarget,
placement: this.props.placement,
container: this.props.container,
containerPadding: this.props.containerPadding
};
var overlay = _react.cloneElement(this.props.overlay, {
placement: props.placement,
container: props.container
});
return _react2['default'].createElement(
_Overlay2['default'],
props,
overlay
);
},
render: function render() {
var trigger = _react2['default'].Children.only(this.props.children);
var props = {
'aria-describedby': this.props.overlay.props.id
};
// create in render otherwise owner is lost...
this._overlay = this.getOverlay();
props.onClick = _utilsCreateChainedFunction2['default'](trigger.props.onClick, this.props.onClick);
if (isOneOf('click', this.props.trigger)) {
props.onClick = _utilsCreateChainedFunction2['default'](this.toggle, props.onClick);
}
if (isOneOf('hover', this.props.trigger)) {
_reactLibWarning2['default'](!(this.props.trigger === 'hover'), '[react-bootstrap] Specifying only the `"hover"` trigger limits the visibilty of the overlay to just mouse users. ' + 'Consider also including the `"focus"` trigger so that touch and keyboard only users can see the overlay as well.');
props.onMouseOver = _utilsCreateChainedFunction2['default'](this.handleDelayedShow, this.props.onMouseOver);
props.onMouseOut = _utilsCreateChainedFunction2['default'](this.handleDelayedHide, this.props.onMouseOut);
}
if (isOneOf('focus', this.props.trigger)) {
props.onFocus = _utilsCreateChainedFunction2['default'](this.handleDelayedShow, this.props.onFocus);
props.onBlur = _utilsCreateChainedFunction2['default'](this.handleDelayedHide, this.props.onBlur);
}
return _react.cloneElement(trigger, props);
},
handleDelayedShow: function handleDelayedShow() {
var _this = this;
if (this._hoverDelay != null) {
clearTimeout(this._hoverDelay);
this._hoverDelay = null;
return;
}
var delay = this.props.delayShow != null ? this.props.delayShow : this.props.delay;
if (!delay) {
this.show();
return;
}
this._hoverDelay = setTimeout(function () {
_this._hoverDelay = null;
_this.show();
}, delay);
},
handleDelayedHide: function handleDelayedHide() {
var _this2 = this;
if (this._hoverDelay != null) {
clearTimeout(this._hoverDelay);
this._hoverDelay = null;
return;
}
var delay = this.props.delayHide != null ? this.props.delayHide : this.props.delay;
if (!delay) {
this.hide();
return;
}
this._hoverDelay = setTimeout(function () {
_this2._hoverDelay = null;
_this2.hide();
}, delay);
}
});
/**
* Creates a new OverlayTrigger class that forwards the relevant context
*
* This static method should only be called at the module level, instead of in
* e.g. a render() method, because it's expensive to create new classes.
*
* For example, you would want to have:
*
* > export default OverlayTrigger.withContext({
* > myContextKey: React.PropTypes.object
* > });
*
* and import this when needed.
*/
OverlayTrigger.withContext = _utilsCreateContextWrapper2['default'](OverlayTrigger, 'overlay');
exports['default'] = OverlayTrigger;
module.exports = exports['default'];
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _inherits = __webpack_require__(3)['default'];
var _classCallCheck = __webpack_require__(8)['default'];
var _extends = __webpack_require__(9)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
exports['default'] = createContextWrapper;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
/**
* Creates new trigger class that injects context into overlay.
*/
function createContextWrapper(Trigger, propName) {
return function (contextTypes) {
var ContextWrapper = (function (_React$Component) {
_inherits(ContextWrapper, _React$Component);
function ContextWrapper() {
_classCallCheck(this, ContextWrapper);
_React$Component.apply(this, arguments);
}
ContextWrapper.prototype.getChildContext = function getChildContext() {
return this.props.context;
};
ContextWrapper.prototype.render = function render() {
// Strip injected props from below.
var _props = this.props;
var wrapped = _props.wrapped;
var context = _props.context;
var props = _objectWithoutProperties(_props, ['wrapped', 'context']);
return _react2['default'].cloneElement(wrapped, props);
};
return ContextWrapper;
})(_react2['default'].Component);
ContextWrapper.childContextTypes = contextTypes;
var TriggerWithContext = (function () {
function TriggerWithContext() {
_classCallCheck(this, TriggerWithContext);
}
TriggerWithContext.prototype.render = function render() {
var props = _extends({}, this.props);
props[propName] = this.getWrappedOverlay();
return _react2['default'].createElement(
Trigger,
props,
this.props.children
);
};
TriggerWithContext.prototype.getWrappedOverlay = function getWrappedOverlay() {
return _react2['default'].createElement(ContextWrapper, {
context: this.context,
wrapped: this.props[propName]
});
};
return TriggerWithContext;
})();
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
module.exports = exports['default'];
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var PageHeader = _react2['default'].createClass({
displayName: 'PageHeader',
render: function render() {
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'page-header') }),
_react2['default'].createElement(
'h1',
null,
this.props.children
)
);
}
});
exports['default'] = PageHeader;
module.exports = exports['default'];
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var PageItem = _react2['default'].createClass({
displayName: 'PageItem',
propTypes: {
href: _react2['default'].PropTypes.string,
target: _react2['default'].PropTypes.string,
title: _react2['default'].PropTypes.string,
disabled: _react2['default'].PropTypes.bool,
previous: _react2['default'].PropTypes.bool,
next: _react2['default'].PropTypes.bool,
onSelect: _react2['default'].PropTypes.func,
eventKey: _react2['default'].PropTypes.any
},
render: function render() {
var classes = {
'disabled': this.props.disabled,
'previous': this.props.previous,
'next': this.props.next
};
return _react2['default'].createElement(
'li',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, classes) }),
_react2['default'].createElement(
_SafeAnchor2['default'],
{
href: this.props.href,
title: this.props.title,
target: this.props.target,
onClick: this.handleSelect },
this.props.children
)
);
},
handleSelect: function handleSelect(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
exports['default'] = PageItem;
module.exports = exports['default'];
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var Pager = _react2['default'].createClass({
displayName: 'Pager',
propTypes: {
onSelect: _react2['default'].PropTypes.func
},
render: function render() {
return _react2['default'].createElement(
'ul',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, 'pager') }),
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderPageItem)
);
},
renderPageItem: function renderPageItem(child, index) {
return _react.cloneElement(child, {
onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect),
key: child.key ? child.key : index
});
}
});
exports['default'] = Pager;
module.exports = exports['default'];
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _PaginationButton = __webpack_require__(90);
var _PaginationButton2 = _interopRequireDefault(_PaginationButton);
var Pagination = _react2['default'].createClass({
displayName: 'Pagination',
mixins: [_BootstrapMixin2['default']],
propTypes: {
activePage: _react2['default'].PropTypes.number,
items: _react2['default'].PropTypes.number,
maxButtons: _react2['default'].PropTypes.number,
ellipsis: _react2['default'].PropTypes.bool,
first: _react2['default'].PropTypes.bool,
last: _react2['default'].PropTypes.bool,
prev: _react2['default'].PropTypes.bool,
next: _react2['default'].PropTypes.bool,
onSelect: _react2['default'].PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
activePage: 1,
items: 1,
maxButtons: 0,
first: false,
last: false,
prev: false,
next: false,
ellipsis: true,
bsClass: 'pagination'
};
},
renderPageButtons: function renderPageButtons() {
var pageButtons = [];
var startPage = undefined,
endPage = undefined,
hasHiddenPagesAfter = undefined;
var _props = this.props;
var maxButtons = _props.maxButtons;
var activePage = _props.activePage;
var items = _props.items;
var onSelect = _props.onSelect;
var ellipsis = _props.ellipsis;
if (maxButtons) {
var hiddenPagesBefore = activePage - parseInt(maxButtons / 2);
startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1;
hasHiddenPagesAfter = startPage + maxButtons <= items;
if (!hasHiddenPagesAfter) {
endPage = items;
startPage = items - maxButtons + 1;
if (startPage < 1) {
startPage = 1;
}
} else {
endPage = startPage + maxButtons - 1;
}
} else {
startPage = 1;
endPage = items;
}
for (var pagenumber = startPage; pagenumber <= endPage; pagenumber++) {
pageButtons.push(_react2['default'].createElement(
_PaginationButton2['default'],
{
key: pagenumber,
eventKey: pagenumber,
active: pagenumber === activePage,
onSelect: onSelect },
pagenumber
));
}
if (maxButtons && hasHiddenPagesAfter && ellipsis) {
pageButtons.push(_react2['default'].createElement(
_PaginationButton2['default'],
{
key: 'ellipsis',
disabled: true },
_react2['default'].createElement(
'span',
{ 'aria-label': 'More' },
'...'
)
));
}
return pageButtons;
},
renderPrev: function renderPrev() {
if (!this.props.prev) {
return null;
}
return _react2['default'].createElement(
_PaginationButton2['default'],
{
key: 'prev',
eventKey: this.props.activePage - 1,
disabled: this.props.activePage === 1,
onSelect: this.props.onSelect },
_react2['default'].createElement(
'span',
{ 'aria-label': 'Previous' },
'‹'
)
);
},
renderNext: function renderNext() {
if (!this.props.next) {
return null;
}
return _react2['default'].createElement(
_PaginationButton2['default'],
{
key: 'next',
eventKey: this.props.activePage + 1,
disabled: this.props.activePage >= this.props.items,
onSelect: this.props.onSelect },
_react2['default'].createElement(
'span',
{ 'aria-label': 'Next' },
'›'
)
);
},
renderFirst: function renderFirst() {
if (!this.props.first) {
return null;
}
return _react2['default'].createElement(
_PaginationButton2['default'],
{
key: 'first',
eventKey: 1,
disabled: this.props.activePage === 1,
onSelect: this.props.onSelect },
_react2['default'].createElement(
'span',
{ 'aria-label': 'First' },
'«'
)
);
},
renderLast: function renderLast() {
if (!this.props.last) {
return null;
}
return _react2['default'].createElement(
_PaginationButton2['default'],
{
key: 'last',
eventKey: this.props.items,
disabled: this.props.activePage >= this.props.items,
onSelect: this.props.onSelect },
_react2['default'].createElement(
'span',
{ 'aria-label': 'Last' },
'»'
)
);
},
render: function render() {
return _react2['default'].createElement(
'ul',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, this.getBsClassSet()) }),
this.renderFirst(),
this.renderPrev(),
this.renderPageButtons(),
this.renderNext(),
this.renderLast()
);
}
});
exports['default'] = Pagination;
module.exports = exports['default'];
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsCreateSelectedEvent = __webpack_require__(91);
var _utilsCreateSelectedEvent2 = _interopRequireDefault(_utilsCreateSelectedEvent);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var PaginationButton = _react2['default'].createClass({
displayName: 'PaginationButton',
mixins: [_BootstrapMixin2['default']],
propTypes: {
className: _react2['default'].PropTypes.string,
eventKey: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]),
onSelect: _react2['default'].PropTypes.func,
disabled: _react2['default'].PropTypes.bool,
active: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
active: false,
disabled: false
};
},
handleClick: function handleClick(event) {
if (this.props.onSelect) {
var selectedEvent = _utilsCreateSelectedEvent2['default'](this.props.eventKey);
this.props.onSelect(event, selectedEvent);
}
},
render: function render() {
var classes = _extends({
active: this.props.active,
disabled: this.props.disabled
}, this.getBsClassSet());
var _props = this.props;
var className = _props.className;
var anchorProps = _objectWithoutProperties(_props, ['className']);
return _react2['default'].createElement(
'li',
{ className: _classnames2['default'](className, classes) },
_react2['default'].createElement(_SafeAnchor2['default'], _extends({}, anchorProps, {
onClick: this.handleClick }))
);
}
});
exports['default'] = PaginationButton;
module.exports = exports['default'];
// eslint-disable-line object-shorthand
/***/ },
/* 91 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = createSelectedEvent;
function createSelectedEvent(eventKey) {
var selectionPrevented = false;
return {
eventKey: eventKey,
preventSelection: function preventSelection() {
selectionPrevented = true;
},
isSelectionPrevented: function isSelectionPrevented() {
return selectionPrevented;
}
};
}
module.exports = exports["default"];
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _Collapse = __webpack_require__(53);
var _Collapse2 = _interopRequireDefault(_Collapse);
var Panel = _react2['default'].createClass({
displayName: 'Panel',
mixins: [_BootstrapMixin2['default']],
propTypes: {
collapsible: _react2['default'].PropTypes.bool,
onSelect: _react2['default'].PropTypes.func,
header: _react2['default'].PropTypes.node,
id: _react2['default'].PropTypes.string,
footer: _react2['default'].PropTypes.node,
defaultExpanded: _react2['default'].PropTypes.bool,
expanded: _react2['default'].PropTypes.bool,
eventKey: _react2['default'].PropTypes.any
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'panel',
bsStyle: 'default'
};
},
getInitialState: function getInitialState() {
var defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : this.props.expanded != null ? this.props.expanded : false;
return {
expanded: defaultExpanded
};
},
handleSelect: function handleSelect(e) {
e.selected = true;
if (this.props.onSelect) {
this.props.onSelect(e, this.props.eventKey);
} else {
e.preventDefault();
}
if (e.selected) {
this.handleToggle();
}
},
handleToggle: function handleToggle() {
this.setState({ expanded: !this.state.expanded });
},
isExpanded: function isExpanded() {
return this.props.expanded != null ? this.props.expanded : this.state.expanded;
},
render: function render() {
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: _classnames2['default'](this.props.className, this.getBsClassSet()),
id: this.props.collapsible ? null : this.props.id, onSelect: null }),
this.renderHeading(),
this.props.collapsible ? this.renderCollapsibleBody() : this.renderBody(),
this.renderFooter()
);
},
renderCollapsibleBody: function renderCollapsibleBody() {
var collapseClass = this.prefixClass('collapse');
return _react2['default'].createElement(
_Collapse2['default'],
{ 'in': this.isExpanded() },
_react2['default'].createElement(
'div',
{
className: collapseClass,
id: this.props.id,
ref: 'panel',
'aria-expanded': this.isExpanded() },
this.renderBody()
)
);
},
renderBody: function renderBody() {
var allChildren = this.props.children;
var bodyElements = [];
var panelBodyChildren = [];
var bodyClass = this.prefixClass('body');
function getProps() {
return { key: bodyElements.length };
}
function addPanelChild(child) {
bodyElements.push(_react.cloneElement(child, getProps()));
}
function addPanelBody(children) {
bodyElements.push(_react2['default'].createElement(
'div',
_extends({ className: bodyClass }, getProps()),
children
));
}
function maybeRenderPanelBody() {
if (panelBodyChildren.length === 0) {
return;
}
addPanelBody(panelBodyChildren);
panelBodyChildren = [];
}
// Handle edge cases where we should not iterate through children.
if (!Array.isArray(allChildren) || allChildren.length === 0) {
if (this.shouldRenderFill(allChildren)) {
addPanelChild(allChildren);
} else {
addPanelBody(allChildren);
}
} else {
allChildren.forEach((function (child) {
if (this.shouldRenderFill(child)) {
maybeRenderPanelBody();
// Separately add the filled element.
addPanelChild(child);
} else {
panelBodyChildren.push(child);
}
}).bind(this));
maybeRenderPanelBody();
}
return bodyElements;
},
shouldRenderFill: function shouldRenderFill(child) {
return _react2['default'].isValidElement(child) && child.props.fill != null;
},
renderHeading: function renderHeading() {
var header = this.props.header;
if (!header) {
return null;
}
if (!_react2['default'].isValidElement(header) || Array.isArray(header)) {
header = this.props.collapsible ? this.renderCollapsibleTitle(header) : header;
} else {
var className = _classnames2['default'](this.prefixClass('title'), header.props.className);
if (this.props.collapsible) {
header = _react.cloneElement(header, {
className: className,
children: this.renderAnchor(header.props.children)
});
} else {
header = _react.cloneElement(header, { className: className });
}
}
return _react2['default'].createElement(
'div',
{ className: this.prefixClass('heading') },
header
);
},
renderAnchor: function renderAnchor(header) {
return _react2['default'].createElement(
'a',
{
href: '#' + (this.props.id || ''),
'aria-controls': this.props.collapsible ? this.props.id : null,
className: this.isExpanded() ? null : 'collapsed',
'aria-expanded': this.isExpanded(),
onClick: this.handleSelect },
header
);
},
renderCollapsibleTitle: function renderCollapsibleTitle(header) {
return _react2['default'].createElement(
'h4',
{ className: this.prefixClass('title') },
this.renderAnchor(header)
);
},
renderFooter: function renderFooter() {
if (!this.props.footer) {
return null;
}
return _react2['default'].createElement(
'div',
{ className: this.prefixClass('footer') },
this.props.footer
);
}
});
exports['default'] = Panel;
module.exports = exports['default'];
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
/* eslint-disable react/no-multi-comp */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Popover = _react2['default'].createClass({
displayName: 'Popover',
mixins: [_BootstrapMixin2['default']],
propTypes: {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: _utilsCustomPropTypes2['default'].isRequiredForA11y(_react2['default'].PropTypes.string),
/**
* Sets the direction the Popover is positioned towards.
*/
placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "left" position value for the Popover.
*/
positionLeft: _react2['default'].PropTypes.number,
/**
* The "top" position value for the Popover.
*/
positionTop: _react2['default'].PropTypes.number,
/**
* The "left" position value for the Popover arrow.
*/
arrowOffsetLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]),
/**
* The "top" position value for the Popover arrow.
*/
arrowOffsetTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]),
/**
* Title text
*/
title: _react2['default'].PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
placement: 'right'
};
},
render: function render() {
var _classes;
var classes = (_classes = {
'popover': true
}, _classes[this.props.placement] = true, _classes);
var style = {
'left': this.props.positionLeft,
'top': this.props.positionTop,
'display': 'block'
};
var arrowStyle = {
'left': this.props.arrowOffsetLeft,
'top': this.props.arrowOffsetTop
};
return _react2['default'].createElement(
'div',
_extends({ role: 'tooltip' }, this.props, { className: _classnames2['default'](this.props.className, classes), style: style, title: null }),
_react2['default'].createElement('div', { className: 'arrow', style: arrowStyle }),
this.props.title ? this.renderTitle() : null,
_react2['default'].createElement(
'div',
{ className: 'popover-content' },
this.props.children
)
);
},
renderTitle: function renderTitle() {
return _react2['default'].createElement(
'h3',
{ className: 'popover-title' },
this.props.title
);
}
});
exports['default'] = Popover;
module.exports = exports['default'];
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
/* eslint react/prop-types: [2, {ignore: "bsStyle"}] */
/* BootstrapMixin contains `bsStyle` type validation */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _Interpolate = __webpack_require__(64);
var _Interpolate2 = _interopRequireDefault(_Interpolate);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var ProgressBar = _react2['default'].createClass({
displayName: 'ProgressBar',
propTypes: {
min: _react.PropTypes.number,
now: _react.PropTypes.number,
max: _react.PropTypes.number,
label: _react.PropTypes.node,
srOnly: _react.PropTypes.bool,
striped: _react.PropTypes.bool,
active: _react.PropTypes.bool,
children: onlyProgressBar,
className: _react2['default'].PropTypes.string,
interpolateClass: _react.PropTypes.node,
isChild: _react.PropTypes.bool
},
mixins: [_BootstrapMixin2['default']],
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'progress-bar',
min: 0,
max: 100
};
},
getPercentage: function getPercentage(now, min, max) {
var roundPrecision = 1000;
return Math.round((now - min) / (max - min) * 100 * roundPrecision) / roundPrecision;
},
render: function render() {
if (this.props.isChild) {
return this.renderProgressBar();
}
var content = undefined;
if (this.props.children) {
content = _utilsValidComponentChildren2['default'].map(this.props.children, this.renderChildBar);
} else {
content = this.renderProgressBar();
}
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'progress') }),
content
);
},
renderChildBar: function renderChildBar(child, index) {
return _react.cloneElement(child, {
isChild: true,
key: child.key ? child.key : index
});
},
renderProgressBar: function renderProgressBar() {
var percentage = this.getPercentage(this.props.now, this.props.min, this.props.max);
var label = undefined;
if (typeof this.props.label === 'string') {
label = this.renderLabel(percentage);
} else {
label = this.props.label;
}
if (this.props.srOnly) {
label = _react2['default'].createElement(
'span',
{ className: 'sr-only' },
label
);
}
var classes = _classnames2['default'](this.props.className, this.getBsClassSet(), {
active: this.props.active,
'progress-bar-striped': this.props.active || this.props.striped
});
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
className: classes,
role: 'progressbar',
style: { width: percentage + '%' },
'aria-valuenow': this.props.now,
'aria-valuemin': this.props.min,
'aria-valuemax': this.props.max }),
label
);
},
renderLabel: function renderLabel(percentage) {
var InterpolateClass = this.props.interpolateClass || _Interpolate2['default'];
return _react2['default'].createElement(
InterpolateClass,
{
now: this.props.now,
min: this.props.min,
max: this.props.max,
percent: percentage,
bsStyle: this.props.bsStyle },
this.props.label
);
}
});
/**
* Custom propTypes checker
*/
function onlyProgressBar(props, propName, componentName) {
if (props[propName]) {
var _ret = (function () {
var error = undefined,
childIdentifier = undefined;
_react2['default'].Children.forEach(props[propName], function (child) {
if (child.type !== ProgressBar) {
childIdentifier = child.type.displayName ? child.type.displayName : child.type;
error = new Error('Children of ' + componentName + ' can contain only ProgressBar components. Found ' + childIdentifier);
}
});
return {
v: error
};
})();
if (typeof _ret === 'object') return _ret.v;
}
}
exports['default'] = ProgressBar;
module.exports = exports['default'];
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Row = _react2['default'].createClass({
displayName: 'Row',
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: _utilsCustomPropTypes2['default'].elementType
},
getDefaultProps: function getDefaultProps() {
return {
componentClass: 'div'
};
},
render: function render() {
var ComponentClass = this.props.componentClass;
return _react2['default'].createElement(
ComponentClass,
_extends({}, this.props, { className: _classnames2['default'](this.props.className, 'row') }),
this.props.children
);
}
});
exports['default'] = Row;
module.exports = exports['default'];
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
/* eslint react/prop-types: [2, {ignore: "bsSize"}] */
/* BootstrapMixin contains `bsSize` type validation */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _DropdownStateMixin = __webpack_require__(57);
var _DropdownStateMixin2 = _interopRequireDefault(_DropdownStateMixin);
var _Button = __webpack_require__(35);
var _Button2 = _interopRequireDefault(_Button);
var _ButtonGroup = __webpack_require__(41);
var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup);
var _DropdownMenu = __webpack_require__(58);
var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu);
var SplitButton = _react2['default'].createClass({
displayName: 'SplitButton',
mixins: [_BootstrapMixin2['default'], _DropdownStateMixin2['default']],
propTypes: {
pullRight: _react2['default'].PropTypes.bool,
title: _react2['default'].PropTypes.node,
href: _react2['default'].PropTypes.string,
id: _react2['default'].PropTypes.string,
target: _react2['default'].PropTypes.string,
dropdownTitle: _react2['default'].PropTypes.node,
dropup: _react2['default'].PropTypes.bool,
onClick: _react2['default'].PropTypes.func,
onSelect: _react2['default'].PropTypes.func,
disabled: _react2['default'].PropTypes.bool,
className: _react2['default'].PropTypes.string,
children: _react2['default'].PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
dropdownTitle: 'Toggle dropdown'
};
},
render: function render() {
var groupClasses = {
'open': this.state.open,
'dropup': this.props.dropup
};
var button = _react2['default'].createElement(
_Button2['default'],
_extends({}, this.props, {
ref: 'button',
onClick: this.handleButtonClick,
title: null,
id: null }),
this.props.title
);
var dropdownButton = _react2['default'].createElement(
_Button2['default'],
_extends({}, this.props, {
ref: 'dropdownButton',
className: _classnames2['default'](this.props.className, 'dropdown-toggle'),
onClick: this.handleDropdownClick,
title: null,
href: null,
target: null,
id: null }),
_react2['default'].createElement(
'span',
{ className: 'sr-only' },
this.props.dropdownTitle
),
_react2['default'].createElement('span', { className: 'caret' }),
_react2['default'].createElement(
'span',
{ style: { letterSpacing: '-.3em' } },
' '
)
);
return _react2['default'].createElement(
_ButtonGroup2['default'],
{
bsSize: this.props.bsSize,
className: _classnames2['default'](groupClasses),
id: this.props.id },
button,
dropdownButton,
_react2['default'].createElement(
_DropdownMenu2['default'],
{
ref: 'menu',
onSelect: this.handleOptionSelect,
'aria-labelledby': this.props.id,
pullRight: this.props.pullRight },
this.props.children
)
);
},
handleButtonClick: function handleButtonClick(e) {
if (this.state.open) {
this.setDropdownState(false);
}
if (this.props.onClick) {
this.props.onClick(e, this.props.href, this.props.target);
}
},
handleDropdownClick: function handleDropdownClick(e) {
e.preventDefault();
this.setDropdownState(!this.state.open);
},
handleOptionSelect: function handleOptionSelect(key) {
if (this.props.onSelect) {
this.props.onSelect(key);
}
this.setDropdownState(false);
}
});
exports['default'] = SplitButton;
module.exports = exports['default'];
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _utilsCreateChainedFunction = __webpack_require__(55);
var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var SubNav = _react2['default'].createClass({
displayName: 'SubNav',
mixins: [_BootstrapMixin2['default']],
propTypes: {
onSelect: _react2['default'].PropTypes.func,
active: _react2['default'].PropTypes.bool,
activeHref: _react2['default'].PropTypes.string,
activeKey: _react2['default'].PropTypes.any,
disabled: _react2['default'].PropTypes.bool,
eventKey: _react2['default'].PropTypes.any,
href: _react2['default'].PropTypes.string,
title: _react2['default'].PropTypes.string,
text: _react2['default'].PropTypes.node,
target: _react2['default'].PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'nav'
};
},
handleClick: function handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
},
isActive: function isActive() {
return this.isChildActive(this);
},
isChildActive: function isChildActive(child) {
if (child.props.active) {
return true;
}
if (this.props.activeKey != null && this.props.activeKey === child.props.eventKey) {
return true;
}
if (this.props.activeHref != null && this.props.activeHref === child.props.href) {
return true;
}
if (child.props.children) {
var isActive = false;
_utilsValidComponentChildren2['default'].forEach(child.props.children, function (grandchild) {
if (this.isChildActive(grandchild)) {
isActive = true;
}
}, this);
return isActive;
}
return false;
},
getChildActiveProp: function getChildActiveProp(child) {
if (child.props.active) {
return true;
}
if (this.props.activeKey != null) {
if (child.props.eventKey === this.props.activeKey) {
return true;
}
}
if (this.props.activeHref != null) {
if (child.props.href === this.props.activeHref) {
return true;
}
}
return child.props.active;
},
render: function render() {
var classes = {
'active': this.isActive(),
'disabled': this.props.disabled
};
return _react2['default'].createElement(
'li',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
_react2['default'].createElement(
_SafeAnchor2['default'],
{
href: this.props.href,
title: this.props.title,
target: this.props.target,
onClick: this.handleClick },
this.props.text
),
_react2['default'].createElement(
'ul',
{ className: 'nav' },
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderNavItem)
)
);
},
renderNavItem: function renderNavItem(child, index) {
return _react.cloneElement(child, {
active: this.getChildActiveProp(child),
onSelect: _utilsCreateChainedFunction2['default'](child.props.onSelect, this.props.onSelect),
key: child.key ? child.key : index
});
}
});
exports['default'] = SubNav;
module.exports = exports['default'];
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _objectWithoutProperties = __webpack_require__(37)['default'];
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsValidComponentChildren = __webpack_require__(28);
var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren);
var _Nav = __webpack_require__(77);
var _Nav2 = _interopRequireDefault(_Nav);
var _NavItem = __webpack_require__(79);
var _NavItem2 = _interopRequireDefault(_NavItem);
var panelId = function panelId(props, child) {
return child.props.id ? child.props.id : props.id && props.id + '___panel___' + child.props.eventKey;
};
var tabId = function tabId(props, child) {
return child.props.id ? child.props.id + '___tab' : props.id && props.id + '___tab___' + child.props.eventKey;
};
function getDefaultActiveKeyFromChildren(children) {
var defaultActiveKey = undefined;
_utilsValidComponentChildren2['default'].forEach(children, function (child) {
if (defaultActiveKey == null) {
defaultActiveKey = child.props.eventKey;
}
});
return defaultActiveKey;
}
var TabbedArea = _react2['default'].createClass({
displayName: 'TabbedArea',
mixins: [_BootstrapMixin2['default']],
propTypes: {
activeKey: _react2['default'].PropTypes.any,
defaultActiveKey: _react2['default'].PropTypes.any,
bsStyle: _react2['default'].PropTypes.oneOf(['tabs', 'pills']),
animation: _react2['default'].PropTypes.bool,
id: _react2['default'].PropTypes.string,
onSelect: _react2['default'].PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
bsStyle: 'tabs',
animation: true
};
},
getInitialState: function getInitialState() {
var defaultActiveKey = this.props.defaultActiveKey != null ? this.props.defaultActiveKey : getDefaultActiveKeyFromChildren(this.props.children);
return {
activeKey: defaultActiveKey,
previousActiveKey: null
};
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (nextProps.activeKey != null && nextProps.activeKey !== this.props.activeKey) {
this.setState({
previousActiveKey: this.props.activeKey
});
}
},
handlePaneAnimateOutEnd: function handlePaneAnimateOutEnd() {
this.setState({
previousActiveKey: null
});
},
render: function render() {
var _props = this.props;
var id = _props.id;
var props = _objectWithoutProperties(_props, ['id']);
var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey;
function renderTabIfSet(child) {
return child.props.tab != null ? this.renderTab(child) : null;
}
var nav = _react2['default'].createElement(
_Nav2['default'],
_extends({}, props, { activeKey: activeKey, onSelect: this.handleSelect, ref: 'tabs' }),
_utilsValidComponentChildren2['default'].map(this.props.children, renderTabIfSet, this)
);
return _react2['default'].createElement(
'div',
null,
nav,
_react2['default'].createElement(
'div',
{ id: id, className: 'tab-content', ref: 'panes' },
_utilsValidComponentChildren2['default'].map(this.props.children, this.renderPane)
)
);
},
getActiveKey: function getActiveKey() {
return this.props.activeKey != null ? this.props.activeKey : this.state.activeKey;
},
renderPane: function renderPane(child, index) {
var activeKey = this.getActiveKey();
var active = child.props.eventKey === activeKey && (this.state.previousActiveKey == null || !this.props.animation);
return _react.cloneElement(child, {
active: active,
id: panelId(this.props, child),
'aria-labelledby': tabId(this.props, child),
key: child.key ? child.key : index,
animation: this.props.animation,
onAnimateOutEnd: this.state.previousActiveKey != null && child.props.eventKey === this.state.previousActiveKey ? this.handlePaneAnimateOutEnd : null
});
},
renderTab: function renderTab(child) {
var _child$props = child.props;
var eventKey = _child$props.eventKey;
var className = _child$props.className;
var tab = _child$props.tab;
var disabled = _child$props.disabled;
return _react2['default'].createElement(
_NavItem2['default'],
{
linkId: tabId(this.props, child),
ref: 'tab' + eventKey,
'aria-controls': panelId(this.props, child),
eventKey: eventKey,
className: className,
disabled: disabled },
tab
);
},
shouldComponentUpdate: function shouldComponentUpdate() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleSelect: function handleSelect(key) {
if (this.props.onSelect) {
this._isChanging = true;
this.props.onSelect(key);
this._isChanging = false;
} else if (key !== this.getActiveKey()) {
this.setState({
activeKey: key,
previousActiveKey: this.getActiveKey()
});
}
}
});
exports['default'] = TabbedArea;
module.exports = exports['default'];
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var Table = _react2['default'].createClass({
displayName: 'Table',
propTypes: {
striped: _react2['default'].PropTypes.bool,
bordered: _react2['default'].PropTypes.bool,
condensed: _react2['default'].PropTypes.bool,
hover: _react2['default'].PropTypes.bool,
responsive: _react2['default'].PropTypes.bool
},
render: function render() {
var classes = {
'table': true,
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed,
'table-hover': this.props.hover
};
var table = _react2['default'].createElement(
'table',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
return this.props.responsive ? _react2['default'].createElement(
'div',
{ className: 'table-responsive' },
table
) : table;
}
});
exports['default'] = Table;
module.exports = exports['default'];
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsTransitionEvents = __webpack_require__(46);
var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents);
var TabPane = _react2['default'].createClass({
displayName: 'TabPane',
propTypes: {
active: _react2['default'].PropTypes.bool,
animation: _react2['default'].PropTypes.bool,
onAnimateOutEnd: _react2['default'].PropTypes.func,
disabled: _react2['default'].PropTypes.bool
},
getDefaultProps: function getDefaultProps() {
return {
animation: true
};
},
getInitialState: function getInitialState() {
return {
animateIn: false,
animateOut: false
};
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.animation) {
if (!this.state.animateIn && nextProps.active && !this.props.active) {
this.setState({
animateIn: true
});
} else if (!this.state.animateOut && !nextProps.active && this.props.active) {
this.setState({
animateOut: true
});
}
}
},
componentDidUpdate: function componentDidUpdate() {
if (this.state.animateIn) {
setTimeout(this.startAnimateIn, 0);
}
if (this.state.animateOut) {
_utilsTransitionEvents2['default'].addEndEventListener(_react2['default'].findDOMNode(this), this.stopAnimateOut);
}
},
startAnimateIn: function startAnimateIn() {
if (this.isMounted()) {
this.setState({
animateIn: false
});
}
},
stopAnimateOut: function stopAnimateOut() {
if (this.isMounted()) {
this.setState({
animateOut: false
});
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd();
}
}
},
render: function render() {
var classes = {
'tab-pane': true,
'fade': true,
'active': this.props.active || this.state.animateOut,
'in': this.props.active && !this.state.animateIn
};
return _react2['default'].createElement(
'div',
_extends({}, this.props, {
role: 'tabpanel',
'aria-hidden': !this.props.active,
className: _classnames2['default'](this.props.className, classes)
}),
this.props.children
);
}
});
exports['default'] = TabPane;
module.exports = exports['default'];
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _SafeAnchor = __webpack_require__(69);
var _SafeAnchor2 = _interopRequireDefault(_SafeAnchor);
var Thumbnail = _react2['default'].createClass({
displayName: 'Thumbnail',
mixins: [_BootstrapMixin2['default']],
propTypes: {
alt: _react2['default'].PropTypes.string,
href: _react2['default'].PropTypes.string,
src: _react2['default'].PropTypes.string
},
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'thumbnail'
};
},
render: function render() {
var classes = this.getBsClassSet();
if (this.props.href) {
return _react2['default'].createElement(
_SafeAnchor2['default'],
_extends({}, this.props, { href: this.props.href, className: _classnames2['default'](this.props.className, classes) }),
_react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt })
);
} else {
if (this.props.children) {
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
_react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }),
_react2['default'].createElement(
'div',
{ className: 'caption' },
this.props.children
)
);
} else {
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
_react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt })
);
}
}
}
});
exports['default'] = Thumbnail;
module.exports = exports['default'];
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
/* eslint-disable react/no-multi-comp */
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var _utilsCustomPropTypes = __webpack_require__(23);
var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes);
var Tooltip = _react2['default'].createClass({
displayName: 'Tooltip',
mixins: [_BootstrapMixin2['default']],
propTypes: {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: _utilsCustomPropTypes2['default'].isRequiredForA11y(_react2['default'].PropTypes.string),
/**
* Sets the direction the Tooltip is positioned towards.
*/
placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "left" position value for the Tooltip.
*/
positionLeft: _react2['default'].PropTypes.number,
/**
* The "top" position value for the Tooltip.
*/
positionTop: _react2['default'].PropTypes.number,
/**
* The "left" position value for the Tooltip arrow.
*/
arrowOffsetLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]),
/**
* The "top" position value for the Tooltip arrow.
*/
arrowOffsetTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]),
/**
* Title text
*/
title: _react2['default'].PropTypes.node
},
getDefaultProps: function getDefaultProps() {
return {
placement: 'right'
};
},
render: function render() {
var _classes;
var classes = (_classes = {
'tooltip': true
}, _classes[this.props.placement] = true, _classes);
var style = _extends({
'left': this.props.positionLeft,
'top': this.props.positionTop
}, this.props.style);
var arrowStyle = {
'left': this.props.arrowOffsetLeft,
'top': this.props.arrowOffsetTop
};
return _react2['default'].createElement(
'div',
_extends({ role: 'tooltip' }, this.props, { className: _classnames2['default'](this.props.className, classes), style: style }),
_react2['default'].createElement('div', { className: 'tooltip-arrow', style: arrowStyle }),
_react2['default'].createElement(
'div',
{ className: 'tooltip-inner' },
this.props.children
)
);
}
});
exports['default'] = Tooltip;
module.exports = exports['default'];
// we don't want to expose the `style` property
// eslint-disable-line react/prop-types
/***/ },
/* 103 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _extends = __webpack_require__(9)['default'];
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _react = __webpack_require__(16);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(17);
var _classnames2 = _interopRequireDefault(_classnames);
var _BootstrapMixin = __webpack_require__(21);
var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin);
var Well = _react2['default'].createClass({
displayName: 'Well',
mixins: [_BootstrapMixin2['default']],
getDefaultProps: function getDefaultProps() {
return {
bsClass: 'well'
};
},
render: function render() {
var classes = this.getBsClassSet();
return _react2['default'].createElement(
'div',
_extends({}, this.props, { className: _classnames2['default'](this.props.className, classes) }),
this.props.children
);
}
});
exports['default'] = Well;
module.exports = exports['default'];
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(2)['default'];
exports.__esModule = true;
var _childrenValueInputValidation2 = __webpack_require__(40);
var _childrenValueInputValidation3 = _interopRequireDefault(_childrenValueInputValidation2);
exports.childrenValueInputValidation = _childrenValueInputValidation3['default'];
var _createChainedFunction2 = __webpack_require__(55);
var _createChainedFunction3 = _interopRequireDefault(_createChainedFunction2);
exports.createChainedFunction = _createChainedFunction3['default'];
var _CustomPropTypes2 = __webpack_require__(23);
var _CustomPropTypes3 = _interopRequireDefault(_CustomPropTypes2);
exports.CustomPropTypes = _CustomPropTypes3['default'];
var _domUtils2 = __webpack_require__(31);
var _domUtils3 = _interopRequireDefault(_domUtils2);
exports.domUtils = _domUtils3['default'];
var _ValidComponentChildren2 = __webpack_require__(28);
var _ValidComponentChildren3 = _interopRequireDefault(_ValidComponentChildren2);
exports.ValidComponentChildren = _ValidComponentChildren3['default'];
/***/ }
/******/ ])
});
; |
test/PanelGroupSpec.js | AlexKVal/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import PanelGroup from '../src/PanelGroup';
import Panel from '../src/Panel';
describe('PanelGroup', function () {
it('Should pass bsStyle to Panels', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PanelGroup bsStyle="default">
<Panel>Panel 1</Panel>
</PanelGroup>
);
let panel = ReactTestUtils.findRenderedComponentWithType(instance, Panel);
assert.equal(panel.props.bsStyle, 'default');
});
it('Should not override bsStyle on Panel', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PanelGroup bsStyle="default">
<Panel bsStyle="primary">Panel 1</Panel>
</PanelGroup>
);
let panel = ReactTestUtils.findRenderedComponentWithType(instance, Panel);
assert.equal(panel.props.bsStyle, 'primary');
});
it('Should not collapse panel by bubbling onSelect callback', function () {
let instance = ReactTestUtils.renderIntoDocument(
<PanelGroup accordion>
<Panel>
<input type="text" className="changeme" />
</Panel>
</PanelGroup>
);
let panel = ReactTestUtils.findRenderedComponentWithType(instance, Panel);
assert.notOk(panel.state.collapsing);
ReactTestUtils.Simulate.select(
ReactTestUtils.findRenderedDOMComponentWithClass(panel, 'changeme')
);
assert.notOk(panel.state.collapsing);
});
describe('Web Accessibility', function() {
let instance, panelBodies, panelGroup, links;
beforeEach(function() {
instance = ReactTestUtils.renderIntoDocument(
<PanelGroup defaultActiveKey='1' accordion>
<Panel header='Collapsible Group Item #1' eventKey='1' id='Panel1ID'>Panel 1</Panel>
<Panel header='Collapsible Group Item #2' eventKey='2' id='Panel2ID'>Panel 2</Panel>
</PanelGroup>
);
let accordion = ReactTestUtils.findRenderedComponentWithType(instance, PanelGroup);
panelGroup = ReactTestUtils.findRenderedDOMComponentWithClass(accordion, 'panel-group');
panelBodies = ReactTestUtils.scryRenderedDOMComponentsWithClass(panelGroup, 'panel-collapse');
links = ReactTestUtils.scryRenderedDOMComponentsWithClass(panelGroup, 'panel-heading')
.map(function(header) {
return ReactTestUtils.findRenderedDOMComponentWithTag(header, 'a');
});
});
it('Should have a role of tablist', function() {
assert.equal(panelGroup.props.role, 'tablist');
});
it('Should provide each header tab with role of tab', function() {
assert.equal(links[0].props.role, 'tab');
assert.equal(links[1].props.role, 'tab');
});
it('Should provide the panelBodies with role of tabpanel', function() {
assert.equal(panelBodies[0].props.role, 'tabpanel');
});
it('Should provide each panel with an aria-labelledby referencing the corresponding header', function() {
assert.equal(panelBodies[0].props.id, links[0].props['aria-controls']);
assert.equal(panelBodies[1].props.id, links[1].props['aria-controls']);
});
it('Should maintain each tab aria-selected state', function() {
assert.equal(links[0].props['aria-selected'], true);
assert.equal(links[1].props['aria-selected'], false);
});
it('Should maintain each tab aria-hidden state', function() {
assert.equal(panelBodies[0].props['aria-hidden'], false);
assert.equal(panelBodies[1].props['aria-hidden'], true);
});
afterEach(function() {
if (instance && ReactTestUtils.isCompositeComponent(instance) && instance.isMounted()) {
React.unmountComponentAtNode(React.findDOMNode(instance));
}
});
});
});
|
node_modules/react-icons/md/style.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const MdStyle = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m9.8 32.9v-10.6l5.7 14h-2.4c-1.8 0-3.3-1.6-3.3-3.4z m3.3-18.3c1 0 1.7-0.8 1.7-1.7s-0.7-1.6-1.7-1.6-1.6 0.7-1.6 1.6 0.7 1.7 1.6 1.7z m23.6 12c0.7 1.7-0.1 3.6-1.8 4.3l-12.2 5.1c-0.4 0.2-0.9 0.3-1.4 0.3-1.3 0-2.5-0.8-3-2.1l-8.3-20c-0.2-0.4-0.2-0.8-0.2-1.3 0-1.3 0.7-2.4 2-3l12.3-5.1c0.5-0.1 0.9-0.2 1.4-0.2 1.2 0 2.4 0.8 2.9 2z m-32.5 6.1c-1.7-0.7-2.5-2.5-1.8-4.3l4.1-9.7v15z"/></g>
</Icon>
)
export default MdStyle
|
src/svg-icons/image/burst-mode.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBurstMode = (props) => (
<SvgIcon {...props}>
<path d="M1 5h2v14H1zm4 0h2v14H5zm17 0H10c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM11 17l2.5-3.15L15.29 16l2.5-3.22L21 17H11z"/>
</SvgIcon>
);
ImageBurstMode = pure(ImageBurstMode);
ImageBurstMode.displayName = 'ImageBurstMode';
ImageBurstMode.muiName = 'SvgIcon';
export default ImageBurstMode;
|
src/components/App.js | pixel-glyph/better-reads | import React from 'react';
import { Route } from 'react-router-dom';
import { Link } from 'react-router-dom';
import update from 'immutability-helper';
import Logo from './Logo';
import SearchBar from './SearchBar';
import Header from './Header';
import BookListPane from './BookListPane';
import Book from './Book';
import BookView from './BookView';
import AddBookBtn from './AddBookBtn';
import MoveBookBtn from './MoveBookBtn';
import ListPicker from './ListPicker';
import SwitchListBtn from './SwitchListBtn';
import PlusIcon from './svg/Plus';
import RemoveIcon from './svg/Remove';
import Modal from './Modal';
import RemovePopup from './RemovePopup';
import ScrollToTopRoute from './ScrollToTopRoute';
import Footer from './Footer';
import base from '../base';
class App extends React.Component {
constructor() {
super();
this.state = {
bookLists: {},
bookIDs: [],
bookView: false,
showList: {
isActive: false,
index: 0
},
showBookMenu: {
isActive: false,
index: 0
},
searchResults: [],
isFetching: false,
showModal: false,
showFullDesc: false,
showBookMenuMoveList: false,
isRemovePopupVisible: false,
newListInputActive: false,
fixListPicker: false
};
}
componentWillMount() {
this.ref = base.syncState('bookLists',
{
context: this,
state: 'bookLists',
defaultValue: {
'Want to Read': {
listName: 'Want to Read',
selected: true,
books: {}
},
'Read': {
listName: 'Read',
selected: false,
books: {}
}
}
});
this.ref = base.syncState('bookIDs',
{
context: this,
state: 'bookIDs',
defaultValue: []
});
this.ref = base.syncState('bookView',
{
context: this,
state: 'bookView',
defaultValue: false
});
this.ref = base.syncState('searchResults',
{
context: this,
state: 'searchResults',
defaultValue: []
});
}
componentWillUnmount() {
base.removeBinding(this.ref);
window.removeEventListener('scroll', this.listPositionScroll);
}
componentDidMount() {
window.addEventListener('scroll', this.listPositionScroll);
}
componentDidUpdate() {
this.ensureSelectedList();
}
listPositionScroll = (e) => {
if(window.didScrollListPicker) return;
if(window.innerWidth < 800) return;
let scrollTop = window.scrollY;
if(scrollTop > 210) {
this.setState({ fixListPicker: true })
} else {
this.setState({ fixListPicker: false })
}
window.didScrollListPicker = true;
};
doesBookExist = (id) => {
return this.state.bookIDs.includes(id);
};
doesListExist = (bookLists, listName) => {
return bookLists.hasOwnProperty(listName);
};
isBookInList = (books, bookID) => {
return books.hasOwnProperty(bookID);
};
getAllLists = (exceptList) => {
if(exceptList) {
let lists = Object.keys(this.state.bookLists);
lists = lists.filter(list => list !== exceptList);
return lists;
}
return Object.keys(this.state.bookLists);
};
addBookID = (id) => {
const bookIDs = [...this.state.bookIDs];
bookIDs.push(id);
this.setState(newState => {
return {
bookIDs: update(newState.bookIDs, {$set: bookIDs})
};
});
};
addBookToList = (listName, book) => {
const books = {...this.state.bookLists[listName].books};
book.list = listName;
books[book.id] = book;
this.setState(newState => {
return {
bookLists: update(newState.bookLists, {[listName]: {books: {$set: books}}})
};
});
};
// for adding a new book from search
addNewBook = (listName, newBook) => {
const id = newBook.id;
if(this.doesBookExist(id)) {
return alert('book is already in a shelf');
}
this.addBookID(id);
this.addBookToList(listName, newBook);
};
removeBookIDs = (removeIDs) => {
const bookIDs = [...this.state.bookIDs];
if(!Array.isArray(removeIDs)) {
removeIDs = [removeIDs];
}
removeIDs.forEach(id => {
const i = bookIDs.indexOf(id);
if(i !== -1) {
bookIDs.splice(i, 1);
} else {
console.warn('ID not found in bookIDs');
}
});
this.setState(newState => {
return {
bookIDs: update(newState.bookIDs, {$set: bookIDs})
};
});
};
removeBookFromList = (listName, bookID) => {
const books = {...this.state.bookLists[listName].books};
if(!this.isBookInList(books, bookID)) {
return alert('book is not in list');
}
books[bookID] = null;
this.setState(newState => {
return {
bookLists: update(newState.bookLists, {[listName]: {books: {$set: books}}})
};
});
};
// for removing a book entirely from the user's collection
removeBook = (listName, bookID) => {
this.removeBookIDs(bookID);
this.removeBookFromList(listName, bookID);
this.removeBookViewList(bookID);
};
moveBook = (toList, book, id) => {
this.removeBookFromList(book.list, id);
this.addBookToList(toList, book);
};
getCurrentList = () => {
let currList;
let currListName =
Object
.keys(this.state.bookLists)
.find(list => {
currList = this.state.bookLists[list]
? this.state.bookLists[list].selected
: false;
return currList;
});
if(!currListName) {
currListName = 'Want to Read';
}
return this.state.bookLists[currListName]
? this.state.bookLists[currListName]
: {};
};
ensureSelectedList = () => {
const bookLists = {...this.state.bookLists};
let listSelected;
for(const list in bookLists) {
if(bookLists[list] && bookLists[list].selected) {
if(listSelected) {
bookLists[list].selected = false;
} else {
listSelected = true;
}
}
}
if(!listSelected && bookLists['Want to Read']) {
bookLists['Want to Read'].selected = true;
}
};
toggleSelected = (listName) => {
const bookLists = {...this.state.bookLists};
let list = bookLists[listName];
if(!list) return;
list.selected = !list.selected;
this.setState(newState => {
return {bookLists: newState.bookLists};
});
};
createList = (listName) => {
const bookLists = {...this.state.bookLists};
bookLists[listName] = {
listName: listName,
selected: true,
books: {}
};
this.setState(newState => {
return {
bookLists: update(newState.bookLists, {$set: bookLists})
};
});
};
removeList = (list) => {
const selectedList = this.getCurrentList().listName;
const currList = !list ? selectedList : list;
const bookLists = {...this.state.bookLists};
if(!this.doesListExist(bookLists, currList)) {
return alert('list does not exist');
}
if(window.confirm(`Are you sure you want to remove your ${currList} shelf and all its books?`)) {
let listToRemove = bookLists[currList];
let ids = [];
for (var id in listToRemove.books) {
ids.push(id);
}
this.removeBookIDs(ids);
bookLists[currList] = null;
this.setState(newState => {
return {
bookLists: update(newState.bookLists, {$set: bookLists})
};
});
if(!list || list === selectedList) {
this.toggleSelected('Want to Read');
}
this.toggleRemovePopup();
setTimeout(() => {
this.toggleRemovePopup();
}, 2500);
}
};
switchList = (listName) => {
const currList = this.getCurrentList();
if(listName === currList.listName) return;
this.toggleSelected(listName);
this.toggleSelected(currList.listName);
};
toggleFetch = () => {
let isFetching = this.state.isFetching;
isFetching = !isFetching;
this.setState(newState => {
return {
isFetching: update(newState.isFetching, {$set: isFetching})
};
});
};
toggleModal = () => {
let showModal = this.state.showModal;
showModal = !showModal;
this.setState(newState => {
return {
showModal: update(newState.showModal, {$set: showModal})
};
});
};
toggleDesc = () => {
let showFullDesc = this.state.showFullDesc;
showFullDesc = !showFullDesc;
this.setState(newState => {
return {
showFullDesc: update(newState.showFullDesc, {$set: showFullDesc})
};
});
};
setResults = (results) => {
let searchResults;
if(results.items) {
searchResults = results.items.map(book => {
const author = book.volumeInfo.authors ? book.volumeInfo.authors[0] : '';
const desc = book.volumeInfo.description ? book.volumeInfo.description : '';
const pubDate = book.volumeInfo.publishedDate ? book.volumeInfo.publishedDate : '';
const img = book.volumeInfo.imageLinks
? book.volumeInfo.imageLinks.smallThumbnail
: 'https://books.google.com/googlebooks/images/no_cover_thumb.gif';
return {
title: book.volumeInfo.title,
id: book.id,
pubDate,
author,
desc,
img
};
});
} else {
searchResults = [];
}
this.setState(newState => {
return {
searchResults: update(newState.searchResults, {$set: searchResults})
};
});
};
listResults = () => {
const { searchResults } = this.state;
if(!searchResults.length) {
return <li className="book no-results">No Results</li>;
}
const results = searchResults.map( (book, i) => {
if(this.doesBookExist(book.id)) {
const lists = this.getAllLists();
lists.forEach((list) => {
let books = this.state.bookLists[list].books;
if(books && this.isBookInList(books, book.id)) {
book.list = list;
return;
}
});
return (
<li key={i}>
<Book bookInfo={book} addNewBook={this.addNewBook}/>
<MoveBookBtn
bookInfo={book}
moveBook={this.moveBook}
getAllLists={this.getAllLists}
showList={this.state.showList}
toggleSideList={this.toggleSideList}
syncBookView={this.syncBookView}
index={i}/>
</li>
);
} else {
return (
<li key={i}>
<Book bookInfo={book} addNewBook={this.addNewBook}/>
<AddBookBtn
bookInfo={book}
addNewBook={this.addNewBook}
getAllLists={this.getAllLists}
showList={this.state.showList}
toggleSideList={this.toggleSideList}
syncBookView={this.syncBookView}
index={i}/>
</li>
)
}
});
return results;
};
setBookView = (book) => {
const bookView = {...this.state.bookView};
bookView.list = book.list || null;
bookView.author = book.author;
bookView.desc = book.desc;
bookView.id = book.id;
bookView.img = book.img;
bookView.pubDate = book.pubDate;
bookView.title = book.title;
this.setState(newState => {
return {
bookView: update(newState.bookView, {$set: bookView})
};
});
};
removeBookViewList = (id) => {
const bookView = {...this.state.bookView};
if(bookView.id !== id) return;
bookView.list = null;
this.setState(newState => {
return {
bookView: update(newState.bookView, {$set: bookView})
};
});
};
toggleBookMenu = (i=0) => {
const showBookMenu = {...this.state.showBookMenu};
showBookMenu.isActive = !showBookMenu.isActive;
showBookMenu.index = i;
this.setState(newState => {
return {
showBookMenu: update(newState.showBookMenu, {$set: showBookMenu})
};
});
};
toggleBookMenuMoveList = () => {
let showBookMenuMoveList = this.state.showBookMenuMoveList;
showBookMenuMoveList = !showBookMenuMoveList;
this.setState(newState => {
return {
showBookMenuMoveList: update(newState.showBookMenuMoveList, {$set: showBookMenuMoveList})
};
});
};
toggleNewListInput = () => {
let newListInputActive = this.state.newListInputActive;
newListInputActive = !newListInputActive;
this.setState(newState => {
return {
newListInputActive: update(newState.newListInputActive, {$set: newListInputActive})
};
});
};
toggleSideList = (i=0) => {
const showList = {...this.state.showList};
showList.isActive = !showList.isActive;
showList.index = i;
this.setState(newState => {
return {
showList: update(newState.showList, {$set: showList})
};
});
};
toggleRemovePopup = () => {
let isRemovePopupVisible = this.state.isRemovePopupVisible;
isRemovePopupVisible = !isRemovePopupVisible;
this.setState({ isRemovePopupVisible });
};
render() {
const Main = () => {
const currList = this.getCurrentList().listName;
const removeListHandler = (listToRemove) => {
this.removeList(listToRemove);
};
return (
<div className="main-wrapper">
<SwitchListBtn
switchList={this.switchList}
toggleSideList={this.toggleSideList}
showList={this.state.showList}
lists={this.state.bookLists}/>
<div className="main-icon-wrapper">
<div className="plus-icon-wrapper icon-wrapper" title="Create New Shelf" onClick={() => this.toggleModal()}>
New Shelf <PlusIcon/>
</div>
{currList !== 'Want to Read' && currList !== 'Read'
? <div className="remove-icon-wrapper icon-wrapper" title="Remove Shelf" onClick={() => removeListHandler()}>
Remove Shelf <RemoveIcon/>
</div>
: null
}
</div>
<div className="book-list-pane-wrapper">
<ListPicker
switchList={this.switchList}
toggleSideList={this.toggleSideList}
showList={this.state.showList}
lists={this.state.bookLists}
fixList={this.state.fixListPicker}
doesListExist={this.doesListExist}
toggleSelected={this.toggleSelected}
getCurrentList={this.getCurrentList}
createList={this.createList}
toggleNewListInput={this.toggleNewListInput}
newListInputActive={this.state.newListInputActive}
removeListHandler={removeListHandler} />
<BookListPane
currentList={this.getCurrentList()}
fixList={this.state.fixListPicker}
toggleBookMenu={this.toggleBookMenu}
getAllLists={this.getAllLists}
moveBook={this.moveBook}
removeBook={this.removeBook}
showBookMenuMoveList={this.state.showBookMenuMoveList}
toggleBookMenuMoveList={this.toggleBookMenuMoveList}
showBookMenu={this.state.showBookMenu} />
</div>
<Modal
toggleSelected={this.toggleSelected}
getCurrentList={this.getCurrentList}
createList={this.createList}
showModal={this.state.showModal}
doesListExist={this.doesListExist}
toggleModal={this.toggleModal}
bookLists={this.state.bookLists} />
</div>
)
};
const Search = () => (
<div className="search-wrapper">
<p className="book-view-back-link"><Link to="/">← Back to My Shelves</Link></p>
{!this.state.isFetching
? <ul className="search-results">
{this.listResults()}
</ul>
: <div className="fetch-spinner">
<div className="bounce1"></div>
<div className="bounce2"></div>
<div className="bounce3"></div>
</div>
}
</div>
);
return (
<div className="app-wrapper">
<Header
path={this.props.location.pathname}
history={this.props.history}
setResults={this.setResults}
toggleFetch={this.toggleFetch}
isBookMenuActive={this.state.showBookMenu.isActive} />
<Logo/>
<SearchBar
path={this.props.location.pathname}
history={this.props.history}
setResults={this.setResults}
toggleFetch={this.toggleFetch}
isBookMenuActive={this.state.showBookMenu.isActive} />
<RemovePopup
isVisible={this.state.isRemovePopupVisible}
message="Shelf has been removed"/>
<ScrollToTopRoute exact path="/" component={Main}/>
<Route path="/search" component={Search}/>
<Route path="/book/:id" render={(props) => (
<BookView
{...props}
bookID={props.match.params.id}
bookInfo={this.state.bookView}
setBookView={this.setBookView}
doesBookExist={this.doesBookExist}
addNewBook={this.addNewBook}
getAllLists={this.getAllLists}
showList={this.state.showList}
toggleSideList={this.toggleSideList}
moveBook={this.moveBook}
toggleDesc={this.toggleDesc}
showFullDesc={this.state.showFullDesc}
removeBook={this.removeBook} />
)}/>
<Footer/>
</div>
)
}
}
export default App;
|
app/components/ProgressBar/index.js | iPhaeton/Selectors-study | import React from 'react';
import ProgressBar from './ProgressBar';
function withProgressBar(WrappedComponent) {
class AppWithProgressBar extends React.Component {
constructor(props) {
super(props);
this.state = {
progress: -1,
loadedRoutes: props.location && [props.location.pathname],
};
this.updateProgress = this.updateProgress.bind(this);
}
componentWillMount() {
// Store a reference to the listener.
/* istanbul ignore next */
this.unsubscribeHistory = this.props.router && this.props.router.listenBefore((location) => {
// Do not show progress bar for already loaded routes.
if (this.state.loadedRoutes.indexOf(location.pathname) === -1) {
this.updateProgress(0);
}
});
}
componentWillUpdate(newProps, newState) {
const { loadedRoutes, progress } = this.state;
const { pathname } = newProps.location;
// Complete progress when route changes. But prevent state update while re-rendering.
if (loadedRoutes.indexOf(pathname) === -1 && progress !== -1 && newState.progress < 100) {
this.updateProgress(100);
this.setState({
loadedRoutes: loadedRoutes.concat([pathname]),
});
}
}
componentWillUnmount() {
// Unset unsubscribeHistory since it won't be garbage-collected.
this.unsubscribeHistory = undefined;
}
updateProgress(progress) {
this.setState({ progress });
}
render() {
return (
<div>
<ProgressBar percent={this.state.progress} updateProgress={this.updateProgress} />
<WrappedComponent {...this.props} />
</div>
);
}
}
AppWithProgressBar.propTypes = {
location: React.PropTypes.object,
router: React.PropTypes.object,
};
return AppWithProgressBar;
}
export default withProgressBar;
|
src/media/js/site/components/tos.js | mozilla/marketplace-submission | import React from 'react';
import urlJoin from 'url-join';
export default class TOSIframe extends React.Component {
static propTypes = {
url: React.PropTypes.string.isRequired,
};
getUrl() {
return urlJoin(process.env.MKT_ROOT, this.props.url);
}
render() {
return (
<div className="tos">
<iframe src={this.getUrl()}></iframe>
</div>
);
}
}
|
src/docs/apiExamples/ReferenceLine.js | recharts/recharts.org | import React from 'react';
import { AreaChart, ReferenceLine, Area, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
const data = [
{
name: 'Page A',
uv: 4000,
pv: 2400,
amt: 2400,
},
{
name: 'Page B',
uv: 3000,
pv: 1398,
amt: 2210,
},
{
name: 'Page C',
uv: 2000,
pv: 9800,
amt: 2290,
},
{
name: 'Page D',
uv: 2780,
pv: 3908,
amt: 2000,
},
{
name: 'Page E',
uv: 1890,
pv: 4800,
amt: 2181,
},
{
name: 'Page F',
uv: 2390,
pv: 3800,
amt: 2500,
},
{
name: 'Page G',
uv: 3490,
pv: 4300,
amt: 2100,
},
];
const example = () => (
<AreaChart
width={730}
height={250}
data={data}
margin={{
top: 20,
right: 30,
left: 0,
bottom: 0,
}}
>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<ReferenceLine x="Page C" stroke="green" label="Min PAGE" />
<ReferenceLine y={4000} label="Max" stroke="red" strokeDasharray="3 3" />
<ReferenceLine
label="Segment"
stroke="green"
strokeDasharray="3 3"
segment={[
{ x: 'Page A', y: 0 },
{ x: 'Page C', y: 4000 },
]}
/>
<Area type="monotone" dataKey="uv" stroke="#8884d8" fill="#8884d8" />
</AreaChart>
);
const exampleCode = `
<AreaChart width={730} height={250} data={data}
margin={{ top: 20, right: 30, left: 0, bottom: 0 }}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<ReferenceLine x="Page C" stroke="green" label="Min PAGE" />
<ReferenceLine y={4000} label="Max" stroke="red" strokeDasharray="3 3" />
<ReferenceLine label="Segment" stroke="green" strokeDasharray="3 3" segment={[{ x: 'Page A', y: 0 }, { x: 'Page C', y: 4000 }]} />
<Area type="monotone" dataKey="uv" stroke="#8884d8" fill="#8884d8" />
</AreaChart>
`;
export default [
{
demo: example,
code: exampleCode,
dataCode: `const data = ${JSON.stringify(data, null, 2)}`,
},
];
|
src/js/LudoPage/MobileLudoPage/MobileCardContent.js | ludonow/ludo-beta-react | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import ReactPlayer from 'react-player';
import { cyan800, deepOrange200 } from 'material-ui/styles/colors';
const RoundRadiusTag = styled.span`
border-radius: 20px;
padding: 8px 20px;
background-color: ${cyan800};
color: white;
font-size: 0.8rem;
`;
const CardContentWrapper = styled.div`
padding: 5px 30px;
color: white;
`;
const CardImage = styled.div`
align-items: center;
display: flex;
justify-content: center;
margin-top: 20px;
img {
width: 200px;
}
`;
const CardInterval = styled.div`
display: flex;
flex-flow: row wrap;
justify-content: center;
margin: 30px 0;
text-align: center;
`;
const CardIntroduction = styled.div`
color: white;
font-size: 0.8rem;
font-weight: bold;
line-height: 1.3;
margin: 30px auto 70px auto;
white-space: pre-line;
`;
const CardTitle = styled.div`
margin: 35px 0;
text-align: center;
font-size: 22px;
font-weight: bold;
`;
const CardTags = styled.div`
display: flex;
flex-flow: row wrap;
justify-content: center;
margin: 15px 0;
text-align: center;
`;
const CardTag = RoundRadiusTag.extend`
display: flex;
align-items: center;
margin: 5px;
`;
const CardVideo = styled.div`
`;
const IntervalTag = RoundRadiusTag.extend`
display: flex;
align-items: center;
margin: 5px;
background-color: ${deepOrange200};
`;
const MobileCardContent = ({
handleImageLightboxOpen,
image_location,
interval,
introduction,
tags,
title,
video,
}) => (
<CardContentWrapper>
<CardTitle>
{title}
</CardTitle>
<CardTags>
{
tags.map((tag, index) => (
<CardTag
key={`introducton-${index}`}
>
#{tag}
</CardTag>
))
}
</CardTags>
<CardInterval>
<IntervalTag>每{interval}天回報</IntervalTag>
</CardInterval>
{
video ?
<CardVideo>
<ReactPlayer
height="auto"
url={video}
width="100%"
/>
</CardVideo>
: null
}
{
image_location ?
<CardImage>
<img
onClick={handleImageLightboxOpen}
src={image_location}
/>
</CardImage>
: null
}
<CardIntroduction>
{introduction}
</CardIntroduction>
</CardContentWrapper>
);
MobileCardContent.propTypes = {
handleImageLightboxOpen: PropTypes.func.isRequired,
interval: PropTypes.number.isRequired,
introduction: PropTypes.string.isRequired,
tags: PropTypes.arrayOf(PropTypes.string.isRequired),
title: PropTypes.string.isRequired,
video: PropTypes.string,
};
export default MobileCardContent;
|
src/svg-icons/editor/format-align-center.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatAlignCenter = (props) => (
<SvgIcon {...props}>
<path d="M7 15v2h10v-2H7zm-4 6h18v-2H3v2zm0-8h18v-2H3v2zm4-6v2h10V7H7zM3 3v2h18V3H3z"/>
</SvgIcon>
);
EditorFormatAlignCenter = pure(EditorFormatAlignCenter);
EditorFormatAlignCenter.displayName = 'EditorFormatAlignCenter';
EditorFormatAlignCenter.muiName = 'SvgIcon';
export default EditorFormatAlignCenter;
|
src/widgets/DatePicker.ios.js | anysome/objective | /**
* Created by Layman(http://github.com/anysome) on 16/3/6.
*/
import React from 'react'
import {DatePickerIOS} from 'react-native'
export default class DatePicker extends React.Component {
render() {
let picker = null;
if (this.props.visible) {
picker = <DatePickerIOS
date={this.props.date}
mode="date"
onDateChange={this.props.onDateChange}
/>;
}
return picker;
}
}
|
node_modules/babel-plugin-transform-es2015-modules-commonjs/node_modules/core-js/client/core.js | fnando/babel-schmooze-sprockets | /**
* core-js 2.4.0
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2016 Denis Pushkarev
*/
!function(__e, __g, undefined){
'use strict';
/******/ (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__) {
__webpack_require__(1);
__webpack_require__(50);
__webpack_require__(51);
__webpack_require__(52);
__webpack_require__(54);
__webpack_require__(55);
__webpack_require__(58);
__webpack_require__(59);
__webpack_require__(60);
__webpack_require__(61);
__webpack_require__(62);
__webpack_require__(63);
__webpack_require__(64);
__webpack_require__(65);
__webpack_require__(66);
__webpack_require__(68);
__webpack_require__(70);
__webpack_require__(72);
__webpack_require__(74);
__webpack_require__(77);
__webpack_require__(78);
__webpack_require__(79);
__webpack_require__(83);
__webpack_require__(87);
__webpack_require__(88);
__webpack_require__(89);
__webpack_require__(90);
__webpack_require__(92);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
__webpack_require__(96);
__webpack_require__(98);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(102);
__webpack_require__(104);
__webpack_require__(105);
__webpack_require__(106);
__webpack_require__(108);
__webpack_require__(109);
__webpack_require__(110);
__webpack_require__(112);
__webpack_require__(113);
__webpack_require__(114);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
__webpack_require__(118);
__webpack_require__(119);
__webpack_require__(120);
__webpack_require__(121);
__webpack_require__(122);
__webpack_require__(123);
__webpack_require__(124);
__webpack_require__(125);
__webpack_require__(127);
__webpack_require__(131);
__webpack_require__(132);
__webpack_require__(133);
__webpack_require__(134);
__webpack_require__(138);
__webpack_require__(140);
__webpack_require__(141);
__webpack_require__(142);
__webpack_require__(143);
__webpack_require__(144);
__webpack_require__(145);
__webpack_require__(146);
__webpack_require__(147);
__webpack_require__(148);
__webpack_require__(149);
__webpack_require__(150);
__webpack_require__(151);
__webpack_require__(152);
__webpack_require__(153);
__webpack_require__(159);
__webpack_require__(160);
__webpack_require__(162);
__webpack_require__(163);
__webpack_require__(164);
__webpack_require__(168);
__webpack_require__(169);
__webpack_require__(170);
__webpack_require__(171);
__webpack_require__(172);
__webpack_require__(174);
__webpack_require__(175);
__webpack_require__(176);
__webpack_require__(177);
__webpack_require__(180);
__webpack_require__(182);
__webpack_require__(183);
__webpack_require__(184);
__webpack_require__(186);
__webpack_require__(188);
__webpack_require__(190);
__webpack_require__(191);
__webpack_require__(192);
__webpack_require__(194);
__webpack_require__(195);
__webpack_require__(196);
__webpack_require__(197);
__webpack_require__(203);
__webpack_require__(206);
__webpack_require__(207);
__webpack_require__(209);
__webpack_require__(210);
__webpack_require__(211);
__webpack_require__(212);
__webpack_require__(213);
__webpack_require__(214);
__webpack_require__(215);
__webpack_require__(216);
__webpack_require__(217);
__webpack_require__(218);
__webpack_require__(219);
__webpack_require__(220);
__webpack_require__(222);
__webpack_require__(223);
__webpack_require__(224);
__webpack_require__(225);
__webpack_require__(226);
__webpack_require__(227);
__webpack_require__(228);
__webpack_require__(229);
__webpack_require__(231);
__webpack_require__(234);
__webpack_require__(235);
__webpack_require__(238);
__webpack_require__(239);
__webpack_require__(240);
__webpack_require__(241);
__webpack_require__(242);
__webpack_require__(243);
__webpack_require__(244);
__webpack_require__(245);
__webpack_require__(246);
__webpack_require__(247);
__webpack_require__(248);
__webpack_require__(250);
__webpack_require__(251);
__webpack_require__(252);
__webpack_require__(253);
__webpack_require__(254);
__webpack_require__(255);
__webpack_require__(256);
__webpack_require__(257);
__webpack_require__(259);
__webpack_require__(260);
__webpack_require__(262);
__webpack_require__(263);
__webpack_require__(264);
__webpack_require__(265);
__webpack_require__(268);
__webpack_require__(269);
__webpack_require__(270);
__webpack_require__(271);
__webpack_require__(272);
__webpack_require__(273);
__webpack_require__(274);
__webpack_require__(275);
__webpack_require__(277);
__webpack_require__(278);
__webpack_require__(279);
__webpack_require__(280);
__webpack_require__(281);
__webpack_require__(282);
__webpack_require__(283);
__webpack_require__(284);
__webpack_require__(285);
__webpack_require__(286);
__webpack_require__(287);
__webpack_require__(288);
__webpack_require__(289);
__webpack_require__(292);
__webpack_require__(157);
__webpack_require__(293);
__webpack_require__(237);
__webpack_require__(294);
__webpack_require__(295);
__webpack_require__(296);
__webpack_require__(297);
__webpack_require__(298);
__webpack_require__(300);
__webpack_require__(301);
__webpack_require__(302);
__webpack_require__(304);
module.exports = __webpack_require__(305);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var global = __webpack_require__(2)
, has = __webpack_require__(3)
, DESCRIPTORS = __webpack_require__(4)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, META = __webpack_require__(20).KEY
, $fails = __webpack_require__(5)
, shared = __webpack_require__(21)
, setToStringTag = __webpack_require__(22)
, uid = __webpack_require__(17)
, wks = __webpack_require__(23)
, wksExt = __webpack_require__(24)
, wksDefine = __webpack_require__(25)
, keyOf = __webpack_require__(27)
, enumKeys = __webpack_require__(40)
, isArray = __webpack_require__(43)
, anObject = __webpack_require__(10)
, toIObject = __webpack_require__(30)
, toPrimitive = __webpack_require__(14)
, createDesc = __webpack_require__(15)
, _create = __webpack_require__(44)
, gOPNExt = __webpack_require__(47)
, $GOPD = __webpack_require__(49)
, $DP = __webpack_require__(9)
, $keys = __webpack_require__(28)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(48).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(42).f = $propertyIsEnumerable;
__webpack_require__(41).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(26)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(8)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ },
/* 2 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 3 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(5)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, hide = __webpack_require__(8)
, redefine = __webpack_require__(16)
, ctx = __webpack_require__(18)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 7 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, createDesc = __webpack_require__(15);
module.exports = __webpack_require__(4) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(10)
, IE8_DOM_DEFINE = __webpack_require__(12)
, toPrimitive = __webpack_require__(14)
, dP = Object.defineProperty;
exports.f = __webpack_require__(4) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(4) && !__webpack_require__(5)(function(){
return Object.defineProperty(__webpack_require__(13)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, document = __webpack_require__(2).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(11);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, hide = __webpack_require__(8)
, has = __webpack_require__(3)
, SRC = __webpack_require__(17)('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(7).inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ },
/* 17 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(19);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var META = __webpack_require__(17)('meta')
, isObject = __webpack_require__(11)
, has = __webpack_require__(3)
, setDesc = __webpack_require__(9).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(5)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
var def = __webpack_require__(9).f
, has = __webpack_require__(3)
, TAG = __webpack_require__(23)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var store = __webpack_require__(21)('wks')
, uid = __webpack_require__(17)
, Symbol = __webpack_require__(2).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(23);
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, LIBRARY = __webpack_require__(26)
, wksExt = __webpack_require__(24)
, defineProperty = __webpack_require__(9).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
/***/ },
/* 26 */
/***/ function(module, exports) {
module.exports = false;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(28)
, toIObject = __webpack_require__(30);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(29)
, enumBugKeys = __webpack_require__(39);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(3)
, toIObject = __webpack_require__(30)
, arrayIndexOf = __webpack_require__(34)(false)
, IE_PROTO = __webpack_require__(38)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(31)
, defined = __webpack_require__(33);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(32);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 32 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 33 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(30)
, toLength = __webpack_require__(35)
, toIndex = __webpack_require__(37);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(36)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 36 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(36)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(21)('keys')
, uid = __webpack_require__(17);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 39 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(28)
, gOPS = __webpack_require__(41)
, pIE = __webpack_require__(42);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
/***/ },
/* 41 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 42 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(32);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(10)
, dPs = __webpack_require__(45)
, enumBugKeys = __webpack_require__(39)
, IE_PROTO = __webpack_require__(38)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(13)('iframe')
, i = enumBugKeys.length
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
__webpack_require__(46).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write('<script>document.F=Object</script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, anObject = __webpack_require__(10)
, getKeys = __webpack_require__(28);
module.exports = __webpack_require__(4) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2).document && document.documentElement;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(30)
, gOPN = __webpack_require__(48).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(29)
, hiddenKeys = __webpack_require__(39).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(42)
, createDesc = __webpack_require__(15)
, toIObject = __webpack_require__(30)
, toPrimitive = __webpack_require__(14)
, has = __webpack_require__(3)
, IE8_DOM_DEFINE = __webpack_require__(12)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(4) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperty: __webpack_require__(9).f});
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperties: __webpack_require__(45)});
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(30)
, $getOwnPropertyDescriptor = __webpack_require__(49).f;
__webpack_require__(53)('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(6)
, core = __webpack_require__(7)
, fails = __webpack_require__(5);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: __webpack_require__(44)});
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(56)
, $getPrototypeOf = __webpack_require__(57);
__webpack_require__(53)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(33);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(3)
, toObject = __webpack_require__(56)
, IE_PROTO = __webpack_require__(38)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(56)
, $keys = __webpack_require__(28);
__webpack_require__(53)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(53)('getOwnPropertyNames', function(){
return __webpack_require__(47).f;
});
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(6);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(67)});
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(28)
, gOPS = __webpack_require__(41)
, pIE = __webpack_require__(42)
, toObject = __webpack_require__(56)
, IObject = __webpack_require__(31)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(5)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(6);
$export($export.S, 'Object', {is: __webpack_require__(69)});
/***/ },
/* 69 */
/***/ function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(6);
$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(71).set});
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(11)
, anObject = __webpack_require__(10);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = __webpack_require__(18)(Function.call, __webpack_require__(49).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__(73)
, test = {};
test[__webpack_require__(23)('toStringTag')] = 'z';
if(test + '' != '[object z]'){
__webpack_require__(16)(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(32)
, TAG = __webpack_require__(23)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(6);
$export($export.P, 'Function', {bind: __webpack_require__(75)});
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var aFunction = __webpack_require__(19)
, isObject = __webpack_require__(11)
, invoke = __webpack_require__(76)
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
/***/ },
/* 76 */
/***/ function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9).f
, createDesc = __webpack_require__(15)
, has = __webpack_require__(3)
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || __webpack_require__(4) && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isObject = __webpack_require__(11)
, getPrototypeOf = __webpack_require__(57)
, HAS_INSTANCE = __webpack_require__(23)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(9).f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, has = __webpack_require__(3)
, cof = __webpack_require__(32)
, inheritIfRequired = __webpack_require__(80)
, toPrimitive = __webpack_require__(14)
, fails = __webpack_require__(5)
, gOPN = __webpack_require__(48).f
, gOPD = __webpack_require__(49).f
, dP = __webpack_require__(9).f
, $trim = __webpack_require__(81).trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(__webpack_require__(44)(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = __webpack_require__(4) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__(16)(global, NUMBER, $Number);
}
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, setPrototypeOf = __webpack_require__(71).set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, defined = __webpack_require__(33)
, fails = __webpack_require__(5)
, spaces = __webpack_require__(82)
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ },
/* 82 */
/***/ function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, anInstance = __webpack_require__(84)
, toInteger = __webpack_require__(36)
, aNumberValue = __webpack_require__(85)
, repeat = __webpack_require__(86)
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !__webpack_require__(5)(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
/***/ },
/* 84 */
/***/ function(module, exports) {
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var cof = __webpack_require__(32);
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var toInteger = __webpack_require__(36)
, defined = __webpack_require__(33);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $fails = __webpack_require__(5)
, aNumberValue = __webpack_require__(85)
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(6);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(6)
, _isFinite = __webpack_require__(2).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(6);
$export($export.S, 'Number', {isInteger: __webpack_require__(91)});
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(11)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(6);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(6)
, isInteger = __webpack_require__(91)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(6);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(6);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseFloat = __webpack_require__(97);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
var $parseFloat = __webpack_require__(2).parseFloat
, $trim = __webpack_require__(81).trim;
module.exports = 1 / $parseFloat(__webpack_require__(82) + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseInt = __webpack_require__(99);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
var $parseInt = __webpack_require__(2).parseInt
, $trim = __webpack_require__(81).trim
, ws = __webpack_require__(82)
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseInt = __webpack_require__(99);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseFloat = __webpack_require__(97);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
/***/ },
/* 102 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(6)
, log1p = __webpack_require__(103)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ },
/* 103 */
/***/ function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(6)
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(6)
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ },
/* 106 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(6)
, sign = __webpack_require__(107);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ },
/* 107 */
/***/ function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(6)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ },
/* 110 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(6)
, $expm1 = __webpack_require__(111);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
/***/ },
/* 111 */
/***/ function(module, exports) {
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(6)
, sign = __webpack_require__(107)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(6)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(6)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(5)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {log1p: __webpack_require__(103)});
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {sign: __webpack_require__(107)});
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(6)
, expm1 = __webpack_require__(111)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(5)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(6)
, expm1 = __webpack_require__(111)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, toIndex = __webpack_require__(37)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, toLength = __webpack_require__(35);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ },
/* 124 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
__webpack_require__(81)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $at = __webpack_require__(126)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(36)
, defined = __webpack_require__(33);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = __webpack_require__(6)
, toLength = __webpack_require__(35)
, context = __webpack_require__(128)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(130)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(129)
, defined = __webpack_require__(33);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(11)
, cof = __webpack_require__(32)
, MATCH = __webpack_require__(23)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(23)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = __webpack_require__(6)
, context = __webpack_require__(128)
, INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(130)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(86)
});
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = __webpack_require__(6)
, toLength = __webpack_require__(35)
, context = __webpack_require__(128)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(130)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(126)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(135)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ },
/* 135 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(26)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, hide = __webpack_require__(8)
, has = __webpack_require__(3)
, Iterators = __webpack_require__(136)
, $iterCreate = __webpack_require__(137)
, setToStringTag = __webpack_require__(22)
, getPrototypeOf = __webpack_require__(57)
, ITERATOR = __webpack_require__(23)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ },
/* 136 */
/***/ function(module, exports) {
module.exports = {};
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var create = __webpack_require__(44)
, descriptor = __webpack_require__(15)
, setToStringTag = __webpack_require__(22)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(8)(IteratorPrototype, __webpack_require__(23)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(139)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, fails = __webpack_require__(5)
, defined = __webpack_require__(33)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
__webpack_require__(139)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
__webpack_require__(139)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
__webpack_require__(139)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
__webpack_require__(139)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(139)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(139)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
__webpack_require__(139)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
__webpack_require__(139)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
__webpack_require__(139)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
__webpack_require__(139)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
__webpack_require__(139)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
__webpack_require__(139)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(6);
$export($export.S, 'Array', {isArray: __webpack_require__(43)});
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(18)
, $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, call = __webpack_require__(154)
, isArrayIter = __webpack_require__(155)
, toLength = __webpack_require__(35)
, createProperty = __webpack_require__(156)
, getIterFn = __webpack_require__(157);
$export($export.S + $export.F * !__webpack_require__(158)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(10);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(136)
, ITERATOR = __webpack_require__(23)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $defineProperty = __webpack_require__(9)
, createDesc = __webpack_require__(15);
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(73)
, ITERATOR = __webpack_require__(23)('iterator')
, Iterators = __webpack_require__(136);
module.exports = __webpack_require__(7).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(23)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, createProperty = __webpack_require__(156);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(5)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (__webpack_require__(31) != Object || !__webpack_require__(161)(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
var fails = __webpack_require__(5);
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, html = __webpack_require__(46)
, cof = __webpack_require__(32)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35)
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__(5)(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, aFunction = __webpack_require__(19)
, toObject = __webpack_require__(56)
, fails = __webpack_require__(5)
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__(161)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $forEach = __webpack_require__(165)(0)
, STRICT = __webpack_require__(161)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(18)
, IObject = __webpack_require__(31)
, toObject = __webpack_require__(56)
, toLength = __webpack_require__(35)
, asc = __webpack_require__(166);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(167);
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, isArray = __webpack_require__(43)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $map = __webpack_require__(165)(1);
$export($export.P + $export.F * !__webpack_require__(161)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 169 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $filter = __webpack_require__(165)(2);
$export($export.P + $export.F * !__webpack_require__(161)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $some = __webpack_require__(165)(3);
$export($export.P + $export.F * !__webpack_require__(161)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $every = __webpack_require__(165)(4);
$export($export.P + $export.F * !__webpack_require__(161)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $reduce = __webpack_require__(173);
$export($export.P + $export.F * !__webpack_require__(161)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(19)
, toObject = __webpack_require__(56)
, IObject = __webpack_require__(31)
, toLength = __webpack_require__(35);
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $reduce = __webpack_require__(173);
$export($export.P + $export.F * !__webpack_require__(161)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
/***/ },
/* 175 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $indexOf = __webpack_require__(34)(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(161)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(161)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
/***/ },
/* 177 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(6);
$export($export.P, 'Array', {copyWithin: __webpack_require__(178)});
__webpack_require__(179)('copyWithin');
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = __webpack_require__(56)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(23)('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(8)(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(6);
$export($export.P, 'Array', {fill: __webpack_require__(181)});
__webpack_require__(179)('fill');
/***/ },
/* 181 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = __webpack_require__(56)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(6)
, $find = __webpack_require__(165)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(179)(KEY);
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(6)
, $find = __webpack_require__(165)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(179)(KEY);
/***/ },
/* 184 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(179)
, step = __webpack_require__(185)
, Iterators = __webpack_require__(136)
, toIObject = __webpack_require__(30);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(135)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ },
/* 185 */
/***/ function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(187)('Array');
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, dP = __webpack_require__(9)
, DESCRIPTORS = __webpack_require__(4)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, inheritIfRequired = __webpack_require__(80)
, dP = __webpack_require__(9).f
, gOPN = __webpack_require__(48).f
, isRegExp = __webpack_require__(129)
, $flags = __webpack_require__(189)
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(__webpack_require__(4) && (!CORRECT_NEW || __webpack_require__(5)(function(){
re2[__webpack_require__(23)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(16)(global, 'RegExp', $RegExp);
}
__webpack_require__(187)('RegExp');
/***/ },
/* 189 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(10);
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(191);
var anObject = __webpack_require__(10)
, $flags = __webpack_require__(189)
, DESCRIPTORS = __webpack_require__(4)
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
__webpack_require__(16)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(__webpack_require__(5)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
/***/ },
/* 191 */
/***/ function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if(__webpack_require__(4) && /./g.flags != 'g')__webpack_require__(9).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(189)
});
/***/ },
/* 192 */
/***/ function(module, exports, __webpack_require__) {
// @@match logic
__webpack_require__(193)('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
/***/ },
/* 193 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var hide = __webpack_require__(8)
, redefine = __webpack_require__(16)
, fails = __webpack_require__(5)
, defined = __webpack_require__(33)
, wks = __webpack_require__(23);
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
/***/ },
/* 194 */
/***/ function(module, exports, __webpack_require__) {
// @@replace logic
__webpack_require__(193)('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
// @@search logic
__webpack_require__(193)('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
// @@split logic
__webpack_require__(193)('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = __webpack_require__(129)
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
/***/ },
/* 197 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(26)
, global = __webpack_require__(2)
, ctx = __webpack_require__(18)
, classof = __webpack_require__(73)
, $export = __webpack_require__(6)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, anInstance = __webpack_require__(84)
, forOf = __webpack_require__(198)
, setProto = __webpack_require__(71).set
, speciesConstructor = __webpack_require__(199)
, task = __webpack_require__(200).set
, microtask = __webpack_require__(201)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[__webpack_require__(23)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(202)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
__webpack_require__(22)($Promise, PROMISE);
__webpack_require__(187)(PROMISE);
Wrapper = __webpack_require__(7)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(158)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(18)
, call = __webpack_require__(154)
, isArrayIter = __webpack_require__(155)
, anObject = __webpack_require__(10)
, toLength = __webpack_require__(35)
, getIterFn = __webpack_require__(157)
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(18)
, invoke = __webpack_require__(76)
, html = __webpack_require__(46)
, cel = __webpack_require__(13)
, global = __webpack_require__(2)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(__webpack_require__(32)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, macrotask = __webpack_require__(200).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = __webpack_require__(32)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
/***/ },
/* 202 */
/***/ function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(16);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
/***/ },
/* 203 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(204);
// 23.1 Map Objects
module.exports = __webpack_require__(205)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var dP = __webpack_require__(9).f
, create = __webpack_require__(44)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, ctx = __webpack_require__(18)
, anInstance = __webpack_require__(84)
, defined = __webpack_require__(33)
, forOf = __webpack_require__(198)
, $iterDefine = __webpack_require__(135)
, step = __webpack_require__(185)
, setSpecies = __webpack_require__(187)
, DESCRIPTORS = __webpack_require__(4)
, fastKey = __webpack_require__(20).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ },
/* 205 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, redefineAll = __webpack_require__(202)
, meta = __webpack_require__(20)
, forOf = __webpack_require__(198)
, anInstance = __webpack_require__(84)
, isObject = __webpack_require__(11)
, fails = __webpack_require__(5)
, $iterDetect = __webpack_require__(158)
, setToStringTag = __webpack_require__(22)
, inheritIfRequired = __webpack_require__(80);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ },
/* 206 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(204);
// 23.2 Set Objects
module.exports = __webpack_require__(205)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ },
/* 207 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var each = __webpack_require__(165)(0)
, redefine = __webpack_require__(16)
, meta = __webpack_require__(20)
, assign = __webpack_require__(67)
, weak = __webpack_require__(208)
, isObject = __webpack_require__(11)
, has = __webpack_require__(3)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(205)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ },
/* 208 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var redefineAll = __webpack_require__(202)
, getWeak = __webpack_require__(20).getWeak
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11)
, anInstance = __webpack_require__(84)
, forOf = __webpack_require__(198)
, createArrayMethod = __webpack_require__(165)
, $has = __webpack_require__(3)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ },
/* 209 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(208);
// 23.4 WeakSet Objects
__webpack_require__(205)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
/***/ },
/* 210 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(6)
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, _apply = Function.apply;
$export($export.S, 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
return _apply.call(aFunction(target), thisArgument, anObject(argumentsList));
}
});
/***/ },
/* 211 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = __webpack_require__(6)
, create = __webpack_require__(44)
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11)
, bind = __webpack_require__(75);
// MS Edge supports only 2 arguments
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
$export($export.S + $export.F * __webpack_require__(5)(function(){
function F(){}
return !(Reflect.construct(function(){}, [], F) instanceof F);
}), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
switch(args.length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ },
/* 212 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = __webpack_require__(9)
, $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, toPrimitive = __webpack_require__(14);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(5)(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 213 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(6)
, gOPD = __webpack_require__(49).f
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ },
/* 214 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
__webpack_require__(137)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
/***/ },
/* 215 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = __webpack_require__(49)
, getPrototypeOf = __webpack_require__(57)
, has = __webpack_require__(3)
, $export = __webpack_require__(6)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(10);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
/***/ },
/* 216 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = __webpack_require__(49)
, $export = __webpack_require__(6)
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
/***/ },
/* 217 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(6)
, getProto = __webpack_require__(57)
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
/***/ },
/* 218 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(6);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
/***/ },
/* 219 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ },
/* 220 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(6);
$export($export.S, 'Reflect', {ownKeys: __webpack_require__(221)});
/***/ },
/* 221 */
/***/ function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(48)
, gOPS = __webpack_require__(41)
, anObject = __webpack_require__(10)
, Reflect = __webpack_require__(2).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ },
/* 222 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 223 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = __webpack_require__(9)
, gOPD = __webpack_require__(49)
, getPrototypeOf = __webpack_require__(57)
, has = __webpack_require__(3)
, $export = __webpack_require__(6)
, createDesc = __webpack_require__(15)
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
/***/ },
/* 224 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(6)
, setProto = __webpack_require__(71);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 225 */
/***/ function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(6);
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
/***/ },
/* 226 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14);
$export($export.P + $export.F * __webpack_require__(5)(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
/***/ },
/* 227 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__(6)
, fails = __webpack_require__(5)
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
/***/ },
/* 228 */
/***/ function(module, exports, __webpack_require__) {
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
__webpack_require__(16)(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
/***/ },
/* 229 */
/***/ function(module, exports, __webpack_require__) {
var TO_PRIMITIVE = __webpack_require__(23)('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))__webpack_require__(8)(proto, TO_PRIMITIVE, __webpack_require__(230));
/***/ },
/* 230 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var anObject = __webpack_require__(10)
, toPrimitive = __webpack_require__(14)
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
/***/ },
/* 231 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $typed = __webpack_require__(232)
, buffer = __webpack_require__(233)
, anObject = __webpack_require__(10)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35)
, isObject = __webpack_require__(11)
, TYPED_ARRAY = __webpack_require__(23)('typed_array')
, ArrayBuffer = __webpack_require__(2).ArrayBuffer
, speciesConstructor = __webpack_require__(199)
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * __webpack_require__(5)(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
__webpack_require__(187)(ARRAY_BUFFER);
/***/ },
/* 232 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, hide = __webpack_require__(8)
, uid = __webpack_require__(17)
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ },
/* 233 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, DESCRIPTORS = __webpack_require__(4)
, LIBRARY = __webpack_require__(26)
, $typed = __webpack_require__(232)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, fails = __webpack_require__(5)
, anInstance = __webpack_require__(84)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, gOPN = __webpack_require__(48).f
, dP = __webpack_require__(9).f
, arrayFill = __webpack_require__(181)
, setToStringTag = __webpack_require__(22)
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, parseInt = global.parseInt
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, min = Math.min
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ },
/* 234 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.G + $export.W + $export.F * !__webpack_require__(232).ABV, {
DataView: __webpack_require__(233).DataView
});
/***/ },
/* 235 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 236 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
if(__webpack_require__(4)){
var LIBRARY = __webpack_require__(26)
, global = __webpack_require__(2)
, fails = __webpack_require__(5)
, $export = __webpack_require__(6)
, $typed = __webpack_require__(232)
, $buffer = __webpack_require__(233)
, ctx = __webpack_require__(18)
, anInstance = __webpack_require__(84)
, propertyDesc = __webpack_require__(15)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, isInteger = __webpack_require__(91)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, toIndex = __webpack_require__(37)
, toPrimitive = __webpack_require__(14)
, has = __webpack_require__(3)
, same = __webpack_require__(69)
, classof = __webpack_require__(73)
, isObject = __webpack_require__(11)
, toObject = __webpack_require__(56)
, isArrayIter = __webpack_require__(155)
, create = __webpack_require__(44)
, getPrototypeOf = __webpack_require__(57)
, gOPN = __webpack_require__(48).f
, isIterable = __webpack_require__(237)
, getIterFn = __webpack_require__(157)
, uid = __webpack_require__(17)
, wks = __webpack_require__(23)
, createArrayMethod = __webpack_require__(165)
, createArrayIncludes = __webpack_require__(34)
, speciesConstructor = __webpack_require__(199)
, ArrayIterators = __webpack_require__(184)
, Iterators = __webpack_require__(136)
, $iterDetect = __webpack_require__(158)
, setSpecies = __webpack_require__(187)
, arrayFill = __webpack_require__(181)
, arrayCopyWithin = __webpack_require__(178)
, $DP = __webpack_require__(9)
, $GOPD = __webpack_require__(49)
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
/***/ },
/* 237 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(73)
, ITERATOR = __webpack_require__(23)('iterator')
, Iterators = __webpack_require__(136);
module.exports = __webpack_require__(7).isIterable = function(it){
var O = Object(it);
return O[ITERATOR] !== undefined
|| '@@iterator' in O
|| Iterators.hasOwnProperty(classof(O));
};
/***/ },
/* 238 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 239 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
/***/ },
/* 240 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 241 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 242 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 243 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 244 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 245 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 246 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(6)
, $includes = __webpack_require__(34)(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(179)('includes');
/***/ },
/* 247 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = __webpack_require__(6)
, $at = __webpack_require__(126)(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
/***/ },
/* 248 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(6)
, $pad = __webpack_require__(249);
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ },
/* 249 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(35)
, repeat = __webpack_require__(86)
, defined = __webpack_require__(33);
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ },
/* 250 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(6)
, $pad = __webpack_require__(249);
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ },
/* 251 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(81)('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
/***/ },
/* 252 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(81)('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
/***/ },
/* 253 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = __webpack_require__(6)
, defined = __webpack_require__(33)
, toLength = __webpack_require__(35)
, isRegExp = __webpack_require__(129)
, getFlags = __webpack_require__(189)
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
__webpack_require__(137)($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
/***/ },
/* 254 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(25)('asyncIterator');
/***/ },
/* 255 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(25)('observable');
/***/ },
/* 256 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(6)
, ownKeys = __webpack_require__(221)
, toIObject = __webpack_require__(30)
, gOPD = __webpack_require__(49)
, createProperty = __webpack_require__(156);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key, D;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
/***/ },
/* 257 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(6)
, $values = __webpack_require__(258)(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
/***/ },
/* 258 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(28)
, toIObject = __webpack_require__(30)
, isEnum = __webpack_require__(42).f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
/***/ },
/* 259 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(6)
, $entries = __webpack_require__(258)(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
/***/ },
/* 260 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, aFunction = __webpack_require__(19)
, $defineProperty = __webpack_require__(9);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
/***/ },
/* 261 */
/***/ function(module, exports, __webpack_require__) {
// Forced replacement prototype accessors methods
module.exports = __webpack_require__(26)|| !__webpack_require__(5)(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete __webpack_require__(2)[K];
});
/***/ },
/* 262 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, aFunction = __webpack_require__(19)
, $defineProperty = __webpack_require__(9);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
/***/ },
/* 263 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14)
, getPrototypeOf = __webpack_require__(57)
, getOwnPropertyDescriptor = __webpack_require__(49).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
/***/ },
/* 264 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14)
, getPrototypeOf = __webpack_require__(57)
, getOwnPropertyDescriptor = __webpack_require__(49).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
__webpack_require__(4) && $export($export.P + __webpack_require__(261), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
/***/ },
/* 265 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(6);
$export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(266)('Map')});
/***/ },
/* 266 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __webpack_require__(73)
, from = __webpack_require__(267);
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
/***/ },
/* 267 */
/***/ function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(198);
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ },
/* 268 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(6);
$export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(266)('Set')});
/***/ },
/* 269 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-global
var $export = __webpack_require__(6);
$export($export.S, 'System', {global: __webpack_require__(2)});
/***/ },
/* 270 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-is-error
var $export = __webpack_require__(6)
, cof = __webpack_require__(32);
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
/***/ },
/* 271 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
/***/ },
/* 272 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
/***/ },
/* 273 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
/***/ },
/* 274 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
/***/ },
/* 275 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
/***/ },
/* 276 */
/***/ function(module, exports, __webpack_require__) {
var Map = __webpack_require__(203)
, $export = __webpack_require__(6)
, shared = __webpack_require__(21)('metadata')
, store = shared.store || (shared.store = new (__webpack_require__(207)));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
/***/ },
/* 277 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
/***/ },
/* 278 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 279 */
/***/ function(module, exports, __webpack_require__) {
var Set = __webpack_require__(206)
, from = __webpack_require__(267)
, metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 280 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 281 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 282 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 283 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 284 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(276)
, anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
/***/ },
/* 285 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = __webpack_require__(6)
, microtask = __webpack_require__(201)()
, process = __webpack_require__(2).process
, isNode = __webpack_require__(32)(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
/***/ },
/* 286 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/zenparsing/es-observable
var $export = __webpack_require__(6)
, global = __webpack_require__(2)
, core = __webpack_require__(7)
, microtask = __webpack_require__(201)()
, OBSERVABLE = __webpack_require__(23)('observable')
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, anInstance = __webpack_require__(84)
, redefineAll = __webpack_require__(202)
, hide = __webpack_require__(8)
, forOf = __webpack_require__(198)
, RETURN = forOf.RETURN;
var getMethod = function(fn){
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function(subscription){
var cleanup = subscription._c;
if(cleanup){
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function(subscription){
return subscription._o === undefined;
};
var closeSubscription = function(subscription){
if(!subscriptionClosed(subscription)){
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function(observer, subscriber){
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer)
, subscription = cleanup;
if(cleanup != null){
if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch(e){
observer.error(e);
return;
} if(subscriptionClosed(this))cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe(){ closeSubscription(this); }
});
var SubscriptionObserver = function(subscription){
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if(m)return m.call(observer, value);
} catch(e){
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value){
var subscription = this._s;
if(subscriptionClosed(subscription))throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if(!m)throw value;
value = m.call(observer, value);
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber){
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer){
return new Subscription(observer, this._f);
},
forEach: function forEach(fn){
var that = this;
return new (core.Promise || global.Promise)(function(resolve, reject){
aFunction(fn);
var subscription = that.subscribe({
next : function(value){
try {
return fn(value);
} catch(e){
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x){
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if(method){
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function(observer){
return observable.subscribe(observer);
});
}
return new C(function(observer){
var done = false;
microtask(function(){
if(!done){
try {
if(forOf(x, false, function(it){
observer.next(it);
if(done)return RETURN;
}) === RETURN)return;
} catch(e){
if(done)throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function(){ done = true; };
});
},
of: function of(){
for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function(observer){
var done = false;
microtask(function(){
if(!done){
for(var i = 0; i < items.length; ++i){
observer.next(items[i]);
if(done)return;
} observer.complete();
}
});
return function(){ done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function(){ return this; });
$export($export.G, {Observable: $Observable});
__webpack_require__(187)('Observable');
/***/ },
/* 287 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $task = __webpack_require__(200);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ },
/* 288 */
/***/ function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__(184)
, redefine = __webpack_require__(16)
, global = __webpack_require__(2)
, hide = __webpack_require__(8)
, Iterators = __webpack_require__(136)
, wks = __webpack_require__(23)
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
/***/ },
/* 289 */
/***/ function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var global = __webpack_require__(2)
, $export = __webpack_require__(6)
, invoke = __webpack_require__(76)
, partial = __webpack_require__(290)
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
/***/ },
/* 290 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var path = __webpack_require__(291)
, invoke = __webpack_require__(76)
, aFunction = __webpack_require__(19);
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
/***/ },
/* 291 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2);
/***/ },
/* 292 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(18)
, $export = __webpack_require__(6)
, createDesc = __webpack_require__(15)
, assign = __webpack_require__(67)
, create = __webpack_require__(44)
, getPrototypeOf = __webpack_require__(57)
, getKeys = __webpack_require__(28)
, dP = __webpack_require__(9)
, keyOf = __webpack_require__(27)
, aFunction = __webpack_require__(19)
, forOf = __webpack_require__(198)
, isIterable = __webpack_require__(237)
, $iterCreate = __webpack_require__(137)
, step = __webpack_require__(185)
, isObject = __webpack_require__(11)
, toIObject = __webpack_require__(30)
, DESCRIPTORS = __webpack_require__(4)
, has = __webpack_require__(3);
// 0 -> Dict.forEach
// 1 -> Dict.map
// 2 -> Dict.filter
// 3 -> Dict.some
// 4 -> Dict.every
// 5 -> Dict.find
// 6 -> Dict.findKey
// 7 -> Dict.mapPairs
var createDictMethod = function(TYPE){
var IS_MAP = TYPE == 1
, IS_EVERY = TYPE == 4;
return function(object, callbackfn, that /* = undefined */){
var f = ctx(callbackfn, that, 3)
, O = toIObject(object)
, result = IS_MAP || TYPE == 7 || TYPE == 2
? new (typeof this == 'function' ? this : Dict) : undefined
, key, val, res;
for(key in O)if(has(O, key)){
val = O[key];
res = f(val, key, object);
if(TYPE){
if(IS_MAP)result[key] = res; // map
else if(res)switch(TYPE){
case 2: result[key] = val; break; // filter
case 3: return true; // some
case 5: return val; // find
case 6: return key; // findKey
case 7: result[res[0]] = res[1]; // mapPairs
} else if(IS_EVERY)return false; // every
}
}
return TYPE == 3 || IS_EVERY ? IS_EVERY : result;
};
};
var findKey = createDictMethod(6);
var createDictIter = function(kind){
return function(it){
return new DictIterator(it, kind);
};
};
var DictIterator = function(iterated, kind){
this._t = toIObject(iterated); // target
this._a = getKeys(iterated); // keys
this._i = 0; // next index
this._k = kind; // kind
};
$iterCreate(DictIterator, 'Dict', function(){
var that = this
, O = that._t
, keys = that._a
, kind = that._k
, key;
do {
if(that._i >= keys.length){
that._t = undefined;
return step(1);
}
} while(!has(O, key = keys[that._i++]));
if(kind == 'keys' )return step(0, key);
if(kind == 'values')return step(0, O[key]);
return step(0, [key, O[key]]);
});
function Dict(iterable){
var dict = create(null);
if(iterable != undefined){
if(isIterable(iterable)){
forOf(iterable, true, function(key, value){
dict[key] = value;
});
} else assign(dict, iterable);
}
return dict;
}
Dict.prototype = null;
function reduce(object, mapfn, init){
aFunction(mapfn);
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, i = 0
, memo, key;
if(arguments.length < 3){
if(!length)throw TypeError('Reduce of empty object with no initial value');
memo = O[keys[i++]];
} else memo = Object(init);
while(length > i)if(has(O, key = keys[i++])){
memo = mapfn(memo, O[key], key, object);
}
return memo;
}
function includes(object, el){
return (el == el ? keyOf(object, el) : findKey(object, function(it){
return it != it;
})) !== undefined;
}
function get(object, key){
if(has(object, key))return object[key];
}
function set(object, key, value){
if(DESCRIPTORS && key in Object)dP.f(object, key, createDesc(0, value));
else object[key] = value;
return object;
}
function isDict(it){
return isObject(it) && getPrototypeOf(it) === Dict.prototype;
}
$export($export.G + $export.F, {Dict: Dict});
$export($export.S, 'Dict', {
keys: createDictIter('keys'),
values: createDictIter('values'),
entries: createDictIter('entries'),
forEach: createDictMethod(0),
map: createDictMethod(1),
filter: createDictMethod(2),
some: createDictMethod(3),
every: createDictMethod(4),
find: createDictMethod(5),
findKey: findKey,
mapPairs: createDictMethod(7),
reduce: reduce,
keyOf: keyOf,
includes: includes,
has: has,
get: get,
set: set,
isDict: isDict
});
/***/ },
/* 293 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(10)
, get = __webpack_require__(157);
module.exports = __webpack_require__(7).getIterator = function(it){
var iterFn = get(it);
if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
/***/ },
/* 294 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, $export = __webpack_require__(6)
, partial = __webpack_require__(290);
// https://esdiscuss.org/topic/promise-returning-delay-function
$export($export.G + $export.F, {
delay: function delay(time){
return new (core.Promise || global.Promise)(function(resolve){
setTimeout(partial.call(resolve, true), time);
});
}
});
/***/ },
/* 295 */
/***/ function(module, exports, __webpack_require__) {
var path = __webpack_require__(291)
, $export = __webpack_require__(6);
// Placeholder
__webpack_require__(7)._ = path._ = path._ || {};
$export($export.P + $export.F, 'Function', {part: __webpack_require__(290)});
/***/ },
/* 296 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.S + $export.F, 'Object', {isObject: __webpack_require__(11)});
/***/ },
/* 297 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.S + $export.F, 'Object', {classof: __webpack_require__(73)});
/***/ },
/* 298 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, define = __webpack_require__(299);
$export($export.S + $export.F, 'Object', {define: define});
/***/ },
/* 299 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, gOPD = __webpack_require__(49)
, ownKeys = __webpack_require__(221)
, toIObject = __webpack_require__(30);
module.exports = function define(target, mixin){
var keys = ownKeys(toIObject(mixin))
, length = keys.length
, i = 0, key;
while(length > i)dP.f(target, key = keys[i++], gOPD.f(mixin, key));
return target;
};
/***/ },
/* 300 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, define = __webpack_require__(299)
, create = __webpack_require__(44);
$export($export.S + $export.F, 'Object', {
make: function(proto, mixin){
return define(create(proto), mixin);
}
});
/***/ },
/* 301 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(135)(Number, 'Number', function(iterated){
this._l = +iterated;
this._i = 0;
}, function(){
var i = this._i++
, done = !(i < this._l);
return {done: done, value: done ? undefined : i};
});
/***/ },
/* 302 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/benjamingr/RexExp.escape
var $export = __webpack_require__(6)
, $re = __webpack_require__(303)(/[\\^$*+?.()|[\]{}]/g, '\\$&');
$export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }});
/***/ },
/* 303 */
/***/ function(module, exports) {
module.exports = function(regExp, replace){
var replacer = replace === Object(replace) ? function(part){
return replace[part];
} : replace;
return function(it){
return String(it).replace(regExp, replacer);
};
};
/***/ },
/* 304 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6);
var $re = __webpack_require__(303)(/[&<>"']/g, {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
});
$export($export.P + $export.F, 'String', {escapeHTML: function escapeHTML(){ return $re(this); }});
/***/ },
/* 305 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6);
var $re = __webpack_require__(303)(/&(?:amp|lt|gt|quot|apos);/g, {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
});
$export($export.P + $export.F, 'String', {unescapeHTML: function unescapeHTML(){ return $re(this); }});
/***/ }
/******/ ]);
// CommonJS export
if(typeof module != 'undefined' && module.exports)module.exports = __e;
// RequireJS export
else if(typeof define == 'function' && define.amd)define(function(){return __e});
// Export to global object
else __g.core = __e;
}(1, 1); |
ajax/libs/analytics.js/2.3.26/analytics.min.js | dominicrico/cdnjs | (function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require})({1:[function(require,module,exports){var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("./version");each(Integrations,function(name,Integration){analytics.use(Integration)})},{"analytics.js-integrations":2,"./analytics":3,each:4,"./version":5}],2:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{each:4,"./integrations.js":6}],4:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:7}],7:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],6:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/awesm"),require("./lib/awesomatic"),require("./lib/bing-ads"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/facebook-conversion-tracking"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/leadlander"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")]},{"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/awesm":13,"./lib/awesomatic":14,"./lib/bing-ads":15,"./lib/bronto":16,"./lib/bugherd":17,"./lib/bugsnag":18,"./lib/chartbeat":19,"./lib/churnbee":20,"./lib/clicktale":21,"./lib/clicky":22,"./lib/comscore":23,"./lib/crazy-egg":24,"./lib/curebit":25,"./lib/customerio":26,"./lib/drip":27,"./lib/errorception":28,"./lib/evergage":29,"./lib/facebook-conversion-tracking":30,"./lib/foxmetrics":31,"./lib/frontleaf":32,"./lib/gauges":33,"./lib/get-satisfaction":34,"./lib/google-analytics":35,"./lib/google-tag-manager":36,"./lib/gosquared":37,"./lib/heap":38,"./lib/hellobar":39,"./lib/hittail":40,"./lib/hubspot":41,"./lib/improvely":42,"./lib/insidevault":43,"./lib/inspectlet":44,"./lib/intercom":45,"./lib/keen-io":46,"./lib/kenshoo":47,"./lib/kissmetrics":48,"./lib/klaviyo":49,"./lib/leadlander":50,"./lib/livechat":51,"./lib/lucky-orange":52,"./lib/lytics":53,"./lib/mixpanel":54,"./lib/mojn":55,"./lib/mouseflow":56,"./lib/mousestats":57,"./lib/navilytics":58,"./lib/olark":59,"./lib/optimizely":60,"./lib/perfect-audience":61,"./lib/pingdom":62,"./lib/piwik":63,"./lib/preact":64,"./lib/qualaroo":65,"./lib/quantcast":66,"./lib/rollbar":67,"./lib/saasquatch":68,"./lib/sentry":69,"./lib/snapengage":70,"./lib/spinnakr":71,"./lib/tapstream":72,"./lib/trakio":73,"./lib/twitter-ads":74,"./lib/uservoice":75,"./lib/vero":76,"./lib/visual-website-optimizer":77,"./lib/webengage":78,"./lib/woopra":79,"./lib/yandex-metrica":80}],8:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;each(events,function(event){var data={};if(user.id())data.user_id=user.id();data.adroll_conversion_value_in_dollars=total;data.order_id=orderId;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){var data={};if(user.id())data.user_id=user.id();data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":81,"to-snake-case":82,"use-https":83,each:4,is:84}],81:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{bind:85,callback:86,clone:87,debug:88,defaults:89,"./protos":90,slug:91,"./statics":92}],85:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:93,"bind-all":94}],93:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],94:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:93,type:7}],86:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":95}],95:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],87:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],88:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":96,"./debug":97}],96:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m[90m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"[0m";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],97:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],89:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],90:[function(require,module,exports){var loadScript=require("segmentio/load-script");var events=require("analytics-events");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var tick=require("next-tick");var assert=require("assert");var after=require("after");var each=require("component/each");var type=require("type");var fmt=require("fmt");var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=null;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];assert(template,fmt('Template "%s" not defined.',name));var attrs=render(template,locals);var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,fn);delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"segmentio/load-script":98,"analytics-events":99,"to-no-case":100,callback:86,emitter:101,"next-tick":95,assert:102,after:103,"component/each":104,type:7,fmt:105}],98:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":106,"next-tick":95,type:7}],106:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}},{}],99:[function(require,module,exports){module.exports={removedProduct:/^[ _]?removed[ _]?product[ _]?$/i,viewedProduct:/^[ _]?viewed[ _]?product[ _]?$/i,viewedProductCategory:/^[ _]?viewed[ _]?product[ _]?category[ _]?$/i,addedProduct:/^[ _]?added[ _]?product[ _]?$/i,completedOrder:/^[ _]?completed[ _]?order[ _]?$/i}},{}],100:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],101:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:107}],107:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],102:[function(require,module,exports){var equals=require("equals");var fmt=require("fmt");var stack=require("stack");module.exports=exports=function(expr,msg){if(expr)return;throw new Error(msg||message())};exports.equal=function(actual,expected,msg){if(actual==expected)return;throw new Error(msg||fmt("Expected %o to equal %o.",actual,expected))};exports.notEqual=function(actual,expected,msg){if(actual!=expected)return;throw new Error(msg||fmt("Expected %o not to equal %o.",actual,expected))};exports.deepEqual=function(actual,expected,msg){if(equals(actual,expected))return;throw new Error(msg||fmt("Expected %o to deeply equal %o.",actual,expected))};exports.notDeepEqual=function(actual,expected,msg){if(!equals(actual,expected))return;throw new Error(msg||fmt("Expected %o not to deeply equal %o.",actual,expected))};exports.strictEqual=function(actual,expected,msg){if(actual===expected)return;throw new Error(msg||fmt("Expected %o to strictly equal %o.",actual,expected))};exports.notStrictEqual=function(actual,expected,msg){if(actual!==expected)return;throw new Error(msg||fmt("Expected %o not to strictly equal %o.",actual,expected))};exports.throws=function(block,error,msg){var err;try{block()}catch(e){err=e}if(!err)throw new Error(msg||fmt("Expected %s to throw an error.",block.toString()));if(error&&!(err instanceof error)){throw new Error(msg||fmt("Expected %s to throw an %o.",block.toString(),error))}};exports.doesNotThrow=function(block,error,msg){var err;try{block()}catch(e){err=e}if(err)throw new Error(msg||fmt("Expected %s not to throw an error.",block.toString()));if(error&&err instanceof error){throw new Error(msg||fmt("Expected %s not to throw an %o.",block.toString(),error))}};function message(){if(!Error.captureStackTrace)return"assertion failed";var callsite=stack()[2];var fn=callsite.getFunctionName();var file=callsite.getFileName();var line=callsite.getLineNumber()-1;var col=callsite.getColumnNumber()-1;var src=get(file);line=src.split("\n")[line].slice(col);var m=line.match(/assert\((.*)\)/);return m&&m[1].trim()}function get(script){var xhr=new XMLHttpRequest;xhr.open("GET",script,false);xhr.send(null);return xhr.responseText}},{equals:108,fmt:105,stack:109}],108:[function(require,module,exports){var type=require("type");function equals(a,b,memos){if(a===b)return true;var fnA=types[type(a)];var fnB=types[type(b)];return fnA&&fnA===fnB?fnA(a,b,memos):false}var types={};types.number=function(a){return a!==a};types["function"]=function(a,b,memos){return a.toString()===b.toString()&&types.object(a,b,memos)&&equals(a.prototype,b.prototype)};types.date=function(a,b){return+a===+b};types.regexp=function(a,b){return a.toString()===b.toString()};types.element=function(a,b){return a.outerHTML===b.outerHTML};types.textnode=function(a,b){return a.textContent===b.textContent};function memoGaurd(fn){return function(a,b,memos){if(!memos)return fn(a,b,[]);var i=memos.length,memo;while(memo=memos[--i]){if(memo[0]===a&&memo[1]===b)return true}return fn(a,b,memos)}}types["arguments"]=types.array=memoGaurd(compareArrays);function compareArrays(a,b,memos){var i=a.length;if(i!==b.length)return false;memos.push([a,b]);while(i--){if(!equals(a[i],b[i],memos))return false}return true}types.object=memoGaurd(compareObjects);function compareObjects(a,b,memos){var ka=getEnumerableProperties(a);var kb=getEnumerableProperties(b);var i=ka.length;if(i!==kb.length)return false;ka.sort();kb.sort();while(i--)if(ka[i]!==kb[i])return false;memos.push([a,b]);i=ka.length;while(i--){var key=ka[i];if(!equals(a[key],b[key],memos))return false}return true}function getEnumerableProperties(object){var result=[];for(var k in object)if(k!=="constructor"){result.push(k)}return result}function allEqual(){var i=arguments.length-1;while(i>0){if(!equals(arguments[i],arguments[--i]))return false}return true}module.exports=allEqual;allEqual.compare=equals},{type:110}],110:[function(require,module,exports){var toString={}.toString;var DomNode=typeof window!="undefined"?window.Node:Function;module.exports=exports=function(x){var type=typeof x;if(type!="object")return type;type=types[toString.call(x)];if(type)return type;if(x instanceof DomNode)switch(x.nodeType){case 1:return"element";case 3:return"text-node";case 9:return"document";case 11:return"document-fragment";default:return"dom-node"}};var types=exports.types={"[object Function]":"function","[object Date]":"date","[object RegExp]":"regexp","[object Arguments]":"arguments","[object Array]":"array","[object String]":"string","[object Null]":"null","[object Undefined]":"undefined","[object Number]":"number","[object Boolean]":"boolean","[object Object]":"object","[object Text]":"text-node","[object Uint8Array]":"bit-array","[object Uint16Array]":"bit-array","[object Uint32Array]":"bit-array","[object Uint8ClampedArray]":"bit-array","[object Error]":"error","[object FormData]":"form-data","[object File]":"file","[object Blob]":"blob"}},{}],105:[function(require,module,exports){var toString=window.JSON?JSON.stringify:function(_){return String(_)};module.exports=fmt;fmt.o=toString;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],109:[function(require,module,exports){module.exports=stack;function stack(){var orig=Error.prepareStackTrace;Error.prepareStackTrace=function(_,stack){return stack};var err=new Error;Error.captureStackTrace(err,arguments.callee);var stack=err.stack;Error.prepareStackTrace=orig;return stack}},{}],103:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],104:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:7,"component-type":7,"to-function":111}],111:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:112,"component-props":112}],112:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],91:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],92:[function(require,module,exports){var after=require("after");var domify=require("domify");var each=require("each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);
this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:103,domify:113,each:104,emitter:101}],113:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],82:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":114}],114:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":115}],115:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],83:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],84:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":116,type:7,"component-type":7}],116:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],9:[function(require,module,exports){var integration=require("analytics.js-integration");var domify=require("domify");var each=require("each");var has=Object.prototype.hasOwnProperty;var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">').mapping("events");AdWords.prototype.initialize=function(){this.load(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=!!this.options.remarketing;var id=this.options.conversionId;var props={};window.google_trackConversion({google_conversion_id:id,google_custom_params:props,google_remarketing_only:remarketing})};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;each(events,function(label){var props=track.properties();window.google_trackConversion({google_conversion_id:id,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:label,google_conversion_value:revenue,google_remarketing_only:false})})}},{"analytics.js-integration":81,domify:113,each:4}],10:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":81}],11:[function(require,module,exports){var integration=require("analytics.js-integration");var Amplitude=module.exports=integration("Amplitude").global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load(this.ready)};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event();window.amplitude.logEvent(event,props)}},{"analytics.js-integration":81}],12:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":81,"load-script":117,is:84}],117:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":106,"next-tick":95,type:7}],13:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":81,each:4}],14:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var noop=function(){};var onBody=require("on-body");var Awesomatic=module.exports=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","").tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');Awesomatic.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.ready()})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)}},{"analytics.js-integration":81,is:84,"on-body":118}],118:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:104}],15:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").option("siteId","").option("domainId","").tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">').mapping("events");Bing.prototype.initialize=function(page){if(!window.mstag){window.mstag={loadTag:noop,time:(new Date).getTime(),_write:writeToAppend}}var self=this;onbody(function(){self.load(function(){var loaded=bind(self,self.loaded);when(loaded,self.ready)})})};Bing.prototype.loaded=function(){return!!(window.mstag&&window.mstag.loadTag!==noop)};Bing.prototype.track=function(track){var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(goal){window.mstag.loadTag("analytics",{domainId:self.options.domainId,revenue:revenue,dedup:"1",type:"1",actionid:goal})})};function writeToAppend(str){var first=document.getElementsByTagName("script")[0];var el=domify(str);if("script"==el.tagName.toLowerCase()&&el.getAttribute("src")){var tmp=document.createElement("script");tmp.src=el.getAttribute("src");tmp.async=true;el=tmp}document.body.appendChild(el)}},{"analytics.js-integration":81,"on-body":118,domify:113,extend:119,bind:93,when:120,each:4}],119:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],120:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:86}],16:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":81,facade:121,"load-pixel":122,querystring:123,each:4}],121:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":124,"./alias":125,"./group":126,"./identify":127,"./track":128,"./page":129,"./screen":130}],124:[function(require,module,exports){var traverse=require("isodate-traverse");var isEnabled=require("./is-enabled");var clone=require("./utils").clone;var type=require("./utils").type;var address=require("./address");var objCase=require("obj-case");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}address(Facade.prototype);Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.multi=function(path){return function(){var multi=this.proxy(path+"s");if("array"==type(multi))return multi;var one=this.proxy(path);if(one)one=[clone(one)];return one||[]}};Facade.one=function(path){return function(){var one=this.proxy(path);if(one)return one;var multi=this.proxy(path+"s");if("array"==type(multi))return multi[0]}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"isodate-traverse":131,"./is-enabled":132,"./utils":133,"./address":134,"obj-case":135,"new-date":136}],131:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:137,isodate:138,each:4}],137:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":116,type:7,"component-type":7}],138:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],132:[function(require,module,exports){var disabled={Salesforce:true};module.exports=function(integration){return!disabled[integration]}},{}],133:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone");exports.type=require("type")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component");exports.type=require("type-component")}},{inherit:139,clone:140,type:7}],139:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],140:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":7,type:7}],134:[function(require,module,exports){var get=require("obj-case");module.exports=function(proto){proto.zip=trait("postalCode","zip");proto.country=trait("country");proto.street=trait("street");proto.state=trait("state");proto.city=trait("city");function trait(a,b){return function(){var traits=this.traits();var props=this.properties?this.properties():{};return get(traits,"address."+a)||get(traits,a)||(b?get(traits,"address."+b):null)||(b?get(traits,b):null)||get(props,"address."+a)||get(props,a)||(b?get(props,"address."+b):null)||(b?get(props,b):null)}}}},{"obj-case":135}],135:[function(require,module,exports){var identity=function(_){return _};module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,path,val){path=normalize(path);var key;var finished=false;while(!finished)loop();function loop(){for(key in obj){var normalizedKey=normalize(key);if(0===path.indexOf(normalizedKey)){var temp=path.substr(normalizedKey.length);if(temp.charAt(0)==="."||temp.length===0){path=temp.substr(1);var child=obj[key];if(null==child){finished=true;return}if(!path.length){finished=true;return}obj=child;return}}}key=undefined;finished=true}if(!key)return;if(null==obj)return obj;return fn(obj,key,val)}}function find(obj,key){if(obj.hasOwnProperty(key))return obj[key]}function del(obj,key){if(obj.hasOwnProperty(key))delete obj[key];return obj}function replace(obj,key,val){if(obj.hasOwnProperty(key))obj[key]=val;return obj}function normalize(path){return path.replace(/[^a-zA-Z0-9\.]+/g,"").toLowerCase()}},{}],136:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{is:141,isodate:138,"./milliseconds":142,"./seconds":143}],141:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":116,type:7}],142:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],143:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],125:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":133,"./facade":124}],126:[function(require,module,exports){var inherit=require("./utils").inherit;var address=require("./address");var isEmail=require("is-email");var newDate=require("new-date");var Facade=require("./facade");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var groupId=this.groupId();if(isEmail(groupId))return groupId};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.name=Facade.proxy("traits.name");Group.prototype.industry=Facade.proxy("traits.industry");Group.prototype.employees=Facade.proxy("traits.employees");Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":133,"./address":134,"is-email":144,"new-date":136,"./facade":124}],144:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],127:[function(require,module,exports){var address=require("./address");var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var get=require("obj-case");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;var type=utils.type;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.age=function(){var date=this.birthday();var age=get(this.traits(),"age");if(null!=age)return age;if("date"!=type(date))return;var now=new Date;return now.getFullYear()-date.getFullYear()};Identify.prototype.avatar=function(){var traits=this.traits();return get(traits,"avatar")||get(traits,"photoUrl")||get(traits,"avatarUrl")};Identify.prototype.position=function(){var traits=this.traits();return get(traits,"position")||get(traits,"jobTitle")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.one("traits.website");Identify.prototype.websites=Facade.multi("traits.website");Identify.prototype.phone=Facade.one("traits.phone");Identify.prototype.phones=Facade.multi("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.gender=Facade.proxy("traits.gender");Identify.prototype.birthday=Facade.proxy("traits.birthday")},{"./address":134,"./facade":124,"is-email":144,"new-date":136,"./utils":133,"obj-case":135,trim:145}],145:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();
return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],128:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var type=require("./utils").type;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");var get=require("obj-case");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.discount=Facade.proxy("properties.discount");Track.prototype.description=Facade.proxy("properties.description");Track.prototype.plan=Facade.proxy("properties.plan");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=get(this.properties(),"subtotal");var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;if(n=this.discount())total+=n;return total};Track.prototype.products=function(){var props=this.properties();var products=get(props,"products");return"array"==type(products)?products:[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":133,"./facade":124,"./identify":127,"is-email":144,"obj-case":135}],129:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.title=Facade.proxy("properties.title");Page.prototype.path=Facade.proxy("properties.path");Page.prototype.url=Facade.proxy("properties.url");Page.prototype.referrer=function(){return this.proxy("properties.referrer")||this.proxy("context.referrer.url")};Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":133,"./facade":124,"./track":128}],130:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),timestamp:this.timestamp(),context:this.context(),properties:props})}},{"./utils":133,"./page":129,"./track":128}],122:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:123,substitute:146}],123:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:145,type:7}],146:[function(require,module,exports){module.exports=substitute;var type=Object.prototype.toString;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){switch(type.call(obj)){case"[object Object]":return null!=obj[prop]?obj[prop]:_;case"[object Array]":var val=obj.shift();return null!=val?val:_}})}},{}],17:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":81,"next-tick":95}],18:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var umd="function"==typeof define&&define.amd;var src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js";var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="'+src+'">');Bugsnag.prototype.initialize=function(page){var self=this;if(umd){window.require([src],function(bugsnag){bugsnag.apiKey=self.options.apiKey;window.Bugsnag=bugsnag;self.ready()});return}this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":81,is:84,extend:119,"on-error":147}],147:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],19:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":81,defaults:148,"on-body":118}],148:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],20:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":81,"global-queue":149,each:4}],149:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],21:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":150,domify:113,each:4,"analytics.js-integration":81,is:84,"use-https":83,"on-body":118}],150:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],22:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:121,extend:119,"analytics.js-integration":81,is:84}],23:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE}},{"analytics.js-integration":81,"use-https":83}],24:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":81}],25:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":81,"global-queue":149,facade:121,throttle:151,"to-iso-string":152,clone:153,each:4,bind:93}],151:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],152:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],153:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:7}],26:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").assumesPageview().global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!window._cio&&window._cio.push!==Array.prototype.push};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:154,"convert-dates":155,facade:121,"analytics.js-integration":81}],154:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:7,clone:140}],155:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:84,clone:87}],27:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("dc").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=track.cents();if(cents)props.value=cents;delete props.revenue;push("track",track.event(),props)};Drip.prototype.identify=function(identify){push("identify",identify.traits())}},{alias:154,"analytics.js-integration":81,is:84,"load-script":117,"global-queue":149}],28:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:119,"analytics.js-integration":81,"on-error":147,"global-queue":149}],29:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:4,"analytics.js-integration":81,"global-queue":149}],30:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Conversion Tracking").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})});if(!events.length){var data=track.properties();push("track",event,data)}}},{"analytics.js-integration":81,"global-queue":149,each:4}],31:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":149,"analytics.js-integration":81,facade:121,each:4}],32:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").assumesPageview().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event();this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":81,bind:93,when:120,is:84}],33:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');
Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":81,"global-queue":149}],34:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":81,"on-body":118}],35:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var keys=require("object").keys;var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","userId",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();window.ga("send","event",{eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId,currency:track.currency()});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId,currency:track.currency()})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();var currency=track.currency();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_set","currencyCode",currency);push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name)||obj[name];if(null==value)continue;ret[key]=value}return ret}},{"analytics.js-integration":81,"global-queue":149,object:156,canonical:157,"use-https":83,facade:121,callback:86,"load-script":117,"obj-case":158,each:4,type:7,url:159,is:84}],156:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],157:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],158:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}},{"case":160}],160:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":161}],161:[function(require,module,exports){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none},{"to-camel-case":162,"to-capital-case":163,"to-constant-case":164,"to-dot-case":165,"to-no-case":115,"to-pascal-case":166,"to-sentence-case":167,"to-slug-case":168,"to-snake-case":169,"to-space-case":170,"to-title-case":171}],162:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":170}],170:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":115}],163:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":115}],164:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":169}],169:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":170}],165:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":170}],166:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":170}],167:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":115}],168:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":170}],171:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":163,"escape-regexp":172,map:173,"title-case-minors":174}],172:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],173:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:104}],174:[function(require,module,exports){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]},{}],159:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],36:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":149,"analytics.js-integration":81}],37:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":81,facade:121,callback:86,"load-script":117,"on-body":118,each:4}],38:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").assumesPageview().global("heap").global("_heapid").option("apiKey","").tag('<script src="//d36lvucg9kzous.cloudfront.net">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":81,alias:154}],39:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":81}],40:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":81,is:84}],41:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":81,"global-queue":149,"convert-dates":155}],42:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":81,alias:154}],43:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);var userId=this.analytics.user().id();if(userId)push("setUserId",userId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.identify=function(identify){push("setUserId",identify.userId())};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.options.events;var event=track.event();var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";if(!has.call(events,event))return;event=events[event];if(event!="sale"){push("trackEvent",event,value,eventId)}}},{"analytics.js-integration":81,"global-queue":149,facade:121,is:84}],44:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//www.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!(window.__insp_&&window.__insp)};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}},{"analytics.js-integration":81,"global-queue":149,alias:154,clone:153}],45:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(traits.company&&companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company)traits.company=alias(traits.company,{created:"created_at"});if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":81,"convert-dates":155,defaults:148,"is-email":144,"load-script":117,"is-empty":116,alias:154,each:4,when:120,is:84}],46:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("ipAddon",false).option("uaAddon",false).option("urlAddon",false).option("referrerAddon",false).option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">');Keen.prototype.initialize=function(){var options=this.options;!function(a,b){if(void 0===b[a]){b["_"+a]={},b[a]=function(c){b["_"+a].clients=b["_"+a].clients||{},b["_"+a].clients[c.projectId]=this,this._config=c},b[a].ready=function(c){b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c)};for(var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){var e=c[d],f=function(a){return function(){return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this}};b[a].prototype[e]=f(e)}}}("Keen",window);this.client=new window.Keen({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});var lib=this.options.readKey?"keen":"keen-tracker";this.load({lib:lib},this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.prototype.configure)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};var options=this.options;if(id)user.userId=id;if(traits)user.traits=traits;var props={user:user};var addons=[];if(options.ipAddon){addons.push({name:"keen:ip_to_geo",input:{ip:"ip_address"},output:"ip_geo_info"});props.ip_address="${keen.ip}"}if(options.uaAddon){addons.push({name:"keen:ua_parser",input:{ua_string:"user_agent"},output:"parsed_user_agent"});props.user_agent="${keen.user_agent}"}if(options.urlAddon){addons.push({name:"keen:url_parser",input:{url:"page_url"},output:"parsed_page_url"});props.page_url=document.location.href}if(options.referrerAddon){addons.push({name:"keen:referrer_parser",input:{referrer_url:"referrer_url",page_url:"page_url"},output:"referrer_info"});props.referrer_url=document.referrer;props.page_url=document.location.href}props.keen={timestamp:identify.timestamp(),addons:addons};this.client.setGlobalProperties(function(){return clone(props)})};Keen.prototype.track=function(track){this.client.addEvent(track.event(),track.properties())}},{"analytics.js-integration":81,clone:153}],47:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":81,indexof:107,is:84}],48:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var Batch=require("batch");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("useless",'<script src="//i.kissmetrics.com/i.js">').tag("library",'<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">');
exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});var batch=new Batch;batch.push(function(done){self.load("useless",done)});batch.push(function(done){self.load("library",done)});batch.end(function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var temp=new Track({event:event,properties:product});var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":81,"global-queue":149,facade:121,alias:154,batch:175,each:4,is:84}],175:[function(require,module,exports){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}},{emitter:176}],176:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],49:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":81,"global-queue":149,"next-tick":95,alias:154}],50:[function(require,module,exports){var integration=require("analytics.js-integration");var LeadLander=module.exports=integration("LeadLander").assumesPageview().global("llactid").global("trackalyzer").option("accountId",null).tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load(this.ready)};LeadLander.prototype.loaded=function(){return!!window.trackalyzer}},{"analytics.js-integration":81}],51:[function(require,module,exports){var integration=require("analytics.js-integration");var clone=require("clone");var each=require("each");var Identify=require("facade").Identify;var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var identify=new Identify({userId:user.id(),traits:user.traits()});window.__lc=clone(this.options);window.__lc.visitor={name:identify.name(),email:identify.email()};this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":81,clone:153,each:4,facade:121,when:120}],52:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":81,facade:121,"use-https":83}],53:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":81,alias:154}],54:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var is=require("is");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var some=require("some");var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(dates(traits,iso));if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;for(var key in props){var val=props[key];if(is.array(val)&&some(val,is.object))props[key]=val.length}if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:154,clone:153,"convert-dates":155,"analytics.js-integration":81,is:84,"to-iso-string":152,indexof:107,"obj-case":158,some:177}],177:[function(require,module,exports){var some=[].some;module.exports=function(arr,fn){if(some)return some.call(arr,fn);for(var i=0,l=arr.length;i<l;++i){if(fn(arr[i],i))return true}return false}},{}],55:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":81,bind:93,when:120,is:84}],56:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":149,"analytics.js-integration":81,each:4}],57:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":81,"use-https":83,each:4,is:84}],58:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":81,"global-queue":149}],59:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId)api("chat.setOperatorGroup",{group:groupId});api("box.onExpand",function(){self._open=true});api("box.onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;name=name?name+" page":props.url;this.notify("looking at "+name)};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();if(traits)api("visitor.updateCustomFields",traits);if(email)api("visitor.updateEmailAddress",{emailAddress:email});if(phone)api("visitor.updatePhoneNumber",{phoneNumber:phone});if(name)api("visitor.updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)api("chat.updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track)return;this.notify('visitor triggered "'+track.event()+'"')};Olark.prototype.notify=function(message){if(!this._open)return;message=message.toLowerCase();api("visitor.getDetails",function(data){if(!data||!data.isConversing)return;api("chat.sendNotificationToOperator",{body:message})})};function api(action,value){window.olark("api."+action,value)}},{"analytics.js-integration":81,"use-https":83,"next-tick":95}],60:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":81,"global-queue":149,callback:86,"next-tick":95,bind:93,each:4}],61:[function(require,module,exports){var integration=require("analytics.js-integration");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pa").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}},{"analytics.js-integration":81}],62:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":81,"global-queue":149,"load-date":150}],63:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue()||0;each(goals,function(goal){push("trackGoal",goal,revenue)})}},{"analytics.js-integration":81,"global-queue":149,each:4}],64:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_lnq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":81,"convert-dates":155,"global-queue":149,alias:154}],65:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":81,"global-queue":149,facade:121,bind:93,when:120}],66:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var settings={event:"refresh",labels:this.labels("page",category,name),qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var settings={event:"click",labels:this.labels("event",name),qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var labels=this.labels("event",name);var category=track.category();if(this.options.advertise&&category){labels+=","+this.labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype.labels=function(type){var args=[].slice.call(arguments,1);var advertise=this.options.advertise;var ret=[];if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;for(var i=0;i<args.length;++i){if(null==args[i])continue;var value=String(args[i]);ret.push(value.replace(/,/g,";"))}ret=advertise?ret.join(" "):ret.join(".");return[type,ret].join(".")}},{"global-queue":149,"analytics.js-integration":81,"use-https":83}],67:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)
}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":81,extend:119,is:84}],68:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":81}],69:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');Sentry.prototype.initialize=function(){var config=this.options.config;var self=this;this.load(function(){window.Raven.config(config).install();self.ready()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":81,is:84}],70:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":81,is:84}],71:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":81,bind:93,when:120}],72:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":81,slug:91,"global-queue":149}],73:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{};window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":81,alias:154,clone:153}],74:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").option("page","").tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.page=function(page){if(this.options.page){this.load({pixelId:this.options.page})}};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(pixelId){self.load({pixelId:pixelId})})}},{"analytics.js-integration":81,each:4}],75:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":81,"global-queue":149,"convert-dates":155,"to-unix-timestamp":178,alias:154,clone:153}],178:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],76:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}},{"analytics.js-integration":81,"global-queue":149,"component/cookie":179}],179:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}},{}],77:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":81,"next-tick":95,each:4}],78:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":81,"use-https":83}],79:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":81,"to-snake-case":82,"is-email":144,extend:119,each:4,type:7}],80:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).option("clickmap",false).option("webvisor",false).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;var clickmap=this.options.clickmap;var webvisor=this.options.webvisor;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id,clickmap:clickmap,webvisor:webvisor})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":81,"next-tick":95,bind:93,when:120}],3:[function(require,module,exports){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",message(Identify,{options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",message(Group,{options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",message(Track,{properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);properties.url=properties.url||canonicalUrl(properties.search);this._invoke("page",message(Page,{properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",message(Alias,{options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}function message(Type,msg){var ctx=msg.options||{};if(ctx.timestamp||ctx.integrations||ctx.context||ctx.anonymousId){msg=defaults(ctx,msg);delete msg.options}return new Type(msg)}},{after:103,bind:180,callback:86,canonical:157,clone:87,"./cookie":181,debug:182,defaults:89,each:4,emitter:101,"./group":183,is:84,"is-email":144,"is-meta":184,"new-date":136,event:185,prevent:186,querystring:187,object:156,"./store":188,url:159,"./user":189,facade:121}],180:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:93,"bind-all":94}],181:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:182,bind:180,cookie:179,clone:87,defaults:89,json:190,"top-domain":191}],182:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":192,"./debug":193}],192:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m[90m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"[0m";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],193:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false
}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],190:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":194}],194:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],191:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:159}],183:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{debug:182,"./entity":195,inherit:196,bind:180}],195:[function(require,module,exports){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.protocol=window.location.protocol;this.options(options)}Entity.prototype.storage=function(){return"file:"==this.protocol||"chrome-extension:"==this.protocol?store:cookie};Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var storage=this.storage();var ret=this._options.persist?storage.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){var storage=this.storage();if(this._options.persist){storage.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{"isodate-traverse":131,defaults:89,"./cookie":181,"./store":188,extend:119,clone:87}],188:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:180,defaults:89,"store.js":197}],197:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:190}],196:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],184:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],185:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],186:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],187:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:145,type:7}],189:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}};function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{debug:182,"./entity":195,inherit:196,bind:180,"./cookie":181}],5:[function(require,module,exports){module.exports="2.3.26"},{}]},{},{1:"analytics"}); |
lib/pages/actions.js | Kegsay/github-pull-review | import triggers from "../logic/triggers";
import {PullRequestTrigger, FileDiffsTrigger, LineCommentsTrigger} from "../logic/triggers";
var TriggerMixin = require("../logic/triggers").TriggerMixin([
PullRequestTrigger, FileDiffsTrigger, LineCommentsTrigger
]);
var React = require("react");
var CommentBox = require("../components/comment-box");
var CommentView = require("../components/comment-view");
var CommentDiffListView = require("../components/comment-diff-list-view");
var Actions = require("../logic/models/action");
module.exports = React.createClass({displayName: 'ActionsPage',
mixins: [TriggerMixin],
propTypes: {
controller: React.PropTypes.any.isRequired
},
getInitialState: function() {
return {
actions: null,
expanded: {}
};
},
// navigating first mount
componentDidMount: function() {
this._loadDiffs(this.props);
},
// navigating once mounted
componentWillReceiveProps: function(newProps) {
this._loadDiffs(newProps);
},
componentDidUpdate: function() {
if (this.state.actions) {
return;
}
var lineCommentsTrigger = this.getTrigger(LineCommentsTrigger);
if (lineCommentsTrigger && lineCommentsTrigger.comments) {
this.setState({
actions: Actions.fromLineComments(lineCommentsTrigger.comments)
});
}
},
_loadDiffs: function(props) {
// set the pr if we already know it.
var pullRequest = this.props.controller.getPullRequest();
if (pullRequest) {
var prTrigger = new triggers.PullRequestTrigger(pullRequest);
this.setTrigger(prTrigger);
}
var ownerRepo = props.params.owner + "/" + props.params.repo;
var pr = props.params.pr;
this.props.controller.getRequestDiffs(ownerRepo, pr, false);
},
toggleExpand: function(actionId) {
var expanded = this.state.expanded;
if (expanded[actionId] === undefined) {
expanded[actionId] = false;
}
expanded[actionId] = !expanded[actionId];
this.setState({
expanded: expanded
})
},
getActionHeaderJsx: function(action, id) {
var expandText = this.state.expanded[id] ? "Collapse" : "Expand";
return (
<div className="ActionsPage_action_header">
<span className="ActionsPage_action_filepath">
{action.getHeadComment().getFilePath()}
</span>
<button onClick={this.toggleExpand.bind(this, id)}> {expandText} </button>
</div>
);
},
onSubmitLineReply: function(action, text) {
return this.props.controller.postReplyLineComment(
this.getTrigger(PullRequestTrigger).pr, text, action.getHeadComment()
);
},
getActionJsx: function(action, index, isDone) {
var id = isDone ? ("d" + index) : ("n" + index);
var body;
if (this.state.expanded[id]) {
var cmtBox;
if (!isDone) {
cmtBox = (
<CommentBox onSubmit={this.onSubmitLineReply.bind(this, action)} />
);
}
body = (
<div>
<CommentDiffListView
patch={action.getHeadComment().getPatch()}
comments={action.getComments()} />
{cmtBox}
</div>
);
}
else {
body = (
<CommentView key={id} comment={action.getHeadComment()} />
);
}
return (
<div className="ActionsPage_action" key={id}>
{this.getActionHeaderJsx(action, id)}
{body}
</div>
);
},
render: function() {
var self = this;
var pr = this.getTrigger(PullRequestTrigger).pr;
if (!pr || !this.state.actions) {
return <div>Loading pull request...</div>;
}
// var fileDiffs = this.state.file_diffs ? this.state.file_diffs.files : [];
var notDones = this.state.actions.filter(function(a) { return !a.isDone(); });
var dones = this.state.actions.filter(function(a) { return a.isDone(); });
return (
<div>
<h2>Outstanding Line Comments</h2>
{notDones.map(function(action, i) {
return self.getActionJsx(action, i, false);
})}
<h2>Completed Line Comments</h2>
{dones.map(function(action, i) {
return self.getActionJsx(action, i, true);
})}
</div>
);
}
});
|
lib/shared/screens/admin/shared/components/page-builder-menu/tabs/style/style-picker/list/index.js | relax/relax | import * as pageBuilderActions from 'actions/page-builder';
import bind from 'decorators/bind';
import Component from 'components/component';
import React from 'react';
import PropTypes from 'prop-types';
import {removeStyle, saveStyle} from 'actions/styles';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import elements from 'elements';
import filter from 'lodash/filter';
import List from './list';
@connect(
(state) => {
const {selectedElement} = state.pageBuilder;
const ElementClass = selectedElement && elements[selectedElement.tag];
const styleType = typeof ElementClass.style === 'string' ? ElementClass.style : ElementClass.style.type;
let styles = [];
if (state.styles) {
styles = filter(state.styles, (style) => (style.type === styleType));
}
return {
styles,
selected: state.pageBuilder.selected
};
},
(dispatch) => bindActionCreators({...pageBuilderActions, removeStyle, saveStyle}, dispatch)
)
export default class StylePickerListContainer extends Component {
static propTypes = {
styles: PropTypes.array.isRequired,
changeElementStyle: PropTypes.func.isRequired,
removeStyle: PropTypes.func.isRequired,
saveStyle: PropTypes.func.isRequired,
selected: PropTypes.object.isRequired,
selectedStyle: PropTypes.object,
onChange: PropTypes.func.isRequired
};
@bind
changeStyle (styleId) {
const {changeElementStyle, selected, onChange} = this.props;
onChange();
changeElementStyle(selected.id, styleId, selected.context);
}
@bind
duplicateStyle (style) {
const newStyle = Object.assign({}, style);
delete newStyle._id;
newStyle.title = `${newStyle.title} (duplicate)`;
this.props.saveStyle(newStyle);
}
render () {
const {styles, selectedStyle} = this.props;
return (
<List
styles={styles}
removeStyle={this.props.removeStyle}
duplicateStyle={this.duplicateStyle}
changeStyle={this.changeStyle}
currentId={selectedStyle && selectedStyle._id}
/>
);
}
}
|
src/svg-icons/maps/ev-station.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsEvStation = (props) => (
<SvgIcon {...props}>
<path d="M19.77 7.23l.01-.01-3.72-3.72L15 4.56l2.11 2.11c-.94.36-1.61 1.26-1.61 2.33 0 1.38 1.12 2.5 2.5 2.5.36 0 .69-.08 1-.21v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v16h10v-7.5h1.5v5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 18v-4.5H6L10 6v5h2l-4 7z"/>
</SvgIcon>
);
MapsEvStation = pure(MapsEvStation);
MapsEvStation.displayName = 'MapsEvStation';
MapsEvStation.muiName = 'SvgIcon';
export default MapsEvStation;
|
ReactToDo/src/App.js | michaelgichia/TODO-List | import React from 'react';
import NavBar from './components/NavBar';
import ToDo from './containers/ToDo';
export default () => {
return (
<div>
<NavBar />
<div className="row">
<ToDo />
</div>
</div>
)
}
|
src/Map/Layers/Marker.js | woutervh-/cancun-react | import React from 'react';
export default class Marker extends React.Component {
static propTypes = {
position: React.PropTypes.shape({
latitude: React.PropTypes.number.isRequired,
longitude: React.PropTypes.number.isRequired
}).isRequired,
anchor: React.PropTypes.shape({
x: React.PropTypes.number.isRequired,
y: React.PropTypes.number.isRequired
}).isRequired,
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired,
source: React.PropTypes.string.isRequired
};
static defaultProps = {
anchor: {x: 0, y: 0}
};
render() {
return null;
}
};
|
internals/templates/app.js | ajfuller/react-casestudy | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(System.import('intl'));
}))
.then(() => Promise.all([
System.import('intl/locale-data/jsonp/de.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
ajax/libs/babel-core/4.5.2/browser-polyfill.js | cgvarela/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){(function(global){"use strict";if(global._babelPolyfill){throw new Error("only one instance of babel/polyfill is allowed")}global._babelPolyfill=true;require("core-js/shim");require("regenerator-babel/runtime")}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":2,"regenerator-babel/runtime":3}],2:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,RangeError=global.RangeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,parseInt=global.parseInt,isFinite=global.isFinite,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,console=global.console||{},ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return toString.call(it).slice(8,-1)}function classof(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[SYMBOL_TAG])=="string"?T:cof(O)}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,isFrozen=Object.isFrozen,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,pow=Math.pow,abs=Math.abs,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function lz(num){return num>9?num:"0"+num}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SYMBOL_SPECIES=getWellKnownSymbol("species"),SYMBOL_ITERATOR;function setSpecies(C){if(DESC&&(framework||!isNative(C)))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(!framework&&isGlobal&&!isFunction(target[key]))exp=source[key];else if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}if(exports[key]!=out)hidden(exports,key,exp)}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR);var ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);FF_ITERATOR in ArrayProto&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function checkDangerIterClosing(fn){var danger=true;var O={next:function(){throw 1},"return":function(){danger=false}};O[SYMBOL_ITERATOR]=returnThis;try{fn(O)}catch(e){}return danger}function closeIterator(iterator){var ret=iterator["return"];if(ret!==undefined)ret.call(iterator)}function safeIterClose(exec,iterator){try{exec(iterator)}catch(e){closeIterator(iterator);throw e}}function forOf(iterable,entries,fn,that){safeIterClose(function(iterator){var f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false){return closeIterator(iterator)}},getIterator(iterable))}!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description),sym=set(create(Symbol[PROTOTYPE]),TAG,tag);AllSymbols[tag]=sym;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return sym};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR||getWellKnownSymbol(ITERATOR),keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(AllSymbols[key]);return result}});setToStringTag(Math,MATH,true);setToStringTag(global.JSON,"JSON",true)}(safeSymbol("tag"),{},{},true);!function(){var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic)}();!function(tmp){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"})}({});!function(){function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames")}();!function(NAME){NAME in FunctionProto||DESC&&defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}})}("name");Number("0o1")&&Number("0b1")||function(_Number,NumberProto){function toNumber(it){if(isObject(it))it=toPrimitive(it);if(typeof it=="string"&&it.length>2&&it.charCodeAt(0)==48){var binary=false;switch(it.charCodeAt(1)){case 66:case 98:binary=true;case 79:case 111:return parseInt(it.slice(2),binary?2:8)}}return+it}function toPrimitive(it){var fn,val;if(isFunction(fn=it.valueOf)&&!isObject(val=fn.call(it)))return val;if(isFunction(fn=it[TO_STRING])&&!isObject(val=fn.call(it)))return val;throw TypeError("Can't convert object to number")}Number=function Number(it){return this instanceof Number?new _Number(toNumber(it)):toNumber(it)};forEach.call(DESC?getNames(_Number):array("MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY"),function(key){key in Number||defineProperty(Number,key,getOwnDescriptor(_Number,key))});Number[PROTOTYPE]=NumberProto;NumberProto[CONSTRUCTOR]=Number;hidden(global,NUMBER,Number)}(Number,Number[PROTOTYPE]);!function(isInteger){$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})}(Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it});!function(){var E=Math.E,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,sign=Math.sign||function(x){return(x=+x)==0||x!=x?x:x<0?-1:1};function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc})}();!function(fromCharCode){function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})}(String.fromCharCode);!function(){$define(STATIC+FORCED*checkDangerIterClosing(Array.from),ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,step;if(isIterable(O)){result=new(generic(this,Array));safeIterClose(function(iterator){for(;!(step=iterator.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}},getIterator(O))}else{result=new(generic(this,Array))(length=toLength(O.length));for(;length>index;index++){result[index]=mapping?f(O[index],index):O[index]}}result.length=index;return result}});$define(STATIC,ARRAY,{of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});setSpecies(Array)}();!function(){$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});if(framework){forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}}();!function(at){defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)})}(createPointAt(true));DESC&&!function(RegExpProto,_RegExp){if(!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});setSpecies(RegExp)}(RegExp[PROTOTYPE],RegExp);isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(run,0,id)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,RECORD){function isThenable(it){var then;if(isObject(it))then=it.then;return isFunction(then)?then:false}function handledRejectionOrHasOnRejected(promise){var record=promise[RECORD],chain=record.c,i=0,react;if(record.h)return true;while(chain.length>i){react=chain[i++];if(react.fail||handledRejectionOrHasOnRejected(react.P))return true}}function notify(record,reject){var chain=record.c;if(reject||chain.length)asap(function(){var promise=record.p,value=record.v,ok=record.s==1,i=0;if(reject&&!handledRejectionOrHasOnRejected(promise)){setTimeout(function(){if(!handledRejectionOrHasOnRejected(promise)){if(NODE){if(!process.emit("unhandledRejection",value,promise)){}}else if(isFunction(console.error)){console.error("Unhandled promise rejection",value)}}},1e3)}else while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){if(!ok)record.h=true;ret=cb===true?value:cb(value);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(value)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(value){var record=this,then,wrapper;if(record.d)return;record.d=true;record=record.r||record;try{if(then=isThenable(value)){wrapper={r:record,d:false};then.call(value,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{record.v=value;record.s=1;notify(record)}}catch(err){reject.call(wrapper||{r:record,d:false},err)}}function reject(value){var record=this;if(record.d)return;record.d=true;record=record.r||record;record.v=value;record.s=2;notify(record,true)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var record={p:this,c:[],s:0,d:false,v:undefined,h:false};hidden(this,RECORD,record);try{executor(ctx(resolve,record,1),ctx(reject,record,1))}catch(err){reject.call(record,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),record=this[RECORD];record.c.push(react);record.s&¬ify(record);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&RECORD in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("record"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),O1=safeSymbol("O1"),WEAK=safeSymbol("weak"),LEAK=safeSymbol("leak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0,tmp={};function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];if(framework)proto[key]=function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result}}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,FOR_EACH)&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,O1,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||!DESC||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(checkDangerIterClosing(function(O){new C(O)})){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto;if(framework)proto[CONSTRUCTOR]=C}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return iterResult(1)}if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(isFrozen(it))return"F";if(!has(it,UID)){if(!create)return"E";hidden(it,UID,++uid)}return"O"+it[UID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}function def(that,key,value){var entry=getEntry(that,key),prev,index;if(entry)entry.v=value;else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!="F")that[O1][index]=entry}return that}var collectionMethods={clear:function(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){
entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return!!getEntry(this,key)}};Map=getCollection(Map,MAP,{get:function(key){var entry=getEntry(this,key);return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function defWeak(that,key,value){if(isFrozen(assertObject(key)))leakStore(that).set(key,value);else{has(key,WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value}return that}function leakStore(that){return that[LEAK]||hidden(that,LEAK,new Map)[LEAK]}var weakMethods={"delete":function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this)["delete"](key);return has(key,WEAK)&&has(key[WEAK],this[UID])&&delete key[WEAK][this[UID]]},has:function(key){if(!isObject(key))return false;if(isFrozen(key))return leakStore(this).has(key);return has(key,WEAK)&&has(key[WEAK],this[UID])}};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)){if(isFrozen(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[UID]]}},set:function(key,value){return defWeak(this,key,value)}},weakMethods,true,true);if(framework&&(new WeakMap).set(Object.freeze(tmp),7).get(tmp)!=7){forEach.call(array("delete,has,get,set"),function(key){var method=WeakMap[PROTOTYPE][key];WeakMap[PROTOTYPE][key]=function(a,b){if(isObject(a)&&isFrozen(a)){var result=leakStore(this)[key](a,b);return key=="set"?this:result}return method.call(this,a,b)}})}WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return defWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=getOwnDescriptor(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getPrototypeOf(target))){return reflectSet(proto,propertyKey,V,receiver)}ownDesc=descriptor(0)}if(has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=getOwnDescriptor(receiver,propertyKey)||descriptor(0);existingDescriptor.value=V;return defineProperty(receiver,propertyKey,existingDescriptor),true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:function(target,argumentsList){var proto=assertFunction(arguments.length<3?target:arguments[2])[PROTOTYPE],instance=create(isObject(proto)?proto:ObjectProto),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance},defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{getOwnPropertyDescriptors:function(object){var O=toObject(object),result={};forEach.call(ownKeys(O),function(key){defineProperty(result,key,descriptor(0,getOwnDescriptor(O,key)))});return result},values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList)}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),true)},{}],3:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){return new Generator(innerFn,outerFn,self||null,tryLocsList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryLocsList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryLocsList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryLocsList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryLocsList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}if(finallyEntry&&(type==="break"||type==="continue")&&finallyEntry.tryLoc<=arg&&arg<finallyEntry.finallyLoc){finallyEntry=null}var record=finallyEntry?finallyEntry.completion:{};record.type=type;record.arg=arg;if(finallyEntry){this.next=finallyEntry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}return ContinueSentinel},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc){return this.complete(entry.completion,entry.afterLoc)}}},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}]},{},[1]); |
ajax/libs/backbone.radio/0.2.0/backbone.radio.js | CrossEye/cdnjs | // Backbone.Radio v0.1.0
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], function(Backbone, _) {
return factory(Backbone, _);
});
}
else if (typeof exports !== 'undefined') {
var Backbone = require('backbone');
var _ = require('underscore');
module.exports = factory(Backbone, _);
}
else {
factory(root.Backbone, root._);
}
}(this, function(Backbone, _) {
'use strict';
var previousRadio = Backbone.Radio;
var Radio = Backbone.Radio = {};
Radio.VERSION = '0.1.0';
Radio.noConflict = function () {
Backbone.Radio = previousRadio;
return this;
};
/*
* Backbone.Radio
* --------------
* The 'top-level' API for working with Backbone.Radio
*
*/
_.extend(Radio, {
_channels: {},
DEBUG: false,
channel: function(channelName) {
if (!channelName) {
throw new Error('You must provide a name for the channel.');
}
return Radio._getChannel( channelName );
},
_getChannel: function(channelName) {
var channel = Radio._channels[channelName];
if(!channel) {
channel = new Radio.Channel(channelName);
Radio._channels[channelName] = channel;
}
return channel;
}
});
/*
* tune-in
* -------
* Get console logs of a channel's activity
*
*/
// Log information about the channel and event
var _log = function(channelName, eventName) {
var args = Array.prototype.slice.call(arguments, 2);
console.log('[' + channelName + '] "'+eventName+'"', args);
};
var _logs = {};
// This is to produce an identical function in both tuneIn and tuneOut,
// so that Backbone.Events unregisters it.
var _partial = function(channelName) {
return _logs[channelName] || (_logs[channelName] = _.partial(_log, channelName));
};
_.extend(Radio, {
// Logs all events on this channel to the console. It sets an
// internal value on the channel telling it we're listening,
// then sets a listener on the Backbone.Events
tuneIn: function(channelName) {
var channel = Radio.channel(channelName);
channel._tunedIn = true;
channel.on('all', _partial(channelName));
},
// Stop logging all of the activities on this channel to the console
tuneOut: function(channelName) {
var channel = Radio.channel(channelName);
channel._tunedIn = false;
channel.off('all', _partial(channelName));
delete _logs[channelName];
}
});
/*
* Backbone.Radio.Commands
* -----------------------
* A messaging system for sending orders.
*
*/
Radio.Commands = {
command: function(name) {
var args = Array.prototype.slice.call(arguments, 1);
var isChannel = this._channelName ? true : false;
// Check if we should log the request, and if so, do it
if (isChannel && this._tunedIn) {
_log.apply(this, [this._channelName, name].concat(args));
}
// If the command isn't handled, log it in DEBUG mode and exit
if (!this._commands || !this._commands[name]) {
if (Radio.DEBUG) {
var channelText = isChannel ? ' on the ' + this._channelName + ' channel' : '';
console.warn('An unhandled event was fired' + channelText + ': "' + name + '"');
}
return;
}
var handler = this._commands[name];
var cb = handler.callback;
var context = handler.context;
cb.apply(context, args);
},
react: function(name, callback, context) {
if (!this._commands) {
this._commands = {};
}
context = context || this;
this._commands[name] = {
callback: callback,
context: context
};
return this;
},
reactOnce: function(name, callback, context) {
var self = this;
var once = _.once(function() {
self.stopReacting(name);
return callback.apply(this, arguments);
});
return this.command(name, once, context);
},
stopReacting: function(name) {
if (!name) {
delete this._commands;
} else {
delete this._commands[name];
}
}
};
/*
* Backbone.Radio.Requests
* -----------------------
* A messaging system for requesting data.
*
*/
Radio.Requests = {
request: function(name) {
var args = Array.prototype.slice.call(arguments, 1);
var isChannel = this._channelName ? true : false;
// Check if we should log the request, and if so, do it
if (isChannel && this._tunedIn) {
_log.apply(this, [this._channelName, name].concat(args));
}
// If the request isn't handled, log it in DEBUG mode and exit
if (!this._requests || !this._requests[name]) {
if (Radio.DEBUG) {
var channelText = isChannel ? ' on the ' + this._channelName + ' channel' : '';
console.warn('An unhandled event was fired' + channelText + ': "' + name + '"');
}
return;
}
var handler = this._requests[name];
var cb = handler.callback;
var context = handler.context;
return cb.apply(context, args);
},
respond: function(name, callback, context) {
if (!this._requests) {
this._requests = {};
}
context = context || this;
callback = _.isFunction(callback) ? callback : _.constant(callback);
this._requests[name] = {
callback: callback,
context: context
};
return this;
},
respondOnce: function(name, callback, context) {
var self = this;
callback = _.isFunction(callback) ? callback : _.constant(callback);
var once = _.once(function() {
self.stopResponding(name);
return callback.apply(this, arguments);
});
return this.request(name, once, context);
},
stopResponding: function(name) {
if (!name) {
delete this._requests;
} else {
delete this._requests[name];
}
}
};
/*
* Backbone.Radio.Channel
* ----------------------
* A Channel is an object that extends from Backbone.Events,
* Radio.Commands, and Radio.Requests.
*
*/
Radio.Channel = function(channelName) {
this._channelName = channelName;
_.extend(this, Backbone.Events, Radio.Commands, Radio.Requests);
};
_.extend(Radio.Channel.prototype, {
// Remove all handlers from the messaging systems of this channel
reset: function() {
this.off();
this.stopListening();
this.stopReacting();
this.stopResponding();
return this;
}
});
function _connect(methodName, hash, context) {
if ( !hash ) { return; }
context = context || this;
_.each(hash, function(fn, eventName) {
this[methodName](eventName, _.bind(fn, context));
}, this);
}
var map = {
Events: 'on',
Commands: 'react',
Requests: 'respond'
};
_.each(map, function(methodName, systemName) {
var connectName = 'connect'+ systemName;
Radio.Channel.prototype[connectName] = _.partial(_connect, methodName);
});
/*
* proxy
* -----
* Supplies a top-level API.
*
*/
var channel, args, systems = [Backbone.Events, Radio.Commands, Radio.Requests];
_.each(systems, function(system) {
_.each(system, function(method, methodName) {
Radio[methodName] = function(channelName) {
args = Array.prototype.slice.call(arguments, 2);
channel = this.channel(channelName);
return channel[methodName].apply(this, args);
};
});
});
return Radio;
}));
|
src/components/LeftSidebar.js | Benguino/star-wars-project | import React from 'react';
import PropTypes from 'prop-types';
export const LeftSidebar = (props) => {
return (
<div className='col-lg-2 col-sm-4' id='left-sidebar'>
{props.children}
</div>
);
};
LeftSidebar.propTypes = {
children: PropTypes.any.isRequired
}; |
app/components/layout/Navigation/MyBuilds/index.js | fotinakis/buildkite-frontend | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
import classNames from 'classnames';
import { hour, seconds } from 'metrick/duration';
import PusherStore from '../../../../stores/PusherStore';
import Button from '../../../shared/Button';
import Spinner from '../../../shared/Spinner';
import Dropdown from '../../../shared/Dropdown';
import Icon from '../../../shared/Icon';
import Badge from '../../../shared/Badge';
import CachedStateWrapper from '../../../../lib/CachedStateWrapper';
import Build from './build';
import DropdownButton from './../dropdown-button';
class MyBuilds extends React.Component {
static propTypes = {
viewer: PropTypes.object,
relay: PropTypes.object.isRequired
}
state = {
isDropdownVisible: false,
scheduledBuildsCount: this.props.viewer.scheduledBuilds ? this.props.viewer.scheduledBuilds.count : 0,
runningBuildsCount: this.props.viewer.runningBuilds ? this.props.viewer.runningBuilds.count : 0
}
// When the MyBuilds mounts, we should see if we've got any cached
// builds numbers so we can show something right away.
componentWillMount() {
const initialState = {};
const cachedState = this.getCachedState();
if (!this.props.viewer.scheduledBuilds) {
initialState.scheduledBuildsCount = cachedState.scheduledBuildsCount || 0;
}
if (!this.props.viewer.runningBuilds) {
initialState.runningBuildsCount = cachedState.runningBuildsCount || 0;
}
this.setState(initialState);
}
componentDidMount() {
PusherStore.on("user_stats:change", this.handlePusherWebsocketEvent);
// Now that "My Builds" has been mounted on the page and Pusher has
// connected, we should force a refetch of the latest `scheduledBuilds` and
// `runningBuilds` counts from GraphQL.
PusherStore.on("connected", this.handlePusherConnected);
// If pusher doesn't connect in 3 seconds, just force the callback
// manually. This can happen if Pusher is being a bit weird, or when
// Pusher isn't connected at all (like in the case of automated tests)
setTimeout(this.handlePusherConnected, 3::seconds);
}
componentWillUnmount() {
PusherStore.off("user_stats:change", this.handlePusherWebsocketEvent);
PusherStore.off("connected", this.handlePusherConnected);
}
// As we get new values for scheduledBuildsCount and runningBuildsCount from
// Relay + GraphQL, we'll be sure to update the cached state with the latest
// values so when the page re-loads, we can show the latest numbers.
componentWillReceiveProps(nextProps) {
if (nextProps.viewer.scheduledBuilds || nextProps.viewer.runningBuilds) {
this.setCachedState({
scheduledBuildsCount: nextProps.viewer.scheduledBuilds.count,
runningBuildsCount: nextProps.viewer.runningBuilds.count
});
}
}
render() {
return (
<Dropdown width={320} className="flex ml-auto" onToggle={this.handleDropdownToggle}>
<DropdownButton className={classNames("flex-none py0", { "lime": this.state.isDropdownVisible })} onMouseEnter={this.handleButtonMouseEnter}>
{'My Builds '}
<div className="xs-hide">
<CSSTransitionGroup transitionName="transition-appear-pop" transitionEnterTimeout={200} transitionLeaveTimeout={200}>
{this.renderBadge()}
</CSSTransitionGroup>
</div>
<Icon
icon="down-triangle"
className="flex-none"
style={{
width: 7,
height: 7,
marginLeft: '.5em'
}}
/>
</DropdownButton>
{this.renderDropdown()}
</Dropdown>
);
}
renderBadge() {
const buildsCount = this.state.runningBuildsCount + this.state.scheduledBuildsCount;
// Only render the badge if we've actually got a number to show
if (buildsCount) {
return (
<Badge className={classNames("hover-lime-child", { "bg-lime": this.state.isDropdownVisible })}>
{buildsCount}
</Badge>
);
}
}
renderDropdown() {
// If `builds` here is null, that means that Relay hasn't fetched the data
// for it yet. It will become an Array once it's loaded.
if (!this.props.viewer.user.builds) {
return this.renderSpinner();
}
// Once we've got an array of builds, we either show what we have, or the
// setup instructions.
if (this.props.viewer.user.builds.edges.length > 0) {
return this.renderBuilds();
}
return this.renderSetupInstructions();
}
renderBuilds() {
return (
<div>
<div className="px3 py2">
{this.props.viewer.user.builds.edges.map((edge) => <Build key={edge.node.id} build={edge.node} />)}
</div>
<div className="pb2 px3">
<Button href="/builds" theme="default" outline={true} className="center" style={{ width: "100%" }}>More Builds</Button>
</div>
</div>
);
}
renderSetupInstructions() {
return (
<div className="px3 py2">
<div className="mb2">To have your builds appear here, make sure that your commit email address (e.g. <code className="border border-gray dark-gray" style={{ padding: '.1em .3em' }}>git config user.email</code>) is added and verified in your list of personal email addresses.</div>
<Button href="/user/emails" theme="default" outline={true} className="center" style={{ width: "100%" }}>Update Email Addresses</Button>
</div>
);
}
renderSpinner() {
return (
<div className="px3 py2 center">
<Spinner />
</div>
);
}
handleDropdownToggle = (visible) => {
// If `includeBuilds` hasn't been set to `true` yet (perhaps the mouseEnter
// event never got triggered because we're on a mobile device) trigger a
// load of the builds as the dropdown opens.
if (!this.props.relay.variables.includeBuilds) {
this.props.relay.forceFetch({ includeBuilds: true });
}
this.setState({ isDropdownVisible: visible });
};
handlePusherConnected = () => {
if (!this.props.relay.variables.includeBuildCounts) {
this.props.relay.forceFetch({ includeBuildCounts: true });
}
};
// If the user is hovering over the "My Builds" button, be sneaky and start
// loading the build data in the background.
handleButtonMouseEnter = () => {
if (!this.props.relay.variables.includeBuilds) {
this.props.relay.forceFetch({ includeBuilds: true });
}
};
// When we recieve a Pusher event, check to see if the build counts have
// changed (meaning a new build has probably started or finished). In that
// case, we'll perform a full refersh of the My Builds data (including new
// numbers for the nav and the builds themselves).
//
// We don't use the data from the payload otherwise the UI would update, and
// then the builds would update a few moments later when the GraphQL query
// finishes, which would be a bit weird.
handlePusherWebsocketEvent = (payload) => {
const scheduledBuildsCountChanged = this.state.scheduledBuildsCount !== payload.scheduledBuildsCount;
const runningBuildsCountChanged = this.state.runningBuildsCount !== payload.runningBuildsCount;
if (scheduledBuildsCountChanged || runningBuildsCountChanged) {
this.props.relay.forceFetch();
}
};
}
// Wrap the MyBuilds in a CachedStateWrapper so we get access to methods
// like `setCachedState`
const CachedMyBuilds = CachedStateWrapper(MyBuilds, { validLength: 1::hour });
export default Relay.createContainer(CachedMyBuilds, {
initialVariables: {
includeBuilds: false,
includeBuildCounts: false
},
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
user {
builds(first: 5) @include(if: $includeBuilds) {
edges {
node {
id
${Build.getFragment('build')}
}
}
}
}
runningBuilds: builds(state: RUNNING) @include(if: $includeBuildCounts) {
count
}
scheduledBuilds: builds(state: SCHEDULED) @include(if: $includeBuildCounts) {
count
}
}
`
}
});
|
frontend/test/app/components/NewsletterFooter-test.js | mathjazz/testpilot | import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import NewsletterFooter from '../../../src/app/components/NewsletterFooter';
describe('app/components/NewsletterFooter', () => {
const _subject = (form) => {
const props = {
newsletterForm: {
subscribe: sinon.spy(),
setEmail: sinon.spy(),
setPrivacy: sinon.spy(),
...form
}
};
return shallow(<NewsletterFooter {...props} />);
};
describe('error notification', () => {
it('should not show when failed=false', () => {
const subject = _subject({ failed: false });
expect(subject.find('.error')).to.have.length(0);
});
it('should show when failed=true', () => {
const subject = _subject({ failed: true });
expect(subject.find('.error')).to.have.length(1);
});
});
describe('header', () => {
it('should render when succeeded=false', () => {
const subject = _subject({ succeeded: false }).find('header');
expect(subject.hasClass('success-header')).to.equal(false);
});
it('should be replaced with a success message when succeeded=true', () => {
const subject = _subject({ succeeded: true }).find('header');
expect(subject.hasClass('success-header')).to.equal(true);
});
});
it('should not have the `correct` class by default', () => {
const subject = _subject({ succeeded: false });
expect(subject.hasClass('success')).to.equal(false);
});
it('should have `correct` class when succeeded=true', () => {
const subject = _subject({ succeeded: true });
expect(subject.hasClass('success')).to.equal(true);
});
it('should pass props to the child NewsletterForm', () => {
const subject = _subject({ foo: 'bar' });
expect(subject.find('NewsletterForm').prop('foo')).to.equal('bar');
});
});
|
src/layout/components/sidebar.js | knledg/react-webpack-skeleton | import _ from 'lodash';
import React from 'react';
import { Link } from 'react-router';
export class Sidebar extends React.Component {
static propTypes = {
location: React.PropTypes.shape({
pathname: React.PropTypes.string.isRequired,
query: React.PropTypes.object.isRequired,
}),
}
state = {
navItems: [
{ pathname: '/', label: 'Home', icon: 'home' },
{ pathname: '/about', label: 'About', icon: 'info' },
{ pathname: '/table-demo', label: 'Tables', icon: 'table' },
{ pathname: '/button-demo', label: 'Buttons', icon: 'dot-circle-o' },
{ pathname: '/progress-bars', label: 'Progress Bars', icon: 'spinner'},
{ pathname: '/modal-demo', label: 'Modals', icon: 'clipboard' },
{ pathname: '/tabs-demo', label: 'Tabs', icon: 'list-ul' },
{ pathname: '/input-demo', label: 'Inputs', icon: 'check-square' },
{ pathname: '/notifications-demo', label: 'Notifications', icon: 'exclamation' },
],
}
isSelected(navItem) {
return this.props.location.pathname === navItem.pathname ? 'selected' : '';
}
renderLinks() {
return _.map(this.state.navItems, (navItem) => {
return (
<li className={`al-sidebar-list-item ${this.isSelected(navItem)}`} key={navItem.pathname}>
<Link className="al-sidebar-list-link" to={{ pathname: navItem.pathname, query: navItem.query }}>
<i className={`fa fa-${navItem.icon}`}></i>
<span>{navItem.label}</span>
</Link>
</li>
);
});
}
render() {
// navitems selected, with-sub-menu
// links - hover
/*
<ul ng-if="item.subMenu" className="al-sidebar-sublist"
ng-className="{expanded: item.expanded, 'slide-right': item.slideRight}">
<li ng-repeat="subitem in item.subMenu" ng-className="{'selected': subitem.selected, 'with-sub-menu': subitem.subMenu}">
<a ng-mouseenter="hoverItem($event, item)" ng-if="subitem.subMenu" href ng-click="toggleSubMenu($event, subitem);"
className="al-sidebar-list-link subitem-submenu-link"><span>{{ subitem.title }}</span>
<b className="fa" ng-className="{'fa-angle-up': subitem.expanded, 'fa-angle-down': !subitem.expanded}"
ng-if="subitem.subMenu"></b>
</a>
<ul ng-if="subitem.subMenu" className="al-sidebar-sublist subitem-submenu-list"
ng-className="{expanded: subitem.expanded, 'slide-right': subitem.slideRight}">
<li ng-mouseenter="hoverItem($event, item)" ng-repeat="subSubitem in subitem.subMenu" ng-className="{selected: subitem.selected}">
<a ng-mouseenter="hoverItem($event, item)" href="{{ subSubitem.root }}">{{
subSubitem.title }}</a>
</li>
</ul>
<a ng-mouseenter="hoverItem($event, item)" target="{{subitem.blank ? '_blank' : '_self'}}" ng-if="!subitem.subMenu" href="{{ subitem.root }}">{{ subitem.title}}</a>
</li>
</ul>
*/
/*
<div className="sidebar-hover-elem" ng-style="{top: hoverElemTop + 'px', height: hoverElemHeight + 'px'}"
ng-className="{'show-hover-elem': showHoverElem }"></div>
*/
// ul - slimscroll="{height: '{{menuHeight}}px'}" slimscroll-watch="menuHeight"
return (
<aside className="al-sidebar" ng-swipe-right="menuExpand()" ng-swipe-left="menuCollapse()"
ng-mouseleave="hoverElemTop=selectElemTop">
<ul className="al-sidebar-list">
{this.renderLinks()}
</ul>
</aside>
);
}
}
|
src/scripts/VideoImage.js | lmacsen/yoda | 'use strict';
import React from 'react';
import Join from 'react/lib/joinClasses';
import VideoDuration from './VideoDuration';
export default React.createClass({
componentDidMount() {
var imgTag = React.findDOMNode(this.refs.image);
var imgSrc = imgTag.getAttribute('src');
var img = new window.Image();
img.src = imgSrc;
},
shouldComponentUpdate(nextProps) {
return this.props.src !== nextProps.src;
},
render() {
var imgClasses = 'video-thumbnail image-thumbnail';
return (
<img ref="image" className={imgClasses} {...this.props} />
);
}
});
|
wrappers/json.js | lukevance/personal_site | import React from 'react'
module.exports = React.createClass({
propTypes () {
return {
route: React.PropTypes.object,
}
},
render () {
const data = this.props.route.page.data
return (
<div>
<h1>{data.title}</h1>
<p>Raw view of json file</p>
<pre dangerouslySetInnerHTML={{ __html: JSON.stringify(data, null, 4) }} />
</div>
)
},
})
|
ajax/libs/handsontable/0.11.0-beta1/jquery.handsontable.full.js | danut007ro/cdnjs | /**
* Handsontable 0.11.0-beta1
* Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs
*
* Copyright 2012-2014 Marcin Warpechowski
* Licensed under the MIT license.
* http://handsontable.com/
*
* Date: Thu Jul 10 2014 13:20:50 GMT+0200 (CEST)
*/
/*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */
var Handsontable = { //class namespace
plugins: {}, //plugin namespace
helper: {} //helper namespace
};
(function ($, window, Handsontable) {
"use strict";
//http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-ie8
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
/**
* Array.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications
*/
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun, thisp) {
"use strict";
if (typeof this === "undefined" || this === null) {
throw new TypeError();
}
if (typeof fun !== "function") {
throw new TypeError();
}
thisp = thisp || this;
if (isNodeList(thisp)) {
thisp = convertNodeListToArray(thisp);
}
var len = thisp.length,
res = [],
i,
val;
for (i = 0; i < len; i += 1) {
if (thisp.hasOwnProperty(i)) {
val = thisp[i]; // in case fun mutates this
if (fun.call(thisp, val, i, thisp)) {
res.push(val);
}
}
}
return res;
function isNodeList(object) {
return /NodeList/i.test(object.item);
}
function convertNodeListToArray(nodeList) {
var array = [];
for (var i = 0, len = nodeList.length; i < len; i++){
array[i] = nodeList[i]
}
return array;
}
};
}
/*
* Copyright 2012 The Polymer Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
if (typeof WeakMap === 'undefined') {
(function() {
var defineProperty = Object.defineProperty;
try {
var properDefineProperty = true;
defineProperty(function(){}, 'foo', {});
} catch (e) {
properDefineProperty = false;
}
/*
IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does.
M$ deserves a high five for this one :)
*/
var counter = +(new Date) % 1e9;
var WeakMap = function() {
this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__');
if(!properDefineProperty){
this._wmCache = [];
}
};
if(properDefineProperty){
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key)
entry[1] = value;
else
defineProperty(key, this.name, {value: [key, value], writable: true});
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ?
entry[1] : undefined;
},
'delete': function(key) {
this.set(key, undefined);
}
};
} else {
WeakMap.prototype = {
set: function(key, value) {
if(typeof key == 'undefined' || typeof value == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
this._wmCache[i].value = value;
return;
}
}
this._wmCache.push({key: key, value: value});
},
get: function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
return this._wmCache[i].value;
}
}
return;
},
'delete': function(key) {
if(typeof key == 'undefined') return;
for(var i = 0, len = this._wmCache.length; i < len; i++){
if(this._wmCache[i].key == key){
Array.prototype.slice.call(this._wmCache, i, 1);
}
}
}
};
}
window.WeakMap = WeakMap;
})();
}
Handsontable.activeGuid = null;
/**
* Handsontable constructor
* @param rootElement The jQuery element in which Handsontable DOM will be inserted
* @param userSettings
* @constructor
*/
Handsontable.Core = function (rootElement, userSettings) {
var priv
, datamap
, grid
, selection
, editorManager
, autofill
, instance = this
, GridSettings = function () {};
Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings
Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings
Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings));
this.rootElement = rootElement;
this.container = document.createElement('DIV');
this.container.className = 'htContainer';
rootElement.prepend(this.container);
this.container = $(this.container);
var $document = $(document.documentElement);
var $body = $(document.body);
this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events
if (!this.rootElement[0].id) {
this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id
}
priv = {
cellSettings: [],
columnSettings: [],
columnsSettingConflicts: ['data', 'width'],
settings: new GridSettings(), // current settings instance
selRange: null, //exposed by public method `getSelectedRange`
isPopulated: null,
scrollable: null,
firstRun: true
};
grid = {
/**
* Inserts or removes rows and columns
* @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col"
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
*/
alter: function (action, index, amount, source, keepEmptyRows) {
var delta;
amount = amount || 1;
switch (action) {
case "insert_row":
delta = datamap.createRow(index, amount);
if (delta) {
if (selection.isSelected() && priv.selRange.from.row >= index) {
priv.selRange.from.row = priv.selRange.from.row + delta;
selection.transformEnd(delta, 0); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "insert_col":
delta = datamap.createCol(index, amount);
if (delta) {
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
var spliceArray = [index, 0];
spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array
}
if (selection.isSelected() && priv.selRange.from.col >= index) {
priv.selRange.from.col = priv.selRange.from.col + delta;
selection.transformEnd(0, delta); //will call render() internally
}
else {
selection.refreshBorders(); //it will call render and prepare methods
}
}
break;
case "remove_row":
datamap.removeRow(index, amount);
priv.cellSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
case "remove_col":
datamap.removeCol(index, amount);
for(var row = 0, len = datamap.getAll().length; row < len; row++){
if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings
priv.cellSettings[row].splice(index, amount);
}
}
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
if(typeof index == 'undefined'){
index = -1;
}
instance.getSettings().colHeaders.splice(index, amount);
}
priv.columnSettings.splice(index, amount);
grid.adjustRowsAndCols();
selection.refreshBorders(); //it will call render and prepare methods
break;
default:
throw new Error('There is no such action "' + action + '"');
break;
}
if (!keepEmptyRows) {
grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh
}
},
/**
* Makes sure there are empty rows at the bottom of the table
*/
adjustRowsAndCols: function () {
var r, rlen, emptyRows, emptyCols;
//should I add empty rows to data source to meet minRows?
rlen = instance.countRows();
if (rlen < priv.settings.minRows) {
for (r = 0; r < priv.settings.minRows - rlen; r++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
emptyRows = instance.countEmptyRows(true);
//should I add empty rows to meet minSpareRows?
if (emptyRows < priv.settings.minSpareRows) {
for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) {
datamap.createRow(instance.countRows(), 1, true);
}
}
//count currently empty cols
emptyCols = instance.countEmptyCols(true);
//should I add empty cols to meet minCols?
if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) {
for (; instance.countCols() < priv.settings.minCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
//should I add empty cols to meet minSpareCols?
if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) {
for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) {
datamap.createCol(instance.countCols(), 1, true);
}
}
// if (priv.settings.enterBeginsEditing) {
// for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) {
// datamap.removeRow();
// }
// }
// if (priv.settings.enterBeginsEditing && !priv.settings.columns) {
// for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) {
// datamap.removeCol();
// }
// }
var rowCount = instance.countRows();
var colCount = instance.countCols();
if (rowCount === 0 || colCount === 0) {
selection.deselect();
}
if (selection.isSelected()) {
var selectionChanged;
var fromRow = priv.selRange.from.row;
var fromCol = priv.selRange.from.col;
var toRow = priv.selRange.to.row;
var toCol = priv.selRange.to.col;
//if selection is outside, move selection to last row
if (fromRow > rowCount - 1) {
fromRow = rowCount - 1;
selectionChanged = true;
if (toRow > fromRow) {
toRow = fromRow;
}
} else if (toRow > rowCount - 1) {
toRow = rowCount - 1;
selectionChanged = true;
if (fromRow > toRow) {
fromRow = toRow;
}
}
//if selection is outside, move selection to last row
if (fromCol > colCount - 1) {
fromCol = colCount - 1;
selectionChanged = true;
if (toCol > fromCol) {
toCol = fromCol;
}
} else if (toCol > colCount - 1) {
toCol = colCount - 1;
selectionChanged = true;
if (fromCol > toCol) {
fromCol = toCol;
}
}
if (selectionChanged) {
instance.selectCell(fromRow, fromCol, toRow, toCol);
}
}
},
/**
* Populate cells at position with 2d array
* @param {Object} start Start selection position
* @param {Array} input 2d array
* @param {Object} [end] End selection position (only for drag-down mode)
* @param {String} [source="populateFromArray"]
* @param {String} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
populateFromArray: function (start, input, end, source, method) {
var r, rlen, c, clen, setData = [], current = {};
rlen = input.length;
if (rlen === 0) {
return false;
}
var repeatCol
, repeatRow
, cmax
, rmax;
// insert data with specified pasteMode method
switch (method) {
case 'shift_down' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
input = Handsontable.helper.translateRowsToColumns(input);
for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) {
if (c < clen) {
for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) {
input[c].push(input[c][r % rlen]);
}
input[c].unshift(start.col + c, start.row, 0);
instance.spliceCol.apply(instance, input[c]);
}
else {
input[c % clen][0] = start.col + c;
instance.spliceCol.apply(instance, input[c % clen]);
}
}
break;
case 'shift_right' :
repeatCol = end ? end.col - start.col + 1 : 0;
repeatRow = end ? end.row - start.row + 1 : 0;
for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) {
if (r < rlen) {
for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) {
input[r].push(input[r][c % clen]);
}
input[r].unshift(start.row + r, start.col, 0);
instance.spliceRow.apply(instance, input[r]);
}
else {
input[r % rlen][0] = start.row + r;
instance.spliceRow.apply(instance, input[r % rlen]);
}
}
break;
case 'overwrite' :
default:
// overwrite and other not specified options
current.row = start.row;
current.col = start.col;
for (r = 0; r < rlen; r++) {
if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) {
break;
}
current.col = start.col;
clen = input[r] ? input[r].length : 0;
for (c = 0; c < clen; c++) {
if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) {
break;
}
if (!instance.getCellMeta(current.row, current.col).readOnly) {
setData.push([current.row, current.col, input[r][c]]);
}
current.col++;
if (end && c === clen - 1) {
c = -1;
}
}
current.row++;
if (end && r === rlen - 1) {
r = -1;
}
}
instance.setDataAtCell(setData, null, null, source || 'populateFromArray');
break;
}
}
};
this.selection = selection = { //this public assignment is only temporary
inProgress: false,
/**
* Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired
*/
begin: function () {
instance.selection.inProgress = true;
},
/**
* Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp
*/
finish: function () {
var sel = instance.getSelected();
Handsontable.hooks.run(instance, "afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]);
Handsontable.hooks.run(instance, "afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3]));
instance.selection.inProgress = false;
},
isInProgress: function () {
return instance.selection.inProgress;
},
/**
* Starts selection range on given td object
* @param {WalkontableCellCoords} coords
*/
setRangeStart: function (coords) {
Handsontable.hooks.run(instance, "beforeSetRangeStart", coords);
priv.selRange = new WalkontableCellRange(coords, coords, coords);
selection.setRangeEnd(coords);
},
/**
* Ends selection range on given td object
* @param {WalkontableCellCoords} coords
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end
*/
setRangeEnd: function (coords, scrollToCell) {
//trigger handlers
Handsontable.hooks.run(instance, "beforeSetRangeEnd", coords);
instance.selection.begin();
priv.selRange.to = coords;
if (!priv.settings.multiSelect) {
priv.selRange.from = coords;
}
//set up current selection
instance.view.wt.selections.current.clear();
instance.view.wt.selections.current.add(priv.selRange.highlight);
//set up area selection
instance.view.wt.selections.area.clear();
if (selection.isMultiple()) {
instance.view.wt.selections.area.add(priv.selRange.from);
instance.view.wt.selections.area.add(priv.selRange.to);
}
//set up highlight
if (priv.settings.currentRowClassName || priv.settings.currentColClassName) {
instance.view.wt.selections.highlight.clear();
instance.view.wt.selections.highlight.add(priv.selRange.from);
instance.view.wt.selections.highlight.add(priv.selRange.to);
}
//trigger handlers
Handsontable.hooks.run(instance, "afterSelection", priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col);
Handsontable.hooks.run(instance, "afterSelectionByProp", priv.selRange.from.row, datamap.colToProp(priv.selRange.from.col), priv.selRange.to.row, datamap.colToProp(priv.selRange.to.col));
if (scrollToCell !== false && instance.view.mainViewIsActive()) {
instance.view.scrollViewport(coords);
}
selection.refreshBorders();
},
/**
* Destroys editor, redraws borders around cells, prepares editor
* @param {Boolean} revertOriginal
* @param {Boolean} keepEditor
*/
refreshBorders: function (revertOriginal, keepEditor) {
if (!keepEditor) {
editorManager.destroyEditor(revertOriginal);
}
instance.view.render();
if (selection.isSelected() && !keepEditor) {
editorManager.prepareEditor();
}
},
/**
* Returns information if we have a multiselection
* @return {Boolean}
*/
isMultiple: function () {
return !(priv.selRange.to.col === priv.selRange.from.col && priv.selRange.to.row === priv.selRange.from.row);
},
/**
* Selects cell relative to current cell (if possible)
*/
transformStart: function (rowDelta, colDelta, force) {
var delta = new WalkontableCellCoords(rowDelta, colDelta);
instance.runHooks('modifyTransformStart', delta);
if (priv.selRange.highlight.row + rowDelta > instance.countRows() - 1) {
if (force && priv.settings.minSpareRows > 0) {
instance.alter("insert_row", instance.countRows());
}
else if (priv.settings.autoWrapCol) {
delta.row = 1 - instance.countRows();
delta.col = priv.selRange.highlight.col + delta.col == instance.countCols() - 1 ? 1 - instance.countCols() : 1;
}
}
else if (priv.settings.autoWrapCol && priv.selRange.highlight.row + delta.row < 0 && priv.selRange.highlight.col + delta.col >= 0) {
delta.row = instance.countRows() - 1;
delta.col = priv.selRange.highlight.col + delta.col == 0 ? instance.countCols() - 1 : -1;
}
if (priv.selRange.highlight.col + delta.col > instance.countCols() - 1) {
if (force && priv.settings.minSpareCols > 0) {
instance.alter("insert_col", instance.countCols());
}
else if (priv.settings.autoWrapRow) {
delta.row = priv.selRange.highlight.row + delta.row == instance.countRows() - 1 ? 1 - instance.countRows() : 1;
delta.col = 1 - instance.countCols();
}
}
else if (priv.settings.autoWrapRow && priv.selRange.highlight.col + delta.col < 0 && priv.selRange.highlight.row + delta.row >= 0) {
delta.row = priv.selRange.highlight.row + delta.row == 0 ? instance.countRows() - 1 : -1;
delta.col = instance.countCols() - 1;
}
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = new WalkontableCellCoords(priv.selRange.highlight.row + delta.row, priv.selRange.highlight.col + delta.col);
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeStart(coords);
},
/**
* Sets selection end cell relative to current selection end cell (if possible)
*/
transformEnd: function (rowDelta, colDelta) {
var delta = new WalkontableCellCoords(rowDelta, colDelta);
instance.runHooks('modifyTransformEnd', delta);
var totalRows = instance.countRows();
var totalCols = instance.countCols();
var coords = new WalkontableCellCoords(priv.selRange.to.row + delta.row, priv.selRange.to.col + delta.col);
if (coords.row < 0) {
coords.row = 0;
}
else if (coords.row > 0 && coords.row >= totalRows) {
coords.row = totalRows - 1;
}
if (coords.col < 0) {
coords.col = 0;
}
else if (coords.col > 0 && coords.col >= totalCols) {
coords.col = totalCols - 1;
}
selection.setRangeEnd(coords);
},
/**
* Returns true if currently there is a selection on screen, false otherwise
* @return {Boolean}
*/
isSelected: function () {
return (priv.selRange !== null);
},
/**
* Returns true if coords is within current selection coords
* @param {WalkontableCellCoords} coords
* @return {Boolean}
*/
inInSelection: function (coords) {
if (!selection.isSelected()) {
return false;
}
return priv.selRange.includes(coords);
},
/**
* Deselects all selected cells
*/
deselect: function () {
if (!selection.isSelected()) {
return;
}
instance.selection.inProgress = false; //needed by HT inception
priv.selRange = null;
instance.view.wt.selections.current.clear();
instance.view.wt.selections.area.clear();
editorManager.destroyEditor();
selection.refreshBorders();
Handsontable.hooks.run(instance, 'afterDeselect');
},
/**
* Select all cells
*/
selectAll: function () {
if (!priv.settings.multiSelect) {
return;
}
selection.setRangeStart(new WalkontableCellCoords(0, 0));
selection.setRangeEnd(new WalkontableCellCoords(instance.countRows() - 1, instance.countCols() - 1), false);
},
/**
* Deletes data from selected cells
*/
empty: function () {
if (!selection.isSelected()) {
return;
}
var topLeft = priv.selRange.getTopLeftCorner();
var bottomRight = priv.selRange.getBottomRightCorner();
var r, c, changes = [];
for (r = topLeft.row; r <= bottomRight.row; r++) {
for (c = topLeft.col; c <= bottomRight.col; c++) {
if (!instance.getCellMeta(r, c).readOnly) {
changes.push([r, c, '']);
}
}
}
instance.setDataAtCell(changes);
}
};
this.autofill = autofill = { //this public assignment is only temporary
handle: null,
/**
* Create fill handle and fill border objects
*/
init: function () {
if (!autofill.handle) {
autofill.handle = {};
}
else {
autofill.handle.disabled = false;
}
},
/**
* Hide fill handle and fill border permanently
*/
disable: function () {
autofill.handle.disabled = true;
},
/**
* Selects cells down to the last row in the left column, then fills down to that cell
*/
selectAdjacent: function () {
var select, data, r, maxR, c;
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
data = datamap.getAll();
rows : for (r = select[2] + 1; r < instance.countRows(); r++) {
for (c = select[1]; c <= select[3]; c++) {
if (data[r][c]) {
break rows;
}
}
if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) {
maxR = r;
}
}
if (maxR) {
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add([select[0], select[1]]);
instance.view.wt.selections.fill.add([maxR, select[3]]);
autofill.apply();
}
},
/**
* Apply fill values to the area in fill border, omitting the selection border
*/
apply: function () {
var drag, select, start, end, _data;
autofill.handle.isDragged = 0;
drag = instance.view.wt.selections.fill.getCorners();
if (!drag) {
return;
}
instance.view.wt.selections.fill.clear();
if (selection.isMultiple()) {
select = instance.view.wt.selections.area.getCorners();
}
else {
select = instance.view.wt.selections.current.getCorners();
}
if (drag[0] === select[0] && drag[1] < select[1]) {
start = new WalkontableCellCoords(
drag[0],
drag[1]
);
end = new WalkontableCellCoords(
drag[2],
select[1] - 1
);
}
else if (drag[0] === select[0] && drag[3] > select[3]) {
start = new WalkontableCellCoords(
drag[0],
select[3] + 1
);
end = new WalkontableCellCoords(
drag[2],
drag[3]
);
}
else if (drag[0] < select[0] && drag[1] === select[1]) {
start = new WalkontableCellCoords(
drag[0],
drag[1]
);
end = new WalkontableCellCoords(
select[0] - 1,
drag[3]
);
}
else if (drag[2] > select[2] && drag[1] === select[1]) {
start = new WalkontableCellCoords(
select[2] + 1,
drag[1]
);
end = new WalkontableCellCoords(
drag[2],
drag[3]
);
}
if (start) {
_data = SheetClip.parse(datamap.getText(priv.selRange.from, priv.selRange.to));
Handsontable.hooks.run(instance, 'beforeAutofill', start, end, _data);
grid.populateFromArray(start, _data, end, 'autofill');
selection.setRangeStart(new WalkontableCellCoords(drag[0], drag[1]));
selection.setRangeEnd(new WalkontableCellCoords(drag[2], drag[3]));
}
/*else {
//reset to avoid some range bug
selection.refreshBorders();
}*/
},
/**
* Show fill border
* @param {WalkontableCellCoords} coords
*/
showBorder: function (coords) {
var topLeft = priv.selRange.getTopLeftCorner();
var bottomRight = priv.selRange.getBottomRightCorner();
if (priv.settings.fillHandle !== 'horizontal' && (bottomRight.row < coords.row || topLeft.row > coords.row)) {
coords = new WalkontableCellCoords(coords.row, bottomRight.col);
}
else if (priv.settings.fillHandle !== 'vertical') {
coords = new WalkontableCellCoords(bottomRight.row, coords.col);
}
else {
return; //wrong direction
}
instance.view.wt.selections.fill.clear();
instance.view.wt.selections.fill.add(priv.selRange.from);
instance.view.wt.selections.fill.add(priv.selRange.to);
instance.view.wt.selections.fill.add(coords);
instance.view.render();
}
};
this.init = function () {
Handsontable.hooks.run(instance, 'beforeInit');
this.updateSettings(priv.settings, true);
this.view = new Handsontable.TableView(this);
editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap);
this.forceFullRender = true; //used when data was changed
this.view.render();
if (typeof priv.firstRun === 'object') {
Handsontable.hooks.run(instance, 'afterChange', priv.firstRun[0], priv.firstRun[1]);
priv.firstRun = false;
}
Handsontable.hooks.run(instance, 'afterInit');
};
function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file
var resolved = false;
return {
validatorsInQueue: 0,
addValidatorToQueue: function () {
this.validatorsInQueue++;
resolved = false;
},
removeValidatorFormQueue: function () {
this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1;
this.checkIfQueueIsEmpty();
},
onQueueEmpty: function () {
},
checkIfQueueIsEmpty: function () {
if (this.validatorsInQueue == 0 && resolved == false) {
resolved = true;
this.onQueueEmpty();
}
}
};
}
function validateChanges(changes, source, callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = resolve;
for (var i = changes.length - 1; i >= 0; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
}
else {
var row = changes[i][0];
var col = datamap.propToCol(changes[i][1]);
var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user)
var cellProperties = instance.getCellMeta(row, logicalCol);
if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') {
if (changes[i][3].length > 0 && /^-?[\d\s]*(\.|\,)?\d*$/.test(changes[i][3])) {
if(typeof cellProperties.language == 'undefined') {
numeral.language('en');
} else {
numeral.language(cellProperties.language);
}
changes[i][3] = parseFloat(changes[i][3].replace(',','.'));
}
}
if (instance.getCellValidator(cellProperties)) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) {
return function (result) {
if (typeof result !== 'boolean') {
throw new Error("Validation error: result is not boolean");
}
if (result === false && cellProperties.allowInvalid === false) {
changes.splice(i, 1); // cancel the change
cellProperties.valid = true; // we cancelled the change, so cell value is still valid
--i;
}
waitingForValidator.removeValidatorFormQueue();
}
})(i, cellProperties)
, source);
}
}
}
waitingForValidator.checkIfQueueIsEmpty();
function resolve() {
var beforeChangeResult;
if (changes.length) {
beforeChangeResult = Handsontable.hooks.execute(instance, "beforeChange", changes, source);
if (typeof beforeChangeResult === 'function') {
$.when(result).then(function () {
callback(); //called when async validators and async beforeChange are resolved
});
}
else if (beforeChangeResult === false) {
changes.splice(0, changes.length); //invalidate all changes (remove everything from array)
}
}
if (typeof beforeChangeResult !== 'function') {
callback(); //called when async validators are resolved and beforeChange was not async
}
}
}
/**
* Internal function to apply changes. Called after validateChanges
* @param {Array} changes Array in form of [row, prop, oldValue, newValue]
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
function applyChanges(changes, source) {
var i = changes.length - 1;
if (i < 0) {
return;
}
for (; 0 <= i; i--) {
if (changes[i] === null) {
changes.splice(i, 1);
continue;
}
if(changes[i][2] == null && changes[i][3] == null) {
continue;
}
if (priv.settings.minSpareRows) {
while (changes[i][0] > instance.countRows() - 1) {
datamap.createRow();
}
}
if (instance.dataType === 'array' && priv.settings.minSpareCols) {
while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) {
datamap.createCol();
}
}
datamap.set(changes[i][0], changes[i][1], changes[i][3]);
}
instance.forceFullRender = true; //used when data was changed
grid.adjustRowsAndCols();
Handsontable.hooks.run(instance, 'beforeChangeRender', changes, source);
selection.refreshBorders(null, true);
Handsontable.hooks.run(instance, 'afterChange', changes, source || 'edit');
}
this.validateCell = function (value, cellProperties, callback, source) {
var validator = instance.getCellValidator(cellProperties);
if (Object.prototype.toString.call(validator) === '[object RegExp]') {
validator = (function (validator) {
return function (value, callback) {
callback(validator.test(value));
}
})(validator);
}
if (typeof validator == 'function') {
value = Handsontable.hooks.execute(instance, "beforeValidate", value, cellProperties.row, cellProperties.prop, source);
// To provide consistent behaviour, validation should be always asynchronous
setTimeout(function () {
validator.call(cellProperties, value, function (valid) {
cellProperties.valid = valid;
valid = Handsontable.hooks.execute(instance, "afterValidate", valid, value, cellProperties.row, cellProperties.prop, source);
callback(valid);
});
});
} else { //resolve callback even if validator function was not found
cellProperties.valid = true;
callback(true);
}
};
function setDataInputToArray(row, prop_or_col, value) {
if (typeof row === "object") { //is it an array of changes
return row;
}
else if ($.isPlainObject(value)) { //backwards compatibility
return value;
}
else {
return [
[row, prop_or_col, value]
];
}
}
/**
* Set data at given cell
* @public
* @param {Number|Array} row or array of changes in format [[row, col, value], ...]
* @param {Number|String} col or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtCell = function (row, col, value, source) {
var input = setDataInputToArray(row, col, value)
, i
, ilen
, changes = []
, prop;
for (i = 0, ilen = input.length; i < ilen; i++) {
if (typeof input[i] !== 'object') {
throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter');
}
if (typeof input[i][1] !== 'number') {
throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`');
}
prop = datamap.colToProp(input[i][1]);
changes.push([
input[i][0],
prop,
datamap.get(input[i][0], prop),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = col;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Set data at given row property
* @public
* @param {Number|Array} row or array of changes in format [[row, prop, value], ...]
* @param {String} prop or source String
* @param {String} value
* @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback)
*/
this.setDataAtRowProp = function (row, prop, value, source) {
var input = setDataInputToArray(row, prop, value)
, i
, ilen
, changes = [];
for (i = 0, ilen = input.length; i < ilen; i++) {
changes.push([
input[i][0],
input[i][1],
datamap.get(input[i][0], input[i][1]),
input[i][2]
]);
}
if (!source && typeof row === "object") {
source = prop;
}
validateChanges(changes, source, function () {
applyChanges(changes, source);
});
};
/**
* Listen to document body keyboard input
*/
this.listen = function () {
Handsontable.activeGuid = instance.guid;
if (document.activeElement && document.activeElement !== document.body) {
document.activeElement.blur();
}
else if (!document.activeElement) { //IE
document.body.focus();
}
};
/**
* Stop listening to document body keyboard input
*/
this.unlisten = function () {
Handsontable.activeGuid = null;
};
/**
* Returns true if current Handsontable instance is listening on document body keyboard input
*/
this.isListening = function () {
return Handsontable.activeGuid === instance.guid;
};
/**
* Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
selection.refreshBorders(revertOriginal);
};
/**
* Populate cells at position with 2d array
* @param {Number} row Start row
* @param {Number} col Start column
* @param {Array} input 2d array
* @param {Number=} endRow End row (use when you want to cut input when certain row is reached)
* @param {Number=} endCol End column (use when you want to cut input when certain column is reached)
* @param {String=} [source="populateFromArray"]
* @param {String=} [method="overwrite"]
* @return {Object|undefined} ending td in pasted area (only if any cell was changed)
*/
this.populateFromArray = function (row, col, input, endRow, endCol, source, method) {
if (!(typeof input === 'object' && typeof input[0] === 'object')) {
throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly
}
return grid.populateFromArray(new WalkontableCellCoords(row, col), input, typeof endRow === 'number' ? new WalkontableCellCoords(endRow, endCol) : null, source, method);
};
/**
* Adds/removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceCol = function (col, index, amount/*, elements... */) {
return datamap.spliceCol.apply(datamap, arguments);
};
/**
* Adds/removes data from the row
* @param {Number} row Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
this.spliceRow = function (row, index, amount/*, elements... */) {
return datamap.spliceRow.apply(datamap, arguments);
};
/**
* Returns current selection. Returns undefined if there is no selection.
* @public
* @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`]
*/
this.getSelected = function () { //https://github.com/handsontable/jquery-handsontable/issues/44 //cjl
if (selection.isSelected()) {
return [priv.selRange.from.row, priv.selRange.from.col, priv.selRange.to.row, priv.selRange.to.col];
}
};
/**
* Returns current selection as a WalkontableCellRange object. Returns undefined if there is no selection.
* @public
* @return {WalkontableCellRange}
*/
this.getSelectedRange = function () { //https://github.com/handsontable/jquery-handsontable/issues/44 //cjl
if (selection.isSelected()) {
return priv.selRange;
}
};
/**
* Render visible data
* @public
*/
this.render = function () {
if (instance.view) {
instance.forceFullRender = true; //used when data was changed
selection.refreshBorders(null, true);
}
};
/**
* Load data from array
* @public
* @param {Array} data
*/
this.loadData = function (data) {
if (typeof data === 'object' && data !== null) {
if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it
//when data is not an array, attempt to make a single-row array of it
data = [data];
}
}
else if(data === null) {
data = [];
var row;
for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) {
row = [];
for (var c = 0, clen = priv.settings.startCols; c < clen; c++) {
row.push(null);
}
data.push(row);
}
}
else {
throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)");
}
priv.isPopulated = false;
GridSettings.prototype.data = data;
if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) {
instance.dataType = 'array';
}
else if (typeof priv.settings.dataSchema === 'function') {
instance.dataType = 'function';
}
else {
instance.dataType = 'object';
}
datamap = new Handsontable.DataMap(instance, priv, GridSettings);
clearCellSettingCache();
grid.adjustRowsAndCols();
Handsontable.hooks.run(instance, 'afterLoadData');
if (priv.firstRun) {
priv.firstRun = [null, 'loadData'];
}
else {
Handsontable.hooks.run(instance, 'afterChange', null, 'loadData');
instance.render();
}
priv.isPopulated = true;
function clearCellSettingCache() {
priv.cellSettings.length = 0;
}
};
/**
* Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data
* @public
* @param {Number} r (Optional) From row
* @param {Number} c (Optional) From col
* @param {Number} r2 (Optional) To row
* @param {Number} c2 (Optional) To col
* @return {Array|Object}
*/
this.getData = function (r, c, r2, c2) {
if (typeof r === 'undefined') {
return datamap.getAll();
}
else {
return datamap.getRange(new WalkontableCellCoords(r, c), new WalkontableCellCoords(r2, c2), datamap.DESTINATION_RENDERER);
}
};
this.getCopyableData = function (startRow, startCol, endRow, endCol) {
return datamap.getCopyableText(new WalkontableCellCoords(startRow, startCol), new WalkontableCellCoords(endRow, endCol));
};
/**
* Update settings
* @public
*/
this.updateSettings = function (settings, init) {
var i, clen;
if (typeof settings.rows !== "undefined") {
throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?");
}
if (typeof settings.cols !== "undefined") {
throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?");
}
for (i in settings) {
if (i === 'data') {
continue; //loadData will be triggered later
}
else {
if (Handsontable.hooks.hooks[i] !== void 0 || Handsontable.hooks.legacy[i] !== void 0) {
if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) {
instance.addHook(i, settings[i]);
}
}
else {
// Update settings
if (!init && settings.hasOwnProperty(i)) {
GridSettings.prototype[i] = settings[i];
}
}
}
}
// Load data or create data map
if (settings.data === void 0 && priv.settings.data === void 0) {
instance.loadData(null); //data source created just now
}
else if (settings.data !== void 0) {
instance.loadData(settings.data); //data source given as option
}
else if (settings.columns !== void 0) {
datamap.createMap();
}
// Init columns constructors configuration
clen = instance.countCols();
//Clear cellSettings cache
priv.cellSettings.length = 0;
if (clen > 0) {
var proto, column;
for (i = 0; i < clen; i++) {
priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
// shortcut for prototype
proto = priv.columnSettings[i].prototype;
// Use settings provided by user
if (GridSettings.prototype.columns) {
column = GridSettings.prototype.columns[i];
Handsontable.helper.extend(proto, column);
Handsontable.helper.extend(proto, expandType(column));
}
}
}
Handsontable.hooks.run(instance, 'afterCellMetaReset');
if (typeof settings.fillHandle !== "undefined") {
if (autofill.handle && settings.fillHandle === false) {
autofill.disable();
}
else if (!autofill.handle && settings.fillHandle !== false) {
autofill.init();
}
}
if (typeof settings.className !== "undefined") {
if (GridSettings.prototype.className) {
instance.rootElement.removeClass(GridSettings.prototype.className);
}
if (settings.className) {
instance.rootElement.addClass(settings.className);
}
}
if (typeof settings.height != 'undefined'){
var height = settings.height;
if (typeof height == 'function'){
height = height();
}
instance.rootElement[0].style.height = height + 'px';
}
if (typeof settings.width != 'undefined'){
var width = settings.width;
if (typeof width == 'function'){
width = width();
}
instance.rootElement[0].style.width = width + 'px';
}
if (height){
instance.rootElement[0].style.overflow = 'auto';
} else {
instance.rootElement[0].style.overflow = 'none';
}
if (!init) {
Handsontable.hooks.run(instance, 'afterUpdateSettings');
}
grid.adjustRowsAndCols();
if (instance.view && !priv.firstRun) {
instance.forceFullRender = true; //used when data was changed
selection.refreshBorders(null, true);
}
};
this.getValue = function () {
var sel = instance.getSelected();
if (GridSettings.prototype.getValue) {
if (typeof GridSettings.prototype.getValue === 'function') {
return GridSettings.prototype.getValue.call(instance);
}
else if (sel) {
return instance.getData()[sel[0]][GridSettings.prototype.getValue];
}
}
else if (sel) {
return instance.getDataAtCell(sel[0], sel[1]);
}
};
function expandType(obj) {
if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type
var type, expandedType = {};
if (typeof obj.type === 'object') {
type = obj.type;
}
else if (typeof obj.type === 'string') {
type = Handsontable.cellTypes[obj.type];
if (type === void 0) {
throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
}
for (var i in type) {
if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) {
expandedType[i] = type[i];
}
}
return expandedType;
};
/**
* Returns current settings object
* @return {Object}
*/
this.getSettings = function () {
return priv.settings;
};
/**
* Clears grid
* @public
*/
this.clear = function () {
selection.selectAll();
selection.empty();
};
/**
* Inserts or removes rows and columns
* @param {String} action See grid.alter for possible values
* @param {Number} index
* @param {Number} amount
* @param {String} [source] Optional. Source of hook runner.
* @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows.
* @public
*/
this.alter = function (action, index, amount, source, keepEmptyRows) {
grid.alter(action, index, amount, source, keepEmptyRows);
};
/**
* Returns <td> element corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Element}
*/
this.getCell = function (row, col) {
return instance.view.getCellAtCoords(new WalkontableCellCoords(row, col));
};
/**
* Returns property name associated with column number
* @param {Number} col
* @public
* @return {String}
*/
this.colToProp = function (col) {
return datamap.colToProp(col);
};
/**
* Returns column number associated with property name
* @param {String} prop
* @public
* @return {Number}
*/
this.propToCol = function (prop) {
return datamap.propToCol(prop);
};
/**
* Return value at `row`, `col`
* @param {Number} row
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCell = function (row, col) {
return datamap.get(row, datamap.colToProp(col));
};
/**
* Return value at `row`, `prop`
* @param {Number} row
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtRowProp = function (row, prop) {
return datamap.get(row, prop);
};
/**
* Return value at `col`
* @param {Number} col
* @public
* @return value (mixed data type)
*/
this.getDataAtCol = function (col) {
return [].concat.apply([], datamap.getRange(new WalkontableCellCoords(0, col), new WalkontableCellCoords(priv.settings.data.length - 1, col), datamap.DESTINATION_RENDERER));
};
/**
* Return value at `prop`
* @param {String} prop
* @public
* @return value (mixed data type)
*/
this.getDataAtProp = function (prop) {
return [].concat.apply([], datamap.getRange(new WalkontableCellCoords(0, datamap.propToCol(prop)), new WalkontableCellCoords(priv.settings.data.length - 1, datamap.propToCol(prop)), datamap.DESTINATION_RENDERER));
};
/**
* Return value at `row`
* @param {Number} row
* @public
* @return value (mixed data type)
*/
this.getDataAtRow = function (row) {
return priv.settings.data[row];
};
/**
* Sets cell meta data object "key" corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @param {String} key
* @param {String} val
*
*/
this.setCellMeta = function (row, col, key, val) {
if (!priv.cellSettings[row]) {
priv.cellSettings[row] = [];
}
if (!priv.cellSettings[row][col]) {
priv.cellSettings[row][col] = new priv.columnSettings[col]();
}
priv.cellSettings[row][col][key] = val;
Handsontable.hooks.run(instance, 'afterSetCellMeta', row, col, key, val);
};
/**
* Returns cell meta data object corresponding to params row, col
* @param {Number} row
* @param {Number} col
* @public
* @return {Object}
*/
this.getCellMeta = function (row, col) {
var prop = datamap.colToProp(col)
, cellProperties;
row = translateRowIndex(row);
col = translateColIndex(col);
if (!priv.columnSettings[col]) {
priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts);
}
if (!priv.cellSettings[row]) {
priv.cellSettings[row] = [];
}
if (!priv.cellSettings[row][col]) {
priv.cellSettings[row][col] = new priv.columnSettings[col]();
}
cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache
cellProperties.row = row;
cellProperties.col = col;
cellProperties.prop = prop;
cellProperties.instance = instance;
Handsontable.hooks.run(instance, 'beforeGetCellMeta', row, col, cellProperties);
Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta
if (cellProperties.cells) {
var settings = cellProperties.cells.call(cellProperties, row, col, prop);
if (settings) {
Handsontable.helper.extend(cellProperties, settings);
Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells
}
}
Handsontable.hooks.run(instance, 'afterGetCellMeta', row, col, cellProperties);
return cellProperties;
};
/**
* If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied)
* we need to translate logical (stored) row index to physical (displayed) index.
* @param row - original row index
* @returns {int} translated row index
*/
function translateRowIndex(row){
return Handsontable.hooks.execute(instance, 'modifyRow', row);
}
/**
* If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin)
* we need to translate logical (stored) column index to physical (displayed) index.
* @param col - original column index
* @returns {int} - translated column index
*/
function translateColIndex(col){
return Handsontable.hooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp
}
var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer');
this.getCellRenderer = function (row, col) {
var renderer = rendererLookup.call(this, row, col);
return Handsontable.renderers.getRenderer(renderer);
};
this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor');
this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator');
/**
* Validates all cells using their validator functions and calls callback when finished. Does not render the view
* @param callback
*/
this.validateCells = function (callback) {
var waitingForValidator = new ValidatorsQueue();
waitingForValidator.onQueueEmpty = callback;
var i = instance.countRows() - 1;
while (i >= 0) {
var j = instance.countCols() - 1;
while (j >= 0) {
waitingForValidator.addValidatorToQueue();
instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () {
waitingForValidator.removeValidatorFormQueue();
}, 'validateCells');
j--;
}
i--;
}
waitingForValidator.checkIfQueueIsEmpty();
};
/**
* Return array of row headers (if they are enabled). If param `row` given, return header at given row as string
* @param {Number} row (Optional)
* @return {Array|String}
*/
this.getRowHeader = function (row) {
if (row === void 0) {
var out = [];
for (var i = 0, ilen = instance.countRows(); i < ilen; i++) {
out.push(instance.getRowHeader(i));
}
return out;
}
else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) {
return priv.settings.rowHeaders[row];
}
else if (typeof priv.settings.rowHeaders === 'function') {
return priv.settings.rowHeaders(row);
}
else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') {
return row + 1;
}
else {
return priv.settings.rowHeaders;
}
};
/**
* Returns information of this table is configured to display row headers
* @returns {boolean}
*/
this.hasRowHeaders = function () {
return !!priv.settings.rowHeaders;
};
/**
* Returns information of this table is configured to display column headers
* @returns {boolean}
*/
this.hasColHeaders = function () {
if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null
return !!priv.settings.colHeaders;
}
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
if (instance.getColHeader(i)) {
return true;
}
}
return false;
};
/**
* Return array of column headers (if they are enabled). If param `col` given, return header at given column as string
* @param {Number} col (Optional)
* @return {Array|String}
*/
this.getColHeader = function (col) {
if (col === void 0) {
var out = [];
for (var i = 0, ilen = instance.countCols(); i < ilen; i++) {
out.push(instance.getColHeader(i));
}
return out;
}
else {
var baseCol = col;
col = Handsontable.hooks.execute(instance, 'modifyCol', col);
if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) {
return priv.settings.columns[col].title;
}
else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) {
return priv.settings.colHeaders[col];
}
else if (typeof priv.settings.colHeaders === 'function') {
return priv.settings.colHeaders(col);
}
else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') {
return Handsontable.helper.spreadsheetColumnLabel(baseCol); //see #1458
}
else {
return priv.settings.colHeaders;
}
}
};
/**
* Return column width from settings (no guessing). Private use intended
* @param {Number} col
* @return {Number}
*/
this._getColWidthFromSettings = function (col) {
var cellProperties = instance.getCellMeta(0, col);
var width = cellProperties.width;
if (width === void 0 || width === priv.settings.width) {
width = cellProperties.colWidths;
}
if (width !== void 0 && width !== null) {
switch (typeof width) {
case 'object': //array
width = width[col];
break;
case 'function':
width = width(col);
break;
}
if (typeof width === 'string') {
width = parseInt(width, 10);
}
}
return width;
};
/**
* Return column width
* @param {Number} col
* @return {Number}
*/
this.getColWidth = function (col) {
var width = instance._getColWidthFromSettings(col);
if (!width) {
width = 50;
}
width = Handsontable.hooks.execute(instance, 'modifyColWidth', width, col);
return width;
};
/**
* Return row height from settings (no guessing). Private use intended
* @param {Number} row
* @return {Number}
*/
this._getRowHeightFromSettings= function (row) {
/* inefficient
var cellProperties = instance.getCellMeta(0, row);
var height = cellProperties.height;
if (height === void 0 || height === priv.settings.height) {
height = cellProperties.rowHeights;
}
*/
var height = priv.settings.rowHeights; //only uses grid settings
if (height !== void 0 && height !== null) {
switch (typeof height) {
case 'object': //array
height = height[row];
break;
case 'function':
height = height(row);
break;
}
if (typeof height === 'string') {
height = parseInt(height, 10);
}
}
return height;
};
/**
* Return row height
* @param {Number} row
* @return {Number}
*/
this.getRowHeight = function (row) {
var height = instance._getRowHeightFromSettings(row);
height = Handsontable.hooks.execute(instance, 'modifyRowHeight', height, row);
return height;
};
/**
* Return total number of rows in grid
* @return {Number}
*/
this.countRows = function () {
return priv.settings.data.length;
};
/**
* Return total number of columns in grid
* @return {Number}
*/
this.countCols = function () {
if (instance.dataType === 'object' || instance.dataType === 'function') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else {
return datamap.colToPropCache.length;
}
}
else if (instance.dataType === 'array') {
if (priv.settings.columns && priv.settings.columns.length) {
return priv.settings.columns.length;
}
else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) {
return priv.settings.data[0].length;
}
else {
return 0;
}
}
};
/**
* Return index of first visible row
* @return {Number}
*/
this.rowOffset = function () {
return instance.view.wt.getSetting('offsetRow');
};
/**
* Return index of first visible column
* @return {Number}
*/
this.colOffset = function () {
return instance.view.wt.getSetting('offsetColumn');
};
/**
* Return number of visible rows. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleRows = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1;
};
/**
* Return number of visible columns. Returns -1 if table is not visible
* @return {Number}
*/
this.countVisibleCols = function () {
return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1;
};
/**
* Return number of empty rows
* @return {Boolean} ending If true, will only count empty rows at the end of the data source
*/
this.countEmptyRows = function (ending) {
var i = instance.countRows() - 1
, empty = 0
, row;
while (i >= 0) {
row = Handsontable.hooks.execute(this, 'modifyRow', i);
if (instance.isEmptyRow(row)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return number of empty columns
* @return {Boolean} ending If true, will only count empty columns at the end of the data source row
*/
this.countEmptyCols = function (ending) {
if (instance.countRows() < 1) {
return 0;
}
var i = instance.countCols() - 1
, empty = 0;
while (i >= 0) {
if (instance.isEmptyCol(i)) {
empty++;
}
else if (ending) {
break;
}
i--;
}
return empty;
};
/**
* Return true if the row at the given index is empty, false otherwise
* @param {Number} r Row index
* @return {Boolean}
*/
this.isEmptyRow = function (r) {
return priv.settings.isEmptyRow.call(instance, r);
};
/**
* Return true if the column at the given index is empty, false otherwise
* @param {Number} c Column index
* @return {Boolean}
*/
this.isEmptyCol = function (c) {
return priv.settings.isEmptyCol.call(instance, c);
};
/**
* Selects cell on grid. Optionally selects range to another cell
* @param {Number} row
* @param {Number} col
* @param {Number} [endRow]
* @param {Number} [endCol]
* @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection
* @public
* @return {Boolean}
*/
this.selectCell = function (row, col, endRow, endCol, scrollToCell) {
if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) {
return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
return false;
}
if (typeof endRow !== "undefined") {
if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
return false;
}
if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
return false;
}
}
var coords = new WalkontableCellCoords(row, col);
priv.selRange = new WalkontableCellRange(coords, coords, coords);
if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell)
}
instance.listen();
if (typeof endRow === "undefined") {
selection.setRangeEnd(priv.selRange.from, scrollToCell);
}
else {
selection.setRangeEnd(new WalkontableCellCoords(endRow, endCol), scrollToCell);
}
instance.selection.finish();
return true;
};
this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) {
arguments[1] = datamap.propToCol(arguments[1]);
if (typeof arguments[3] !== "undefined") {
arguments[3] = datamap.propToCol(arguments[3]);
}
return instance.selectCell.apply(instance, arguments);
};
/**
* Deselects current sell selection on grid
* @public
*/
this.deselectCell = function () {
selection.deselect();
};
/**
* Remove grid from DOM
* @public
*/
this.destroy = function () {
instance._clearTimeouts();
if (instance.view) { //in case HT is destroyed before initialization has finished
instance.view.wt.destroy();
}
instance.rootElement.empty();
instance.rootElement.removeData('handsontable');
instance.rootElement.off('.handsontable');
$(window).off('.' + instance.guid);
$document.off('.' + instance.guid);
$body.off('.' + instance.guid);
Handsontable.hooks.run(instance, 'afterDestroy');
};
/**
* Returns active editor object
* @returns {Object}
*/
this.getActiveEditor = function(){
return editorManager.getActiveEditor();
};
/**
* Return Handsontable instance
* @public
* @return {Object}
*/
this.getInstance = function () {
return instance;
};
this.addHook = function (key, fn) {
Handsontable.hooks.add(key, fn, instance);
};
this.addHookOnce = function (key, fn) {
Handsontable.hooks.once(key, fn, instance);
};
this.removeHook = function (key, fn) {
Handsontable.hooks.remove(key, fn, instance);
};
this.runHooks = function (key, p1, p2, p3, p4, p5) {
Handsontable.hooks.run(instance, key, p1, p2, p3, p4, p5);
};
this.runHooksAndReturn = function (key, p1, p2, p3, p4, p5) {
return Handsontable.hooks.execute(instance, key, p1, p2, p3, p4, p5);
};
this.timeouts = {};
/**
* Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called
* @public
*/
this._registerTimeout = function (key, handle, ms) {
clearTimeout(this.timeouts[key]);
this.timeouts[key] = setTimeout(handle, ms || 0);
};
/**
* Clears all known timeouts
* @public
*/
this._clearTimeouts = function () {
for (var key in this.timeouts) {
if (this.timeouts.hasOwnProperty(key)) {
clearTimeout(this.timeouts[key]);
}
}
};
/**
* Handsontable version
*/
this.version = '0.11.0-beta1'; //inserted by grunt from package.json
};
var DefaultSettings = function () {};
DefaultSettings.prototype = {
data: void 0,
width: void 0,
height: void 0,
startRows: 5,
startCols: 5,
rowHeaders: null,
colHeaders: null,
minRows: 0,
minCols: 0,
maxRows: Infinity,
maxCols: Infinity,
minSpareRows: 0,
minSpareCols: 0,
multiSelect: true,
fillHandle: true,
fixedRowsTop: 0,
fixedColumnsLeft: 0,
outsideClickDeselects: true,
enterBeginsEditing: true,
enterMoves: {row: 1, col: 0},
tabMoves: {row: 0, col: 1},
autoWrapRow: false,
autoWrapCol: false,
copyRowsLimit: 1000,
copyColsLimit: 1000,
pasteMode: 'overwrite',
currentRowClassName: void 0,
currentColClassName: void 0,
stretchH: 'hybrid',
isEmptyRow: function (r) {
var val;
for (var c = 0, clen = this.countCols(); c < clen; c++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
isEmptyCol: function (c) {
var val;
for (var r = 0, rlen = this.countRows(); r < rlen; r++) {
val = this.getDataAtCell(r, c);
if (val !== '' && val !== null && typeof val !== 'undefined') {
return false;
}
}
return true;
},
observeDOMVisibility: true,
allowInvalid: true,
invalidCellClassName: 'htInvalid',
placeholderCellClassName: 'htPlaceholder',
readOnlyCellClassName: 'htDimmed',
fragmentSelection: false,
readOnly: false,
type: 'text',
copyable: true,
debug: false, //shows debug overlays in Walkontable
wordWrap: true,
noWordWrapClassName: 'htNoWrap'
};
Handsontable.DefaultSettings = DefaultSettings;
$.fn.handsontable = function (action) {
var i
, ilen
, args
, output
, userSettings
, $this = this.first() // Use only first element from list
, instance = $this.data('handsontable');
// Init case
if (typeof action !== 'string') {
userSettings = action || {};
if (instance) {
instance.updateSettings(userSettings);
}
else {
instance = new Handsontable.Core($this, userSettings);
$this.data('handsontable', instance);
instance.init();
}
return $this;
}
// Action case
else {
args = [];
if (arguments.length > 1) {
for (i = 1, ilen = arguments.length; i < ilen; i++) {
args.push(arguments[i]);
}
}
if (instance) {
if (typeof instance[action] !== 'undefined') {
output = instance[action].apply(instance, args);
}
else {
throw new Error('Handsontable do not provide action: ' + action);
}
}
return output;
}
};
(function (window) {
'use strict';
function MultiMap() {
var map = {
arrayMap: [],
weakMap: new WeakMap()
};
return {
'get': function (key) {
if (canBeAnArrayMapKey(key)) {
return map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
return map.weakMap.get(key);
}
},
'set': function (key, value) {
if (canBeAnArrayMapKey(key)) {
map.arrayMap[key] = value;
} else if (canBeAWeakMapKey(key)) {
map.weakMap.set(key, value);
} else {
throw new Error('Invalid key type');
}
},
'delete': function (key) {
if (canBeAnArrayMapKey(key)) {
delete map.arrayMap[key];
} else if (canBeAWeakMapKey(key)) {
map.weakMap['delete'](key); //Delete must be called using square bracket notation, because IE8 does not handle using `delete` with dot notation
}
}
};
function canBeAnArrayMapKey(obj){
return obj !== null && !isNaNSymbol(obj) && (typeof obj == 'string' || typeof obj == 'number');
}
function canBeAWeakMapKey(obj){
return obj !== null && (typeof obj == 'object' || typeof obj == 'function');
}
function isNaNSymbol(obj){
return obj !== obj; // NaN === NaN is always false
}
}
if (!window.MultiMap){
window.MultiMap = MultiMap;
}
})(window);
/**
* DOM helper optimized for maximum performance
* It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery
* @type {Object}
*/
if(!window.Handsontable) {
var Handsontable = {}; //required because Walkontable test suite uses this class directly
}
Handsontable.Dom = {};
//goes up the DOM tree (including given element) until it finds an element that matches the nodeName
Handsontable.Dom.closest = function (elem, nodeNames, until) {
while (elem != null && elem !== until) {
if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) {
return elem;
}
elem = elem.parentNode;
}
return null;
};
//goes up the DOM tree and checks if element is child of another element
Handsontable.Dom.isChildOf = function (child, parent) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Counts index of element within its parent
* WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable
* Otherwise would need to check for nodeType or use previousElementSibling
* @see http://jsperf.com/sibling-index/10
* @param {Element} elem
* @return {Number}
*/
Handsontable.Dom.index = function (elem) {
var i = 0;
while (elem = elem.previousSibling) {
++i
}
return i;
};
if (document.documentElement.classList) {
// HTML5 classList API
Handsontable.Dom.hasClass = function (ele, cls) {
return ele.classList.contains(cls);
};
Handsontable.Dom.addClass = function (ele, cls) {
ele.classList.add(cls);
};
Handsontable.Dom.removeClass = function (ele, cls) {
ele.classList.remove(cls);
};
}
else {
//http://snipplr.com/view/3561/addclass-removeclass-hasclass/
Handsontable.Dom.hasClass = function (ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
};
Handsontable.Dom.addClass = function (ele, cls) {
if (!this.hasClass(ele, cls)) ele.className += " " + cls;
};
Handsontable.Dom.removeClass = function (ele, cls) {
if (this.hasClass(ele, cls)) { //is this really needed?
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js
}
};
}
/*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
Handsontable.Dom.addEvent = (function () {
var that = this;
if (document.addEventListener) {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.addEventListener(type, cb, false);
}
else if (elem && elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
else {
return function (elem, type, cb) {
if ((elem && !elem.length) || elem === window) {
elem.attachEvent('on' + type, function () {
//normalize
//http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
var e = window['event'];
e.target = e.srcElement;
//e.offsetX = e.layerX;
//e.offsetY = e.layerY;
e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement;
if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug
return cb.call(elem, e)
});
}
else if (elem.length) {
var len = elem.length;
for (var i = 0; i < len; i++) {
that.addEvent(elem[i], type, cb);
}
}
};
}
})();
Handsontable.Dom.triggerEvent = function (element, eventName, target) {
var event;
if (document.createEvent) {
event = document.createEvent("MouseEvents");
event.initEvent(eventName, true, true);
} else {
event = document.createEventObject();
event.eventType = eventName;
}
event.eventName = eventName;
event.target = target;
if (document.createEvent) {
target.dispatchEvent(event);
} else {
target.fireEvent("on" + event.eventType, event);
}
};*/
Handsontable.Dom.removeTextNodes = function (elem, parent) {
if (elem.nodeType === 3) {
parent.removeChild(elem); //bye text nodes!
}
else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) {
var childs = elem.childNodes;
for (var i = childs.length - 1; i >= 0; i--) {
this.removeTextNodes(childs[i], elem);
}
}
};
/**
* Remove childs function
* WARNING - this doesn't unload events and data attached by jQuery
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9
* http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method
* @param element
* @returns {void}
*/
//
Handsontable.Dom.empty = function (element) {
var child;
while (child = element.lastChild) {
element.removeChild(child);
}
};
Handsontable.Dom.HTML_CHARACTERS = /(<(.*)>|&(.*);)/;
/**
* Insert content into element trying avoid innerHTML method.
* @return {void}
*/
Handsontable.Dom.fastInnerHTML = function (element, content) {
if (this.HTML_CHARACTERS.test(content)) {
element.innerHTML = content;
}
else {
this.fastInnerText(element, content);
}
};
/**
* Insert text content into element
* @return {void}
*/
if (document.createTextNode('test').textContent) { //STANDARDS
Handsontable.Dom.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.textContent = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
else { //IE8
Handsontable.Dom.fastInnerText = function (element, content) {
var child = element.firstChild;
if (child && child.nodeType === 3 && child.nextSibling === null) {
//fast lane - replace existing text node
//http://jsperf.com/replace-text-vs-reuse
child.data = content;
}
else {
//slow lane - empty element and insert a text node
this.empty(element);
element.appendChild(document.createTextNode(content));
}
};
}
/**
* Returns true/false depending if element has offset parent
* @param elem
* @returns {boolean}
*/
/*if (document.createTextNode('test').textContent) { //STANDARDS
Handsontable.Dom.hasOffsetParent = function (elem) {
return !!elem.offsetParent;
}
}
else {
Handsontable.Dom.hasOffsetParent = function (elem) {
try {
if (!elem.offsetParent) {
return false;
}
}
catch (e) {
return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here
}
return true;
}
}*/
/**
* Returns true if element is attached to the DOM and visible, false otherwise
* @param elem
* @returns {boolean}
*/
Handsontable.Dom.isVisible = function (elem) {
//fast method according to benchmarks, but requires layout so slow in our case
/*
if (!Handsontable.Dom.hasOffsetParent(elem)) {
return false; //fixes problem with UI Bootstrap <tabs> directive
}
// if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here
if (elem.offsetWidth > 0) {
return true;
}
*/
//slow method
var next = elem;
while (next !== document.documentElement) { //until <html> reached
if (next === null) { //parent detached from DOM
return false;
}
else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE
if (next.host) { //this is Web Components Shadow DOM
//see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation
//according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet
if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled
return Handsontable.Dom.isVisible(next.host.impl);
}
else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled
return Handsontable.Dom.isVisible(next.host);
}
else {
throw new Error("Lost in Web Components world");
}
}
else {
return false; //this is a node detached from document in IE8
}
}
else if (next.style.display === 'none') {
return false;
}
next = next.parentNode;
}
return true;
};
/**
* Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster
* @param {HTMLElement} elem
* @return {Object}
*/
Handsontable.Dom.offset = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE offset (see also Handsontable.Dom.outerHeight)
//http://jsperf.com/offset-vs-getboundingclientrect/8
var box = elem.getBoundingClientRect();
return {
top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0),
left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0)
};
}
var offsetLeft = elem.offsetLeft
, offsetTop = elem.offsetTop
, lastElem = elem;
while (elem = elem.offsetParent) {
if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0
break;
}
offsetLeft += elem.offsetLeft;
offsetTop += elem.offsetTop;
lastElem = elem;
}
if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6
//if(lastElem !== document.body) { //faster but does gives false positive in Firefox
offsetLeft += window.pageXOffset || document.documentElement.scrollLeft;
offsetTop += window.pageYOffset || document.documentElement.scrollTop;
}
return {
left: offsetLeft,
top: offsetTop
};
};
Handsontable.Dom.getWindowScrollTop = function () {
var res = window.scrollY;
if (res == void 0) { //IE8-11
res = document.documentElement.scrollTop;
}
return res;
};
Handsontable.Dom.getWindowScrollLeft = function () {
var res = window.scrollX;
if (res == void 0) { //IE8-11
res = document.documentElement.scrollLeft;
}
return res;
};
Handsontable.Dom.getScrollTop = function (elem) {
if (elem === window) {
return Handsontable.Dom.getWindowScrollTop(elem);
}
else {
return elem.scrollTop;
}
};
Handsontable.Dom.getScrollLeft = function (elem) {
if (elem === window) {
return Handsontable.Dom.getWindowScrollLeft(elem);
}
else {
return elem.scrollLeft;
}
};
Handsontable.Dom.getComputedStyle = function (elem) {
return elem.currentStyle || document.defaultView.getComputedStyle(elem);
};
Handsontable.Dom.outerWidth = function (elem) {
return elem.offsetWidth;
};
Handsontable.Dom.outerHeight = function (elem) {
if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') {
//fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight
//jQuery (1.10.1) still has this unsolved
//may be better to just switch to getBoundingClientRect
//http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html
//http://bugs.jquery.com/ticket/2196
//http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140
return elem.offsetHeight + elem.firstChild.offsetHeight;
}
else {
return elem.offsetHeight;
}
};
(function () {
var hasCaptionProblem;
function detectCaptionProblem() {
var TABLE = document.createElement('TABLE');
TABLE.style.borderSpacing = 0;
TABLE.style.borderWidth = 0;
TABLE.style.padding = 0;
var TBODY = document.createElement('TBODY');
TABLE.appendChild(TBODY);
TBODY.appendChild(document.createElement('TR'));
TBODY.firstChild.appendChild(document.createElement('TD'));
TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>';
var CAPTION = document.createElement('CAPTION');
CAPTION.innerHTML = 'c<br>c<br>c<br>c';
CAPTION.style.padding = 0;
CAPTION.style.margin = 0;
TABLE.insertBefore(CAPTION, TBODY);
document.body.appendChild(TABLE);
hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean
document.body.removeChild(TABLE);
}
Handsontable.Dom.hasCaptionProblem = function () {
if (hasCaptionProblem === void 0) {
detectCaptionProblem();
}
return hasCaptionProblem;
};
/**
* Returns caret position in text input
* @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea
* @return {Number}
*/
Handsontable.Dom.getCaretPosition = function (el) {
if (el.selectionStart) {
return el.selectionStart;
}
else if (document.selection) { //IE8
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
};
/**
* Sets caret position in text input
* @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
* @param {Element} el
* @param {Number} pos
* @param {Number} endPos
*/
Handsontable.Dom.setCaretPosition = function (el, pos, endPos) {
if (endPos === void 0) {
endPos = pos;
}
if (el.setSelectionRange) {
el.focus();
el.setSelectionRange(pos, endPos);
}
else if (el.createTextRange) { //IE8
var range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', endPos);
range.moveStart('character', pos);
range.select();
}
};
var cachedScrollbarWidth;
//http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes
function walkontableCalculateScrollbarWidth() {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild(inner);
(document.body || document.documentElement).appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
(document.body || document.documentElement).removeChild(outer);
return (w1 - w2);
}
/**
* Returns the computed width of the native browser scroll bar
* @return {Number} width
*/
Handsontable.Dom.getScrollbarWidth = function () {
if (cachedScrollbarWidth === void 0) {
cachedScrollbarWidth = walkontableCalculateScrollbarWidth();
}
return cachedScrollbarWidth;
}
})();
/**
* Handsontable TableView constructor
* @param {Object} instance
*/
Handsontable.TableView = function (instance) {
var that = this
, $window = $(window)
, $documentElement = $(document.documentElement);
this.instance = instance;
this.settings = instance.getSettings();
instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions
// in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+
instance.rootElement.addClass('handsontable');
var table = document.createElement('TABLE');
table.className = 'htCore';
this.THEAD = document.createElement('THEAD');
table.appendChild(this.THEAD);
this.TBODY = document.createElement('TBODY');
table.appendChild(this.TBODY);
instance.$table = $(table);
instance.container.prepend(instance.$table);
instance.rootElement.on('mousedown.handsontable', function (event) {
if (!that.isTextSelectionAllowed(event.target)) {
clearTextSelection();
event.preventDefault();
window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe.
}
});
$documentElement.on('keyup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && !event.shiftKey) {
instance.selection.finish();
}
});
var isMouseDown;
$documentElement.on('mouseup.' + instance.guid, function (event) {
if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button
instance.selection.finish();
}
isMouseDown = false;
if (instance.autofill.handle && instance.autofill.handle.isDragged) {
if (instance.autofill.handle.isDragged > 1) {
instance.autofill.apply();
}
instance.autofill.handle.isDragged = 0;
}
if (Handsontable.helper.isOutsideInput(document.activeElement)) {
instance.unlisten();
}
});
$documentElement.on('mousedown.' + instance.guid, function (event) {
var next = event.target;
if (next.shadowRoot) {
return; //click inside Web Component
}
if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar
while (next !== document.documentElement) {
if (next === null) {
return; //click on something that was a row but now is detached (possibly because your click triggered a rerender)
}
if (next === instance.rootElement[0]) {
return; //click inside container
}
next = next.parentNode;
}
}
//function did not return until here, we have an outside click!
if (that.settings.outsideClickDeselects) {
instance.deselectCell();
}
else {
instance.destroyEditor();
}
});
instance.$table.on('selectstart', function (event) {
if (that.settings.fragmentSelection) {
return;
}
//https://github.com/handsontable/jquery-handsontable/issues/160
//selectstart is IE only event. Prevent text from being selected when performing drag down in IE8
event.preventDefault();
});
var clearTextSelection = function () {
//http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}
};
var walkontableConfig = {
debug: function () {
return that.settings.debug;
},
table: table,
stretchH: this.settings.stretchH,
data: instance.getDataAtCell,
totalRows: instance.countRows,
totalColumns: instance.countCols,
offsetRow: 0,
offsetColumn: 0,
fixedColumnsLeft: function () {
return that.settings.fixedColumnsLeft;
},
fixedRowsTop: function () {
return that.settings.fixedRowsTop;
},
renderAllRows: that.settings.renderAllRows,
rowHeaders: function () {
return instance.hasRowHeaders() ? [function (index, TH) {
that.appendRowHeader(index, TH);
}] : []
},
columnHeaders: function () {
return instance.hasColHeaders() ? [function (index, TH) {
that.appendColHeader(index, TH);
}] : []
},
columnWidth: instance.getColWidth,
rowHeight: instance.getRowHeight,
cellRenderer: function (row, col, TD) {
var prop = that.instance.colToProp(col)
, cellProperties = that.instance.getCellMeta(row, col)
, renderer = that.instance.getCellRenderer(cellProperties);
var value = that.instance.getDataAtRowProp(row, prop);
renderer(that.instance, TD, row, col, prop, value, cellProperties);
Handsontable.hooks.run(that.instance, 'afterRenderer', TD, row, col, prop, value, cellProperties);
},
selections: {
current: {
className: 'current',
border: {
width: 2,
color: '#5292F7',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple()
}
}
},
area: {
className: 'area',
border: {
width: 1,
color: '#89AFF9',
style: 'solid',
cornerVisible: function () {
return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple()
}
}
},
highlight: {
highlightRowClassName: that.settings.currentRowClassName,
highlightColumnClassName: that.settings.currentColClassName
},
fill: {
className: 'fill',
border: {
width: 1,
color: 'red',
style: 'solid'
}
}
},
hideBorderOnMouseDownOver: function () {
return that.settings.fragmentSelection;
},
onCellMouseDown: function (event, coords, TD, wt) {
instance.listen();
that.activeWt = wt;
isMouseDown = true;
if (event.target.className === 'manualColumnMover') {
return;
}
if (event.button === 2 && instance.selection.inInSelection(coords)) { //right mouse button
//do nothing
}
else if (event.shiftKey) {
if (coords.row >= 0 && coords.col >= 0) {
instance.selection.setRangeEnd(coords);
}
}
else {
if (coords.row < 0 || coords.col < 0) {
if (coords.row < 0) {
instance.selectCell(0, coords.col, instance.countRows() - 1, coords.col);
}
if (coords.col < 0) {
instance.selectCell(coords.row, 0, coords.row, instance.countCols() - 1);
}
}
else {
instance.selection.setRangeStart(coords);
}
}
Handsontable.hooks.run(instance, 'afterOnCellMouseDown', event, coords, TD);
that.activeWt = that.wt;
},
/*onCellMouseOut: function (/*event, coords, TD* /) {
if (isMouseDown && that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}
},*/
onCellMouseOver: function (event, coords, TD, wt) {
that.activeWt = wt;
if (coords.row >= 0 && coords.col >= 0) { //is not a header
if (isMouseDown) {
/*if (that.settings.fragmentSelection === 'single') {
clearTextSelection(); //otherwise text selection blinks during multiple cells selection
}*/
instance.selection.setRangeEnd(coords);
}
else if (instance.autofill.handle && instance.autofill.handle.isDragged) {
instance.autofill.handle.isDragged++;
instance.autofill.showBorder(coords);
}
}
Handsontable.hooks.run(instance, 'afterOnCellMouseOver', event, coords, TD);
that.activeWt = that.wt;
},
onCellCornerMouseDown: function (event) {
instance.autofill.handle.isDragged = 1;
event.preventDefault();
Handsontable.hooks.run(instance, 'afterOnCellCornerMouseDown', event);
},
onCellCornerDblClick: function () {
instance.autofill.selectAdjacent();
},
beforeDraw: function (force) {
that.beforeRender(force);
},
onDraw: function(force){
that.onDraw(force);
},
onScrollVertically: function () {
instance.runHooks('afterScrollVertically');
},
onScrollHorizontally: function () {
instance.runHooks('afterScrollHorizontally');
}
};
Handsontable.hooks.run(instance, 'beforeInitWalkontable', walkontableConfig);
this.wt = new Walkontable(walkontableConfig);
this.activeWt = this.wt;
/*$window.on('resize.' + instance.guid, function () {
instance._registerTimeout('resizeTimeout', function () {
instance.forceFullRender = true;
that.render();
}, 60);
});*/
$(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) {
if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar
event.stopPropagation();
}
});
$documentElement.on('click.' + instance.guid, function () {
if (that.settings.observeDOMVisibility) {
if (that.wt.drawInterrupted) {
that.instance.forceFullRender = true;
that.render();
}
}
});
};
Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) {
if ( Handsontable.helper.isInput(el) ) {
return (true);
}
if (this.settings.fragmentSelection && Handsontable.Dom.isChildOf(el, this.TBODY)) {
return (true);
}
return false;
};
Handsontable.TableView.prototype.isCellEdited = function () {
var activeEditor = this.instance.getActiveEditor();
return activeEditor && activeEditor.isOpened();
};
Handsontable.TableView.prototype.getWidth = function () {
return this.wt.wtViewport.getWorkspaceActualWidth();
};
Handsontable.TableView.prototype.getHeight = function () {
return this.wt.wtViewport.getWorkspaceActualHeight();
};
Handsontable.TableView.prototype.beforeRender = function (force) {
if (force) { //force = did Walkontable decide to do full render
Handsontable.hooks.run(this.instance, 'beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
}
};
Handsontable.TableView.prototype.onDraw = function(force){
if (force) { //force = did Walkontable decide to do full render
Handsontable.hooks.run(this.instance, 'afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render?
}
};
Handsontable.TableView.prototype.render = function () {
this.wt.draw(!this.instance.forceFullRender);
this.instance.forceFullRender = false;
this.instance.rootElement.triggerHandler('render.handsontable');
};
/**
* Returns td object given coordinates
* @param {WalkontableCellCoords} coords
*/
Handsontable.TableView.prototype.getCellAtCoords = function (coords) {
var td = this.wt.wtTable.getCell(coords);
if (td < 0) { //there was an exit code (cell is out of bounds)
return null;
}
else {
return td;
}
};
/**
* Scroll viewport to selection
* @param {WalkontableCellCoords} coords
*/
Handsontable.TableView.prototype.scrollViewport = function (coords) {
this.wt.scrollViewport(coords);
};
/**
* Append row header to a TH element
* @param row
* @param TH
*/
Handsontable.TableView.prototype.appendRowHeader = function (row, TH) {
if (row > -1) {
Handsontable.Dom.fastInnerHTML(TH, this.instance.getRowHeader(row));
}
else {
var DIV = document.createElement('DIV');
DIV.className = 'relative';
Handsontable.Dom.fastInnerText(DIV, '\u00A0');
Handsontable.Dom.empty(TH);
TH.appendChild(DIV);
}
};
/**
* Append column header to a TH element
* @param col
* @param TH
*/
Handsontable.TableView.prototype.appendColHeader = function (col, TH) {
var DIV = document.createElement('DIV')
, SPAN = document.createElement('SPAN');
DIV.className = 'relative';
SPAN.className = 'colHeader';
Handsontable.Dom.fastInnerHTML(SPAN, this.instance.getColHeader(col));
DIV.appendChild(SPAN);
Handsontable.Dom.empty(TH);
TH.appendChild(DIV);
Handsontable.hooks.run(this.instance, 'afterGetColHeader', col, TH);
};
/**
* Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar)
* @param {Number} left
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementWidth = function (leftOffset) {
this.wt.wtScrollbars.horizontal.readWindowSize();
var workspaceWidth = this.wt.wtViewport.getWorkspaceWidth();
var maxWidth = workspaceWidth - leftOffset;
return maxWidth > 0 ? maxWidth : 0;
};
/**
* Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar)
* @param {Number} topOffset
* @return {Number}
*/
Handsontable.TableView.prototype.maximumVisibleElementHeight = function (topOffset) {
this.wt.wtScrollbars.vertical.readWindowSize();
var workspaceHeight = this.wt.wtViewport.getWorkspaceHeight();
var maxHeight = workspaceHeight - topOffset;
return maxHeight > 0 ? maxHeight : 0;
};
Handsontable.TableView.prototype.mainViewIsActive = function () {
return this.wt === this.activeWt;
};
/**
* Utility to register editors and common namespace for keeping reference to all editor classes
*/
(function (Handsontable) {
'use strict';
function RegisteredEditor(editorClass) {
var clazz, instances;
instances = {};
clazz = editorClass;
this.getInstance = function (hotInstance) {
if (!(hotInstance.guid in instances)) {
instances[hotInstance.guid] = new clazz(hotInstance);
}
return instances[hotInstance.guid];
}
}
var registeredEditorNames = {};
var registeredEditorClasses = new WeakMap();
Handsontable.editors = {
/**
* Registers editor under given name
* @param {String} editorName
* @param {Function} editorClass
*/
registerEditor: function (editorName, editorClass) {
var editor = new RegisteredEditor(editorClass);
if (typeof editorName === "string") {
registeredEditorNames[editorName] = editor;
}
registeredEditorClasses.set(editorClass, editor);
},
/**
* Returns instance (singleton) of editor class
* @param {String|Function} editorName/editorClass
* @returns {Function} editorClass
*/
getEditor: function (editorName, hotInstance) {
var editor;
if (typeof editorName == 'function') {
if (!(registeredEditorClasses.get(editorName))) {
this.registerEditor(null, editorName);
}
editor = registeredEditorClasses.get(editorName);
}
else if (typeof editorName == 'string') {
editor = registeredEditorNames[editorName];
}
else {
throw Error('Only strings and functions can be passed as "editor" parameter ');
}
if (!editor) {
throw Error('No editor registered under name "' + editorName + '"');
}
return editor.getInstance(hotInstance);
}
};
})(Handsontable);
(function(Handsontable){
'use strict';
Handsontable.EditorManager = function(instance, priv, selection){
var that = this;
var $document = $(document);
var keyCodes = Handsontable.helper.keyCode;
var activeEditor;
var init = function () {
function onKeyDown(event) {
if (!instance.isListening()) {
return;
}
if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin
priv.settings.beforeOnKeyDown.call(instance, event);
}
Handsontable.hooks.run(instance, 'beforeKeyDown', event);
if (!event.isImmediatePropagationStopped()) {
priv.lastKeyCode = event.keyCode;
if (selection.isSelected()) {
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (!activeEditor.isWaiting()) {
if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown && !that.isEditorOpened()) {
that.openEditor('');
event.stopPropagation(); //required by HandsontableEditor
return;
}
}
var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart;
switch (event.keyCode) {
case keyCodes.A:
if (ctrlDown) {
selection.selectAll(); //select all cells
event.preventDefault();
event.stopPropagation();
break;
}
case keyCodes.ARROW_UP:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionUp(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_DOWN:
if (that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionDown(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_RIGHT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionRight(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.ARROW_LEFT:
if(that.isEditorOpened() && !activeEditor.isWaiting()){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionLeft(event.shiftKey);
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.TAB:
var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves;
if (event.shiftKey) {
selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left
}
else {
selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed)
}
event.preventDefault();
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
selection.empty(event);
that.prepareEditor();
event.preventDefault();
break;
case keyCodes.F2: /* F2 */
that.openEditor();
event.preventDefault(); //prevent Opera from opening Go to Page dialog
break;
case keyCodes.ENTER: /* return/enter */
if(that.isEditorOpened()){
if (activeEditor.state !== Handsontable.EditorState.WAITING){
that.closeEditorAndSaveChanges(ctrlDown);
}
moveSelectionAfterEnter(event.shiftKey);
} else {
if (instance.getSettings().enterBeginsEditing){
that.openEditor();
} else {
moveSelectionAfterEnter(event.shiftKey);
}
}
event.preventDefault(); //don't add newline to field
event.stopImmediatePropagation(); //required by HandsontableEditor
break;
case keyCodes.ESCAPE:
if(that.isEditorOpened()){
that.closeEditorAndRestoreOriginalValue(ctrlDown);
}
event.preventDefault();
break;
case keyCodes.HOME:
if (event.ctrlKey || event.metaKey) {
rangeModifier(new WalkontableCellCoords(0, priv.selRange.from.col));
}
else {
rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, 0));
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.END:
if (event.ctrlKey || event.metaKey) {
rangeModifier(new WalkontableCellCoords(instance.countRows() - 1, priv.selRange.from.col));
}
else {
rangeModifier(new WalkontableCellCoords(priv.selRange.from.row, instance.countCols() - 1));
}
event.preventDefault(); //don't scroll the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_UP:
selection.transformStart(-instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(-instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page up the window
event.stopPropagation(); //required by HandsontableEditor
break;
case keyCodes.PAGE_DOWN:
selection.transformStart(instance.countVisibleRows(), 0);
instance.view.wt.scrollVertical(instance.countVisibleRows());
instance.view.render();
event.preventDefault(); //don't page down the window
event.stopPropagation(); //required by HandsontableEditor
break;
default:
break;
}
}
}
}
$document.on('keydown.handsontable.' + instance.guid, onKeyDown);
function onDblClick(event, coords, elem) {
if(elem.nodeName == "TD") { //may be TD or TH
//that.instance.destroyEditor();
that.openEditor();
}
}
instance.view.wt.update('onCellDblClick', onDblClick);
instance.addHook('afterDestroy', function(){
$document.off('keydown.handsontable.' + instance.guid);
});
function moveSelectionAfterEnter(shiftKey){
var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves;
if (shiftKey) {
selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up
}
else {
selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed)
}
}
function moveSelectionUp(shiftKey){
if (shiftKey) {
selection.transformEnd(-1, 0);
}
else {
selection.transformStart(-1, 0);
}
}
function moveSelectionDown(shiftKey){
if (shiftKey) {
selection.transformEnd(1, 0); //expanding selection down with shift
}
else {
selection.transformStart(1, 0); //move selection down
}
}
function moveSelectionRight(shiftKey){
if (shiftKey) {
selection.transformEnd(0, 1);
}
else {
selection.transformStart(0, 1);
}
}
function moveSelectionLeft(shiftKey){
if (shiftKey) {
selection.transformEnd(0, -1);
}
else {
selection.transformStart(0, -1);
}
}
};
/**
* Destroy current editor, if exists
* @param {Boolean} revertOriginal
*/
this.destroyEditor = function (revertOriginal) {
this.closeEditor(revertOriginal);
};
this.getActiveEditor = function () {
return activeEditor;
};
/**
* Prepare text input to be displayed at given grid cell
*/
this.prepareEditor = function () {
if (activeEditor && activeEditor.isWaiting()){
this.closeEditor(false, false, function(dataSaved){
if(dataSaved){
that.prepareEditor();
}
});
return;
}
var row = priv.selRange.highlight.row;
var col = priv.selRange.highlight.col;
var prop = instance.colToProp(col);
var td = instance.getCell(row, col);
var originalValue = instance.getDataAtCell(row, col);
var cellProperties = instance.getCellMeta(row, col);
var editorClass = instance.getCellEditor(cellProperties);
activeEditor = Handsontable.editors.getEditor(editorClass, instance);
activeEditor.prepare(row, col, prop, td, originalValue, cellProperties);
};
this.isEditorOpened = function () {
return activeEditor.isOpened();
};
this.openEditor = function (initialValue) {
if (!activeEditor.cellProperties.readOnly){
activeEditor.beginEditing(initialValue);
}
};
this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) {
if (!activeEditor){
if(callback) {
callback(false);
}
}
else {
activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback);
}
};
this.closeEditorAndSaveChanges = function(ctrlDown){
return this.closeEditor(false, ctrlDown);
};
this.closeEditorAndRestoreOriginalValue = function(ctrlDown){
return this.closeEditor(true, ctrlDown);
};
init();
};
})(Handsontable);
/**
* Utility to register renderers and common namespace for keeping reference to all renderers classes
*/
(function (Handsontable) {
'use strict';
var registeredRenderers = {};
Handsontable.renderers = {
/**
* Registers renderer under given name
* @param {String} rendererName
* @param {Function} rendererFunction
*/
registerRenderer: function (rendererName, rendererFunction) {
registeredRenderers[rendererName] = rendererFunction
},
/**
* @param {String|Function} rendererName/rendererFunction
* @returns {Function} rendererFunction
*/
getRenderer: function (rendererName) {
if (typeof rendererName == 'function'){
return rendererName;
}
if (typeof rendererName != 'string'){
throw Error('Only strings and functions can be passed as "renderer" parameter ');
}
if (!(rendererName in registeredRenderers)) {
throw Error('No editor registered under name "' + rendererName + '"');
}
return registeredRenderers[rendererName];
}
};
})(Handsontable);
/**
* Returns true if keyCode represents a printable character
* @param {Number} keyCode
* @return {Boolean}
*/
Handsontable.helper.isPrintableChar = function (keyCode) {
return ((keyCode == 32) || //space
(keyCode >= 48 && keyCode <= 57) || //0-9
(keyCode >= 96 && keyCode <= 111) || //numpad
(keyCode >= 186 && keyCode <= 192) || //;=,-./`
(keyCode >= 219 && keyCode <= 222) || //[]{}\|"'
keyCode >= 226 || //special chars (229 for Asian chars)
(keyCode >= 65 && keyCode <= 90)); //a-z
};
Handsontable.helper.isMetaKey = function (keyCode) {
var keyCodes = Handsontable.helper.keyCode;
var metaKeys = [
keyCodes.ARROW_DOWN,
keyCodes.ARROW_UP,
keyCodes.ARROW_LEFT,
keyCodes.ARROW_RIGHT,
keyCodes.HOME,
keyCodes.END,
keyCodes.DELETE,
keyCodes.BACKSPACE,
keyCodes.F1,
keyCodes.F2,
keyCodes.F3,
keyCodes.F4,
keyCodes.F5,
keyCodes.F6,
keyCodes.F7,
keyCodes.F8,
keyCodes.F9,
keyCodes.F10,
keyCodes.F11,
keyCodes.F12,
keyCodes.TAB,
keyCodes.PAGE_DOWN,
keyCodes.PAGE_UP,
keyCodes.ENTER,
keyCodes.ESCAPE,
keyCodes.SHIFT,
keyCodes.CAPS_LOCK,
keyCodes.ALT
];
return metaKeys.indexOf(keyCode) != -1;
};
Handsontable.helper.isCtrlKey = function (keyCode) {
var keys = Handsontable.helper.keyCode;
return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1;
};
/**
* Converts a value to string
* @param value
* @return {String}
*/
Handsontable.helper.stringify = function (value) {
switch (typeof value) {
case 'string':
case 'number':
return value + '';
break;
case 'object':
if (value === null) {
return '';
}
else {
return value.toString();
}
break;
case 'undefined':
return '';
break;
default:
return value.toString();
}
};
/**
* Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc
* @param index
* @returns {String}
*/
Handsontable.helper.spreadsheetColumnLabel = function (index) {
var dividend = index + 1;
var columnLabel = '';
var modulo;
while (dividend > 0) {
modulo = (dividend - 1) % 26;
columnLabel = String.fromCharCode(65 + modulo) + columnLabel;
dividend = parseInt((dividend - modulo) / 26, 10);
}
return columnLabel;
};
/**
* Checks if value of n is a numeric one
* http://jsperf.com/isnan-vs-isnumeric/4
* @param n
* @returns {boolean}
*/
Handsontable.helper.isNumeric = function (n) {
var t = typeof n;
return t == 'number' ? !isNaN(n) && isFinite(n) :
t == 'string' ? !n.length ? false :
n.length == 1 ? /\d/.test(n) :
/^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) :
t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false;
};
Handsontable.helper.isArray = function (obj) {
return Object.prototype.toString.call(obj).match(/array/i) !== null;
};
/**
* Checks if child is a descendant of given parent node
* http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another
* @param parent
* @param child
* @returns {boolean}
*/
Handsontable.helper.isDescendant = function (parent, child) {
var node = child.parentNode;
while (node != null) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
};
/**
* Generates a random hex string. Used as namespace for Handsontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
Handsontable.helper.randomString = function () {
return walkontableRandomString();
};
/**
* Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`.
* Creates temporary dummy function to call it as constructor.
* Described in ticket: https://github.com/handsontable/jquery-handsontable/pull/516
* @param {Object} Child child class
* @param {Object} Parent parent class
* @return {Object} extended Child
*/
Handsontable.helper.inherit = function (Child, Parent) {
Parent.prototype.constructor = Parent;
Child.prototype = new Parent();
Child.prototype.constructor = Child;
return Child;
};
/**
* Perform shallow extend of a target object with extension's own properties
* @param {Object} target An object that will receive the new properties
* @param {Object} extension An object containing additional properties to merge into the target
*/
Handsontable.helper.extend = function (target, extension) {
for (var i in extension) {
if (extension.hasOwnProperty(i)) {
target[i] = extension[i];
}
}
};
Handsontable.helper.getPrototypeOf = function (obj) {
var prototype;
if(typeof obj.__proto__ == "object"){
prototype = obj.__proto__;
} else {
var oldConstructor,
constructor = obj.constructor;
if (typeof obj.constructor == "function") {
oldConstructor = constructor;
if (delete obj.constructor){
constructor = obj.constructor; // get real constructor
obj.constructor = oldConstructor; // restore constructor
}
}
prototype = constructor ? constructor.prototype : null; // needed for IE
}
return prototype;
};
/**
* Factory for columns constructors.
* @param {Object} GridSettings
* @param {Array} conflictList
* @return {Object} ColumnSettings
*/
Handsontable.helper.columnFactory = function (GridSettings, conflictList) {
function ColumnSettings () {}
Handsontable.helper.inherit(ColumnSettings, GridSettings);
// Clear conflict settings
for (var i = 0, len = conflictList.length; i < len; i++) {
ColumnSettings.prototype[conflictList[i]] = void 0;
}
return ColumnSettings;
};
Handsontable.helper.translateRowsToColumns = function (input) {
var i
, ilen
, j
, jlen
, output = []
, olen = 0;
for (i = 0, ilen = input.length; i < ilen; i++) {
for (j = 0, jlen = input[i].length; j < jlen; j++) {
if (j == olen) {
output.push([]);
olen++;
}
output[j].push(input[i][j])
}
}
return output;
};
Handsontable.helper.to2dArray = function (arr) {
var i = 0
, ilen = arr.length;
while (i < ilen) {
arr[i] = [arr[i]];
i++;
}
};
Handsontable.helper.extendArray = function (arr, extension) {
var i = 0
, ilen = extension.length;
while (i < ilen) {
arr.push(extension[i]);
i++;
}
};
/**
* Determines if the given DOM element is an input field.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isInput = function (element) {
var inputs = ['INPUT', 'SELECT', 'TEXTAREA'];
return inputs.indexOf(element.nodeName) > -1;
}
/**
* Determines if the given DOM element is an input field placed OUTSIDE of HOT.
* Notice: By 'input' we mean input, textarea and select nodes
* @param element - DOM element
* @returns {boolean}
*/
Handsontable.helper.isOutsideInput = function (element) {
return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1;
};
Handsontable.helper.keyCode = {
MOUSE_LEFT: 1,
MOUSE_RIGHT: 3,
MOUSE_MIDDLE: 2,
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
END: 35,
ENTER: 13,
ESCAPE: 27,
CONTROL_LEFT: 91,
COMMAND_LEFT: 17,
COMMAND_RIGHT: 93,
ALT: 18,
HOME: 36,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
SPACE: 32,
SHIFT: 16,
CAPS_LOCK: 20,
TAB: 9,
ARROW_RIGHT: 39,
ARROW_LEFT: 37,
ARROW_UP: 38,
ARROW_DOWN: 40,
F1: 112,
F2: 113,
F3: 114,
F4: 115,
F5: 116,
F6: 117,
F7: 118,
F8: 119,
F9: 120,
F10: 121,
F11: 122,
F12: 123,
A: 65,
X: 88,
C: 67,
V: 86
};
/**
* Determines whether given object is a plain Object.
* Note: String and Array are not plain Objects
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isObject = function (obj) {
return Object.prototype.toString.call(obj) == '[object Object]';
};
/**
* Determines whether given object is an Array.
* Note: String is not an Array
* @param {*} obj
* @returns {boolean}
*/
Handsontable.helper.isArray = function(obj){
return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]';
};
Handsontable.helper.pivot = function (arr) {
var pivotedArr = [];
if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){
return pivotedArr;
}
var rowCount = arr.length;
var colCount = arr[0].length;
for(var i = 0; i < rowCount; i++){
for(var j = 0; j < colCount; j++){
if(!pivotedArr[j]){
pivotedArr[j] = [];
}
pivotedArr[j][i] = arr[i][j];
}
}
return pivotedArr;
};
Handsontable.helper.proxy = function (fun, context) {
return function () {
return fun.apply(context, arguments);
};
};
/**
* Factory that produces a function for searching methods (or any properties) which could be defined directly in
* table configuration or implicitly, within cell type definition.
*
* For example: renderer can be defined explicitly using "renderer" property in column configuration or it can be
* defined implicitly using "type" property.
*
* Methods/properties defined explicitly always takes precedence over those defined through "type".
*
* If the method/property is not found in an object, searching is continued recursively through prototype chain, until
* it reaches the Object.prototype.
*
*
* @param methodName {String} name of the method/property to search (i.e. 'renderer', 'validator', 'copyable')
* @param allowUndefined {Boolean} [optional] if false, the search is continued if methodName has not been found in cell "type"
* @returns {Function}
*/
Handsontable.helper.cellMethodLookupFactory = function (methodName, allowUndefined) {
allowUndefined = typeof allowUndefined == 'undefined' ? true : allowUndefined;
return function cellMethodLookup (row, col) {
return (function getMethodFromProperties(properties) {
if (!properties){
return; //method not found
}
else if (properties.hasOwnProperty(methodName) && properties[methodName] !== void 0) { //check if it is own and is not empty
return properties[methodName]; //method defined directly
} else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty
var type;
if(typeof properties.type != 'string' ){
throw new Error('Cell type must be a string ');
}
type = translateTypeNameToObject(properties.type);
if (type.hasOwnProperty(methodName)) {
return type[methodName]; //method defined in type.
} else if (allowUndefined) {
return; //method does not defined in type (eg. validator), returns undefined
}
}
return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties));
})(typeof row == 'number' ? this.getCellMeta(row, col) : row);
};
function translateTypeNameToObject(typeName) {
var type = Handsontable.cellTypes[typeName];
if(typeof type == 'undefined'){
throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes');
}
return type;
}
};
Handsontable.helper.toString = function (obj) {
return '' + obj;
};
(function (Handsontable) {
'use strict';
/**
* Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names
* TODO refactor arguments of methods getRange, getText to be numbers (not objects)
* TODO remove priv, GridSettings from object constructor
*
* @param instance
* @param priv
* @param GridSettings
* @constructor
*/
Handsontable.DataMap = function (instance, priv, GridSettings) {
this.instance = instance;
this.priv = priv;
this.GridSettings = GridSettings;
this.dataSource = this.instance.getSettings().data;
if (this.dataSource[0]) {
this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]);
}
else {
this.duckSchema = {};
}
this.createMap();
};
Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1;
Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2;
Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) {
var schema;
if ($.isPlainObject(obj)) {
schema = {};
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
if ($.isPlainObject(obj[i])) {
schema[i] = this.recursiveDuckSchema(obj[i]);
}
else {
schema[i] = null;
}
}
}
}
else {
schema = [];
}
return schema;
};
Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) {
var prop, i;
if (typeof lastCol === 'undefined') {
lastCol = 0;
parent = '';
}
if ($.isPlainObject(schema)) {
for (i in schema) {
if (schema.hasOwnProperty(i)) {
if (schema[i] === null) {
prop = parent + i;
this.colToPropCache.push(prop);
this.propToColCache.set(prop, lastCol);
lastCol++;
}
else {
lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.');
}
}
}
}
return lastCol;
};
Handsontable.DataMap.prototype.createMap = function () {
if (typeof this.getSchema() === "undefined") {
throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`");
}
var i, ilen, schema = this.getSchema();
this.colToPropCache = [];
this.propToColCache = new MultiMap();
var columns = this.instance.getSettings().columns;
if (columns) {
for (i = 0, ilen = columns.length; i < ilen; i++) {
if (typeof columns[i].data != 'undefined'){
this.colToPropCache[i] = columns[i].data;
this.propToColCache.set(columns[i].data, i);
}
}
}
else {
this.recursiveDuckColumns(schema);
}
};
Handsontable.DataMap.prototype.colToProp = function (col) {
col = Handsontable.hooks.execute(this.instance, 'modifyCol', col);
if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') {
return this.colToPropCache[col];
}
else {
return col;
}
};
Handsontable.DataMap.prototype.propToCol = function (prop) {
var col;
if (typeof this.propToColCache.get(prop) !== 'undefined') {
col = this.propToColCache.get(prop);
} else {
col = prop;
}
col = Handsontable.hooks.execute(this.instance, 'modifyCol', col);
return col;
};
Handsontable.DataMap.prototype.getSchema = function () {
var schema = this.instance.getSettings().dataSchema;
if (schema) {
if (typeof schema === 'function') {
return schema();
}
return schema;
}
return this.duckSchema;
};
/**
* Creates row at the bottom of the data array
* @param {Number} [index] Optional. Index of the row before which the new row will be inserted
*/
Handsontable.DataMap.prototype.createRow = function (index, amount, createdAutomatically) {
var row
, colCount = this.instance.countCols()
, numberOfCreatedRows = 0
, currentIndex;
if (!amount) {
amount = 1;
}
if (typeof index !== 'number' || index >= this.instance.countRows()) {
index = this.instance.countRows();
}
currentIndex = index;
var maxRows = this.instance.getSettings().maxRows;
while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) {
if (this.instance.dataType === 'array') {
row = [];
for (var c = 0; c < colCount; c++) {
row.push(null);
}
}
else if (this.instance.dataType === 'function') {
row = this.instance.getSettings().dataSchema(index);
}
else {
row = $.extend(true, {}, this.getSchema());
}
if (index === this.instance.countRows()) {
this.dataSource.push(row);
}
else {
this.dataSource.splice(index, 0, row);
}
numberOfCreatedRows++;
currentIndex++;
}
Handsontable.hooks.run(this.instance, 'afterCreateRow', index, numberOfCreatedRows, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedRows;
};
/**
* Creates col at the right of the data array
* @param {Number} [index] Optional. Index of the column before which the new column will be inserted
* * @param {Number} [amount] Optional.
*/
Handsontable.DataMap.prototype.createCol = function (index, amount, createdAutomatically) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("Cannot create new column. When data source in an object, " +
"you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." +
"If you want to be able to add new columns, you have to use array datasource.");
}
var rlen = this.instance.countRows()
, data = this.dataSource
, constructor
, numberOfCreatedCols = 0
, currentIndex;
if (!amount) {
amount = 1;
}
currentIndex = index;
var maxCols = this.instance.getSettings().maxCols;
while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) {
constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts);
if (typeof index !== 'number' || index >= this.instance.countCols()) {
for (var r = 0; r < rlen; r++) {
if (typeof data[r] === 'undefined') {
data[r] = [];
}
data[r].push(null);
}
// Add new column constructor
this.priv.columnSettings.push(constructor);
}
else {
for (var r = 0; r < rlen; r++) {
data[r].splice(currentIndex, 0, null);
}
// Add new column constructor at given index
this.priv.columnSettings.splice(currentIndex, 0, constructor);
}
numberOfCreatedCols++;
currentIndex++;
}
Handsontable.hooks.run(this.instance, 'afterCreateCol', index, numberOfCreatedCols, createdAutomatically);
this.instance.forceFullRender = true; //used when data was changed
return numberOfCreatedCols;
};
/**
* Removes row from the data array
* @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed
* @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed
*/
Handsontable.DataMap.prototype.removeRow = function (index, amount) {
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countRows() + index) % this.instance.countRows();
// We have to map the physical row ids to logical and than perform removing with (possibly) new row id
var logicRows = this.physicalRowsToLogical(index, amount);
var actionWasNotCancelled = Handsontable.hooks.execute(this.instance, 'beforeRemoveRow', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
var newData = data.filter(function (row, index) {
return logicRows.indexOf(index) == -1;
});
data.length = 0;
Array.prototype.push.apply(data, newData);
Handsontable.hooks.run(this.instance, 'afterRemoveRow', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Removes column from the data array
* @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed
* @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed
*/
Handsontable.DataMap.prototype.removeCol = function (index, amount) {
if (this.instance.dataType === 'object' || this.instance.getSettings().columns) {
throw new Error("cannot remove column with object data source or columns option specified");
}
if (!amount) {
amount = 1;
}
if (typeof index !== 'number') {
index = -amount;
}
index = (this.instance.countCols() + index) % this.instance.countCols();
var actionWasNotCancelled = Handsontable.hooks.execute(this.instance, 'beforeRemoveCol', index, amount);
if (actionWasNotCancelled === false) {
return;
}
var data = this.dataSource;
for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) {
data[r].splice(index, amount);
}
this.priv.columnSettings.splice(index, amount);
Handsontable.hooks.run(this.instance, 'afterRemoveCol', index, amount);
this.instance.forceFullRender = true; //used when data was changed
};
/**
* Add / removes data from the column
* @param {Number} col Index of column in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var colData = this.instance.getDataAtCol(col);
var removed = colData.slice(index, index + amount);
var after = colData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
Handsontable.helper.to2dArray(elements);
this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol');
return removed;
};
/**
* Add / removes data from the row
* @param {Number} row Index of row in which do you want to do splice.
* @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end
* @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed
* param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array
*/
Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) {
var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : [];
var rowData = this.instance.getDataAtRow(row);
var removed = rowData.slice(index, index + amount);
var after = rowData.slice(index + amount);
Handsontable.helper.extendArray(elements, after);
var i = 0;
while (i < amount) {
elements.push(null); //add null in place of removed elements
i++;
}
this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow');
return removed;
};
/**
* Returns single value from the data array
* @param {Number} row
* @param {Number} prop
*/
Handsontable.DataMap.prototype.get = function (row, prop) {
row = Handsontable.hooks.execute(this.instance, 'modifyRow', row);
if (typeof prop === 'string' && prop.indexOf('.') > -1) {
var sliced = prop.split(".");
var out = this.dataSource[row];
if (!out) {
return null;
}
for (var i = 0, ilen = sliced.length; i < ilen; i++) {
out = out[sliced[i]];
if (typeof out === 'undefined') {
return null;
}
}
return out;
}
else if (typeof prop === 'function') {
/**
* allows for interacting with complex structures, for example
* d3/jQuery getter/setter properties:
*
* {columns: [{
* data: function(row, value){
* if(arguments.length === 1){
* return row.property();
* }
* row.property(value);
* }
* }]}
*/
return prop(this.dataSource.slice(
row,
row + 1
)[0]);
}
else {
return this.dataSource[row] ? this.dataSource[row][prop] : null;
}
};
var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable', false);
/**
* Returns single value from the data array (intended for clipboard copy to an external application)
* @param {Number} row
* @param {Number} prop
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyable = function (row, prop) {
if (copyableLookup.call(this.instance, row, this.propToCol(prop))) {
return this.get(row, prop);
}
return '';
};
/**
* Saves single value to the data array
* @param {Number} row
* @param {Number} prop
* @param {String} value
* @param {String} [source] Optional. Source of hook runner.
*/
Handsontable.DataMap.prototype.set = function (row, prop, value, source) {
row = Handsontable.hooks.execute(this.instance, 'modifyRow', row, source || "datamapGet");
if (typeof prop === 'string' && prop.indexOf('.') > -1) {
var sliced = prop.split(".");
var out = this.dataSource[row];
for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) {
out = out[sliced[i]];
}
out[sliced[i]] = value;
}
else if (typeof prop === 'function') {
/* see the `function` handler in `get` */
prop(this.dataSource.slice(
row,
row + 1
)[0], value);
}
else {
this.dataSource[row][prop] = value;
}
};
/**
* This ridiculous piece of code maps rows Id that are present in table data to those displayed for user.
* The trick is, the physical row id (stored in settings.data) is not necessary the same
* as the logical (displayed) row id (e.g. when sorting is applied).
*/
Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) {
var totalRows = this.instance.countRows();
var physicRow = (totalRows + index) % totalRows;
var logicRows = [];
var rowsToRemove = amount;
var row;
while (physicRow < totalRows && rowsToRemove) {
row = Handsontable.hooks.execute(this.instance, 'modifyRow', physicRow);
logicRows.push(row);
rowsToRemove--;
physicRow++;
}
return logicRows;
};
/**
* Clears the data array
*/
Handsontable.DataMap.prototype.clear = function () {
for (var r = 0; r < this.instance.countRows(); r++) {
for (var c = 0; c < this.instance.countCols(); c++) {
this.set(r, this.colToProp(c), '');
}
}
};
/**
* Returns the data array
* @return {Array}
*/
Handsontable.DataMap.prototype.getAll = function () {
return this.dataSource;
};
/**
* Returns data range as array
* @param {Object} start Start selection position
* @param {Object} end End selection position
* @param {Number} destination Destination of datamap.get
* @return {Array}
*/
Handsontable.DataMap.prototype.getRange = function (start, end, destination) {
var r, rlen, c, clen, output = [], row;
var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get;
rlen = Math.max(start.row, end.row);
clen = Math.max(start.col, end.col);
for (r = Math.min(start.row, end.row); r <= rlen; r++) {
row = [];
for (c = Math.min(start.col, end.col); c <= clen; c++) {
row.push(getFn.call(this, r, this.colToProp(c)));
}
output.push(row);
}
return output;
};
/**
* Return data as text (tab separated columns)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER));
};
/**
* Return data as copyable text (tab separated columns intended for clipboard copy to an external application)
* @param {Object} start (Optional) Start selection position
* @param {Object} end (Optional) End selection position
* @return {String}
*/
Handsontable.DataMap.prototype.getCopyableText = function (start, end) {
return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR));
};
})(Handsontable);
(function (Handsontable) {
'use strict';
/*
Adds appropriate CSS class to table cell, based on cellProperties
*/
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
if (cellProperties.className) {
TD.className = cellProperties.className;
}
if (cellProperties.readOnly) {
Handsontable.Dom.addClass(TD, cellProperties.readOnlyCellClassName);
}
if (cellProperties.valid === false && cellProperties.invalidCellClassName) {
Handsontable.Dom.addClass(TD, cellProperties.invalidCellClassName);
}
if (cellProperties.wordWrap === false && cellProperties.noWordWrapClassName) {
Handsontable.Dom.addClass(TD, cellProperties.noWordWrapClassName);
}
if (!value && cellProperties.placeholder) {
Handsontable.Dom.addClass(TD, cellProperties.placeholderCellClassName);
}
}
})(Handsontable);
/**
* Default text renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.cellDecorator.apply(this, arguments);
if (!value && cellProperties.placeholder) {
value = cellProperties.placeholder;
}
var escaped = Handsontable.helper.stringify(value);
if (cellProperties.rendererTemplate) {
Handsontable.Dom.empty(TD);
var TEMPLATE = document.createElement('TEMPLATE');
TEMPLATE.setAttribute('bind', '{{}}');
TEMPLATE.innerHTML = cellProperties.rendererTemplate;
HTMLTemplateElement.decorate(TEMPLATE);
TEMPLATE.model = instance.getDataAtRow(row);
TD.appendChild(TEMPLATE);
}
else {
Handsontable.Dom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
};
//Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility
Handsontable.renderers.TextRenderer = TextRenderer;
Handsontable.renderers.registerRenderer('text', TextRenderer);
})(Handsontable);
(function (Handsontable) {
var clonableWRAPPER = document.createElement('DIV');
clonableWRAPPER.className = 'htAutocompleteWrapper';
var clonableARROW = document.createElement('DIV');
clonableARROW.className = 'htAutocompleteArrow';
clonableARROW.appendChild(document.createTextNode('\u25BC'));
//this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
var wrapTdContentWithWrapper = function(TD, WRAPPER){
WRAPPER.innerHTML = TD.innerHTML;
Handsontable.Dom.empty(TD);
TD.appendChild(WRAPPER);
};
/**
* Autocomplete renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement
var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
TD.appendChild(ARROW);
Handsontable.Dom.addClass(TD, 'htAutocomplete');
if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed
//otherwise empty fields appear borderless in demo/renderers.html (IE)
TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals for a text node
//this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
if (!instance.acArrowListener) {
//not very elegant but easy and fast
instance.acArrowListener = function () {
instance.view.wt.getSetting('onCellDblClick', null, new WalkontableCellCoords(row, col), TD);
};
instance.rootElement.on('mousedown.htAutocompleteArrow', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead
//We need to unbind the listener after the table has been destroyed
instance.addHookOnce('afterDestroy', function () {
this.rootElement.off('mousedown.htAutocompleteArrow');
});
}
};
Handsontable.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer;
Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer);
})(Handsontable);
/**
* Checkbox renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var clonableINPUT = document.createElement('INPUT');
clonableINPUT.className = 'htCheckboxRendererInput';
clonableINPUT.type = 'checkbox';
clonableINPUT.setAttribute('autocomplete', 'off');
var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (typeof cellProperties.checkedTemplate === "undefined") {
cellProperties.checkedTemplate = true;
}
if (typeof cellProperties.uncheckedTemplate === "undefined") {
cellProperties.uncheckedTemplate = false;
}
Handsontable.Dom.empty(TD); //TODO identify under what circumstances this line can be removed
var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement
if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) {
INPUT.checked = true;
TD.appendChild(INPUT);
}
else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) {
TD.appendChild(INPUT);
}
else if (value === null) { //default value
INPUT.className += ' noValue';
TD.appendChild(INPUT);
}
else {
Handsontable.Dom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
var $input = $(INPUT);
if (cellProperties.readOnly) {
$input.on('click', function (event) {
event.preventDefault();
});
}
else {
$input.on('mousedown', function (event) {
event.stopPropagation(); //otherwise can confuse cell mousedown handler
});
$input.on('mouseup', function (event) {
event.stopPropagation(); //otherwise can confuse cell dblclick handler
});
$input.on('change', function(){
if (this.checked) {
instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate);
}
else {
instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate);
}
});
}
if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){
instance.CheckboxRenderer = {
beforeKeyDownHookBound : true
};
instance.addHook('beforeKeyDown', function(event){
if(event.keyCode == Handsontable.helper.keyCode.SPACE){
var cell, checkbox, cellProperties;
var selRange = instance.getSelectedRange();
var topLeft = selRange.getTopLeftCorner();
var bottomRight = selRange.getBottomRightCorner();
for(var row = topLeft.row; row <= bottomRight.row; row++ ){
for(var col = topLeft.col; col <= bottomRight.col; col++){
cell = instance.getCell(row, col);
cellProperties = instance.getCellMeta(row, col);
checkbox = cell.querySelectorAll('input[type=checkbox]');
if(checkbox.length > 0 && !cellProperties.readOnly){
if(!event.isImmediatePropagationStopped()){
event.stopImmediatePropagation();
event.preventDefault();
}
for(var i = 0, len = checkbox.length; i < len; i++){
checkbox[i].checked = !checkbox[i].checked;
$(checkbox[i]).trigger('change');
}
}
}
}
}
});
}
};
Handsontable.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.CheckboxRenderer = CheckboxRenderer;
Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer);
})(Handsontable);
/**
* Numeric cell renderer
* @param {Object} instance Handsontable instance
* @param {Element} TD Table cell where to render
* @param {Number} row
* @param {Number} col
* @param {String|Number} prop Row object property name
* @param value Value to render (remember to escape unsafe HTML before inserting to DOM!)
* @param {Object} cellProperties Cell properites (shared by cell renderer and editor)
*/
(function (Handsontable) {
'use strict';
var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
if (Handsontable.helper.isNumeric(value)) {
if (typeof cellProperties.language !== 'undefined') {
numeral.language(cellProperties.language)
}
value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/
Handsontable.Dom.addClass(TD, 'htNumeric');
}
Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties);
};
Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0
Handsontable.renderers.NumericRenderer = NumericRenderer;
Handsontable.renderers.registerRenderer('numeric', NumericRenderer);
})(Handsontable);
(function(Handosntable){
'use strict';
var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) {
Handsontable.renderers.TextRenderer.apply(this, arguments);
value = TD.innerHTML;
var hash;
var hashLength = cellProperties.hashLength || value.length;
var hashSymbol = cellProperties.hashSymbol || '*';
for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol);
Handsontable.Dom.fastInnerHTML(TD, hash);
};
Handosntable.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.PasswordRenderer = PasswordRenderer;
Handosntable.renderers.registerRenderer('password', PasswordRenderer);
})(Handsontable);
(function (Handsontable) {
function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){
Handsontable.renderers.cellDecorator.apply(this, arguments);
Handsontable.Dom.fastInnerHTML(TD, value);
}
Handsontable.renderers.registerRenderer('html', HtmlRenderer);
Handsontable.renderers.HtmlRenderer = HtmlRenderer;
})(Handsontable);
(function (Handsontable) {
'use strict';
Handsontable.EditorState = {
VIRGIN: 'STATE_VIRGIN', //before editing
EDITING: 'STATE_EDITING',
WAITING: 'STATE_WAITING', //waiting for async validation
FINISHED: 'STATE_FINISHED'
};
function BaseEditor(instance) {
this.instance = instance;
this.state = Handsontable.EditorState.VIRGIN;
this._opened = false;
this._closeCallback = null;
this.init();
}
BaseEditor.prototype._fireCallbacks = function(result) {
if(this._closeCallback){
this._closeCallback(result);
this._closeCallback = null;
}
}
BaseEditor.prototype.init = function(){};
BaseEditor.prototype.getValue = function(){
throw Error('Editor getValue() method unimplemented');
};
BaseEditor.prototype.setValue = function(newValue){
throw Error('Editor setValue() method unimplemented');
};
BaseEditor.prototype.open = function(){
throw Error('Editor open() method unimplemented');
};
BaseEditor.prototype.close = function(){
throw Error('Editor close() method unimplemented');
};
BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){
this.TD = td;
this.row = row;
this.col = col;
this.prop = prop;
this.originalValue = originalValue;
this.cellProperties = cellProperties;
this.state = Handsontable.EditorState.VIRGIN;
};
BaseEditor.prototype.extend = function(){
var baseClass = this.constructor;
function Editor(){
baseClass.apply(this, arguments);
}
function inherit(Child, Parent){
function Bridge() {
}
Bridge.prototype = Parent.prototype;
Child.prototype = new Bridge();
Child.prototype.constructor = Child;
return Child;
}
return inherit(Editor, baseClass);
};
BaseEditor.prototype.saveValue = function (val, ctrlDown) {
if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells)
var sel = this.instance.getSelected();
this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit');
}
else {
this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit');
}
};
BaseEditor.prototype.beginEditing = function(initialValue){
if (this.state != Handsontable.EditorState.VIRGIN) {
return;
}
this.instance.view.scrollViewport(new WalkontableCellCoords(this.row, this.col));
this.instance.view.render();
this.state = Handsontable.EditorState.EDITING;
initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue;
this.setValue(Handsontable.helper.stringify(initialValue));
this.open();
this._opened = true;
this.focus();
this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered)
};
BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) {
if (callback) {
var previousCloseCallback = this._closeCallback;
this._closeCallback = function (result) {
if(previousCloseCallback){
previousCloseCallback(result);
}
callback(result);
};
}
if (this.isWaiting()) {
return;
}
if (this.state == Handsontable.EditorState.VIRGIN) {
var that = this;
setTimeout(function () {
that._fireCallbacks(true);
});
return;
}
if (this.state == Handsontable.EditorState.EDITING) {
if (restoreOriginalValue) {
this.cancelChanges();
return;
}
var val = [
[String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js
];
this.state = Handsontable.EditorState.WAITING;
this.saveValue(val, ctrlDown);
if(this.instance.getCellValidator(this.cellProperties)){
var that = this;
this.instance.addHookOnce('afterValidate', function (result) {
that.state = Handsontable.EditorState.FINISHED;
that.discardEditor(result);
});
} else {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor(true);
}
}
};
BaseEditor.prototype.cancelChanges = function () {
this.state = Handsontable.EditorState.FINISHED;
this.discardEditor();
};
BaseEditor.prototype.discardEditor = function (result) {
if (this.state !== Handsontable.EditorState.FINISHED) {
return;
}
if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed
this.instance.selectCell(this.row, this.col);
this.focus();
this.state = Handsontable.EditorState.EDITING;
this._fireCallbacks(false);
}
else {
this.close();
this._opened = false;
this.state = Handsontable.EditorState.VIRGIN;
this._fireCallbacks(true);
}
};
BaseEditor.prototype.isOpened = function(){
return this._opened;
};
BaseEditor.prototype.isWaiting = function () {
return this.state === Handsontable.EditorState.WAITING;
};
Handsontable.editors.BaseEditor = BaseEditor;
})(Handsontable);
(function(Handsontable){
var TextEditor = Handsontable.editors.BaseEditor.prototype.extend();
TextEditor.prototype.init = function(){
this.createElements();
this.bindEvents();
};
TextEditor.prototype.getValue = function(){
return this.TEXTAREA.value
};
TextEditor.prototype.setValue = function(newValue){
this.TEXTAREA.value = newValue;
};
var onBeforeKeyDown = function onBeforeKeyDown(event){
var instance = this;
var that = instance.getActiveEditor();
var keyCodes = Handsontable.helper.keyCode;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
//Process only events that have been fired in the editor
if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){
return;
}
if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) {
//when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea
event.stopImmediatePropagation();
return;
}
switch (event.keyCode) {
case keyCodes.ARROW_RIGHT:
if (Handsontable.Dom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ARROW_LEFT: /* arrow left */
if (Handsontable.Dom.getCaretPosition(that.TEXTAREA) !== 0) {
event.stopImmediatePropagation();
}
break;
case keyCodes.ENTER:
var selected = that.instance.getSelected();
var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]);
if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line
if(that.isOpened()){
that.setValue(that.getValue() + '\n');
that.focus();
} else {
that.beginEditing(that.originalValue + '\n')
}
event.stopImmediatePropagation();
}
event.preventDefault(); //don't add newline to field
break;
case keyCodes.A:
case keyCodes.X:
case keyCodes.C:
case keyCodes.V:
if(ctrlDown){
event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context)
break;
}
case keyCodes.BACKSPACE:
case keyCodes.DELETE:
case keyCodes.HOME:
case keyCodes.END:
event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context)
break;
}
};
TextEditor.prototype.open = function(){
this.refreshDimensions(); //need it instantly, to prevent https://github.com/handsontable/jquery-handsontable/issues/348
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.close = function(){
this.textareaParentStyle.display = 'none';
if (document.activeElement === this.TEXTAREA) {
this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose
}
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
TextEditor.prototype.focus = function(){
this.TEXTAREA.focus();
Handsontable.Dom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length);
};
TextEditor.prototype.createElements = function () {
this.$body = $(document.body);
this.TEXTAREA = document.createElement('TEXTAREA');
this.$textarea = $(this.TEXTAREA);
Handsontable.Dom.addClass(this.TEXTAREA, 'handsontableInput');
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.TEXTAREA_PARENT = document.createElement('DIV');
Handsontable.Dom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder');
this.textareaParentStyle = this.TEXTAREA_PARENT.style;
this.textareaParentStyle.top = 0;
this.textareaParentStyle.left = 0;
this.textareaParentStyle.display = 'none';
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT);
var that = this;
Handsontable.hooks.add('afterRender', function () {
that.instance._registerTimeout('refresh_editor_dimensions', function () {
that.refreshDimensions();
}, 0);
});
};
TextEditor.prototype.refreshDimensions = function () {
if (this.state !== Handsontable.EditorState.EDITING) {
return;
}
///start prepare textarea position
this.TD = this.instance.getCell(this.row, this.col);
if (!this.TD) {
//TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited
return;
}
var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport
var currentOffset = Handsontable.Dom.offset(this.TD);
var containerOffset = Handsontable.Dom.offset(this.instance.rootElement[0]);
var editTop = currentOffset.top - containerOffset.top - 1;
var editLeft = currentOffset.left - containerOffset.left - 1;
var settings = this.instance.getSettings();
var rowHeadersCount = settings.rowHeaders === false ? 0 : 1;
var colHeadersCount = settings.colHeaders === false ? 0 : 1;
if (editTop < 0) {
editTop = 0;
}
if (editLeft < 0) {
editLeft = 0;
}
if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) {
editTop += 1;
}
if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) {
editLeft += 1;
}
this.textareaParentStyle.top = editTop + 'px';
this.textareaParentStyle.left = editLeft + 'px';
///end prepare textarea position
var cellTopOffset = this.TD.offsetTop,
cellLeftOffset = this.TD.offsetLeft - this.instance.view.wt.wtScrollbars.horizontal.getScrollPosition();
var width = $td.width()
, maxWidth = this.instance.view.maximumVisibleElementWidth(cellLeftOffset) - 10 //10 is TEXTAREAs border and padding
, height = $td.outerHeight() - 4
, maxHeight = this.instance.view.maximumVisibleElementHeight(cellTopOffset)-2; //10 is TEXTAREAs border and padding
if (parseInt($td.css('border-top-width'), 10) > 0) {
height -= 1;
}
if (parseInt($td.css('border-left-width'), 10) > 0) {
if (rowHeadersCount > 0) {
width -= 1;
}
}
//in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize
this.$textarea.autoResize({
minHeight: Math.min(height, maxHeight),
maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
minWidth: Math.min(width, maxWidth),
maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar)
animate: false,
extraSpace: 0
});
this.textareaParentStyle.display = 'block';
};
TextEditor.prototype.bindEvents = function () {
this.$textarea.on('cut.editor', function (event) {
event.stopPropagation();
});
this.$textarea.on('paste.editor', function (event) {
event.stopPropagation();
});
};
Handsontable.editors.TextEditor = TextEditor;
Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor);
})(Handsontable);
(function(Handsontable){
//Blank editor, because all the work is done by renderer
var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend();
CheckboxEditor.prototype.beginEditing = function () {
var checkbox = this.TD.querySelector('input[type="checkbox"]');
if (checkbox) {
$(checkbox).trigger('click');
}
};
CheckboxEditor.prototype.finishEditing = function () {};
CheckboxEditor.prototype.init = function () {};
CheckboxEditor.prototype.open = function () {};
CheckboxEditor.prototype.close = function () {};
CheckboxEditor.prototype.getValue = function () {};
CheckboxEditor.prototype.setValue = function () {};
CheckboxEditor.prototype.focus = function () {};
Handsontable.editors.CheckboxEditor = CheckboxEditor;
Handsontable.editors.registerEditor('checkbox', CheckboxEditor);
})(Handsontable);
(function (Handsontable) {
var DateEditor = Handsontable.editors.TextEditor.prototype.extend();
DateEditor.prototype.init = function () {
if (!$.datepicker) {
throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?");
}
Handsontable.editors.TextEditor.prototype.init.apply(this, arguments);
this.isCellEdited = false;
var that = this;
this.instance.addHook('afterDestroy', function () {
that.destroyElements();
})
};
DateEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.datePicker = document.createElement('DIV');
Handsontable.Dom.addClass(this.datePicker, 'htDatepickerHolder');
this.datePickerStyle = this.datePicker.style;
this.datePickerStyle.position = 'absolute';
this.datePickerStyle.top = 0;
this.datePickerStyle.left = 0;
this.datePickerStyle.zIndex = 99;
document.body.appendChild(this.datePicker);
this.$datePicker = $(this.datePicker);
var that = this;
var defaultOptions = {
dateFormat: "yy-mm-dd",
showButtonPanel: true,
changeMonth: true,
changeYear: true,
onSelect: function (dateStr) {
that.setValue(dateStr);
that.finishEditing(false);
}
};
this.$datePicker.datepicker(defaultOptions);
/**
* Prevent recognizing clicking on jQuery Datepicker as clicking outside of table
*/
this.$datePicker.on('mousedown', function (event) {
event.stopPropagation();
});
this.hideDatepicker();
};
DateEditor.prototype.destroyElements = function () {
this.$datePicker.datepicker('destroy');
this.$datePicker.remove();
};
DateEditor.prototype.open = function () {
Handsontable.editors.TextEditor.prototype.open.call(this);
this.showDatepicker();
};
DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
this.hideDatepicker();
Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
DateEditor.prototype.showDatepicker = function () {
var $td = $(this.TD);
var offset = $td.offset();
this.datePickerStyle.top = (offset.top + $td.height()) + 'px';
this.datePickerStyle.left = offset.left + 'px';
var dateOptions = {
defaultDate: this.originalValue || void 0
};
$.extend(dateOptions, this.cellProperties);
this.$datePicker.datepicker("option", dateOptions);
if (this.originalValue) {
this.$datePicker.datepicker("setDate", this.originalValue);
}
this.datePickerStyle.display = 'block';
};
DateEditor.prototype.hideDatepicker = function () {
this.datePickerStyle.display = 'none';
};
Handsontable.editors.DateEditor = DateEditor;
Handsontable.editors.registerEditor('date', DateEditor);
})(Handsontable);
/**
* This is inception. Using Handsontable as Handsontable editor
*/
(function (Handsontable) {
"use strict";
var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend();
HandsontableEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
var DIV = document.createElement('DIV');
DIV.className = 'handsontableEditor';
this.TEXTAREA_PARENT.appendChild(DIV);
this.$htContainer = $(DIV);
this.$htContainer.handsontable();
};
HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) {
Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments);
var parent = this;
var options = {
startRows: 0,
startCols: 0,
minRows: 0,
minCols: 0,
className: 'listbox',
copyPaste: false,
cells: function () {
return {
readOnly: true
}
},
fillHandle: false,
afterOnCellMouseDown: function () {
var value = this.getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
},
beforeOnKeyDown: function (event) {
var instance = this;
switch (event.keyCode) {
case Handsontable.helper.keyCode.ESCAPE:
parent.instance.destroyEditor(true);
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ENTER: //enter
var sel = instance.getSelected();
var value = this.getDataAtCell(sel[0], sel[1]);
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
parent.setValue(value);
}
parent.instance.destroyEditor();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){
instance.deselectCell();
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
break;
}
}
};
if (this.cellProperties.handsontable) {
options = $.extend(options, cellProperties.handsontable);
}
this.$htContainer.handsontable('destroy');
this.$htContainer.handsontable(options);
};
var onBeforeKeyDown = function (event) {
if (event.isImmediatePropagationStopped()) {
return;
}
var editor = this.getActiveEditor();
var innerHOT = editor.$htContainer.handsontable('getInstance');
if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) {
if (!innerHOT.getSelected()){
innerHOT.selectCell(0, 0);
} else {
var selectedRow = innerHOT.getSelected()[0];
var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow;
innerHOT.selectCell(rowToSelect, 0);
}
event.preventDefault();
event.stopImmediatePropagation();
}
};
HandsontableEditor.prototype.open = function () {
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
Handsontable.editors.TextEditor.prototype.open.apply(this, arguments);
this.$htContainer.handsontable('render');
if (this.cellProperties.strict) {
this.$htContainer.handsontable('selectCell', 0, 0);
this.$textarea[0].style.visibility = 'hidden';
} else {
this.$htContainer.handsontable('deselectCell');
this.$textarea[0].style.visibility = 'visible';
}
Handsontable.Dom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length);
};
HandsontableEditor.prototype.close = function () {
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
this.instance.listen();
Handsontable.editors.TextEditor.prototype.close.apply(this, arguments);
};
HandsontableEditor.prototype.focus = function () {
this.instance.listen();
Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments);
};
HandsontableEditor.prototype.beginEditing = function (initialValue) {
var onBeginEditing = this.instance.getSettings().onBeginEditing;
if (onBeginEditing && onBeginEditing() === false) {
return;
}
Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments);
};
HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) {
if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor
this.instance.listen(); //return the focus to the parent HOT instance
}
if (this.$htContainer.handsontable('getSelected')) {
var value = this.$htContainer.handsontable('getInstance').getValue();
if (value !== void 0) { //if the value is undefined then it means we don't want to set the value
this.setValue(value);
}
}
return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments);
};
Handsontable.editors.HandsontableEditor = HandsontableEditor;
Handsontable.editors.registerEditor('handsontable', HandsontableEditor);
})(Handsontable);
(function (Handsontable) {
var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend();
AutocompleteEditor.prototype.init = function () {
Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments);
this.$htContainer.handsontable('updateSettings', {height: this.getDropdownHeight()});
this.query = null;
this.choices = [];
};
AutocompleteEditor.prototype.createElements = function(){
Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments);
this.$htContainer.addClass('autocompleteEditor');
};
AutocompleteEditor.prototype.bindEvents = function(){
var that = this;
this.$textarea.on('keydown.autocompleteEditor', function(event){
if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){
setTimeout(function () {
that.queryChoices(that.$textarea.val());
});
} else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){
that.$htContainer.handsontable('deselectCell');
}
});
this.$htContainer.on('mouseleave', function () {
if(that.cellProperties.strict === true){
that.highlightBestMatchingChoice();
}
});
this.$htContainer.on('mouseenter', function () {
that.$htContainer.handsontable('deselectCell');
});
Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments);
};
var onBeforeKeyDownInner;
AutocompleteEditor.prototype.open = function () {
Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments);
this.$textarea[0].style.visibility = 'visible';
this.focus();
var choicesListHot = this.$htContainer.handsontable('getInstance');
var that = this;
choicesListHot.updateSettings({
'colWidths': [Handsontable.Dom.outerWidth(this.TEXTAREA) - 2],
afterRenderer: function (TD, row, col, prop, value) {
var caseSensitive = this.getCellMeta(row, col).filteringCaseSensitive === true;
var indexOfMatch = caseSensitive ? value.indexOf(this.query) : value.toLowerCase().indexOf(that.query.toLowerCase());
if(indexOfMatch != -1){
var match = value.substr(indexOfMatch, that.query.length);
TD.innerHTML = value.replace(match, '<strong>' + match + '</strong>');
}
}
});
onBeforeKeyDownInner = function (event) {
var instance = this;
if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){
if (instance.getSelected() && instance.getSelected()[0] == 0){
if(!parent.cellProperties.strict){
instance.deselectCell();
}
parent.instance.listen();
parent.focus();
event.preventDefault();
event.stopImmediatePropagation();
}
}
};
choicesListHot.addHook('beforeKeyDown', onBeforeKeyDownInner);
this.queryChoices(this.TEXTAREA.value);
};
AutocompleteEditor.prototype.close = function () {
this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner);
Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments);
};
AutocompleteEditor.prototype.queryChoices = function(query){
this.query = query;
if (typeof this.cellProperties.source == 'function'){
var that = this;
this.cellProperties.source(query, function(choices){
that.updateChoicesList(choices)
});
} else if (Handsontable.helper.isArray(this.cellProperties.source)) {
var choices;
if(!query || this.cellProperties.filter === false){
choices = this.cellProperties.source;
} else {
var filteringCaseSensitive = this.cellProperties.filteringCaseSensitive === true;
var lowerCaseQuery = query.toLowerCase();
choices = this.cellProperties.source.filter(function(choice){
if (filteringCaseSensitive) {
return choice.indexOf(query) != -1;
} else {
return choice.toLowerCase().indexOf(lowerCaseQuery) != -1;
}
});
}
this.updateChoicesList(choices)
} else {
this.updateChoicesList([]);
}
};
AutocompleteEditor.prototype.updateChoicesList = function (choices) {
this.choices = choices;
this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices]));
if(this.cellProperties.strict === true){
this.highlightBestMatchingChoice();
}
this.focus();
};
AutocompleteEditor.prototype.highlightBestMatchingChoice = function () {
var bestMatchingChoice = this.findBestMatchingChoice();
if ( typeof bestMatchingChoice == 'undefined' && this.cellProperties.allowInvalid === false){
bestMatchingChoice = 0;
}
if(typeof bestMatchingChoice == 'undefined'){
this.$htContainer.handsontable('deselectCell');
} else {
this.$htContainer.handsontable('selectCell', bestMatchingChoice, 0);
}
};
AutocompleteEditor.prototype.findBestMatchingChoice = function(){
var bestMatch = {};
var valueLength = this.getValue().length;
var currentItem;
var indexOfValue;
var charsLeft;
for(var i = 0, len = this.choices.length; i < len; i++){
currentItem = this.choices[i];
if(valueLength > 0){
indexOfValue = currentItem.indexOf(this.getValue())
} else {
indexOfValue = currentItem === this.getValue() ? 0 : -1;
}
if(indexOfValue == -1) continue;
charsLeft = currentItem.length - indexOfValue - valueLength;
if( typeof bestMatch.indexOfValue == 'undefined'
|| bestMatch.indexOfValue > indexOfValue
|| ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){
bestMatch.indexOfValue = indexOfValue;
bestMatch.charsLeft = charsLeft;
bestMatch.index = i;
}
}
return bestMatch.index;
};
AutocompleteEditor.prototype.getDropdownHeight = function(){
//return 10 * this.$htContainer.handsontable('getInstance').getRowHeight(0);
//sorry, we can't measure row height before it was rendered. Let's use fixed height for now
return 230;
};
Handsontable.editors.AutocompleteEditor = AutocompleteEditor;
Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor);
})(Handsontable);
(function(Handsontable){
var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend();
PasswordEditor.prototype.createElements = function () {
Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments);
this.TEXTAREA = document.createElement('input');
this.TEXTAREA.setAttribute('type', 'password');
this.TEXTAREA.className = 'handsontableInput';
this.textareaStyle = this.TEXTAREA.style;
this.textareaStyle.width = 0;
this.textareaStyle.height = 0;
this.$textarea = $(this.TEXTAREA);
Handsontable.Dom.empty(this.TEXTAREA_PARENT);
this.TEXTAREA_PARENT.appendChild(this.TEXTAREA);
};
Handsontable.editors.PasswordEditor = PasswordEditor;
Handsontable.editors.registerEditor('password', PasswordEditor);
})(Handsontable);
(function (Handsontable) {
var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend();
SelectEditor.prototype.init = function(){
this.select = document.createElement('SELECT');
Handsontable.Dom.addClass(this.select, 'htSelectEditor');
this.select.style.display = 'none';
this.instance.rootElement[0].appendChild(this.select);
};
SelectEditor.prototype.prepare = function(){
Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments);
var selectOptions = this.cellProperties.selectOptions;
var options;
if (typeof selectOptions == 'function'){
options = this.prepareOptions(selectOptions(this.row, this.col, this.prop))
} else {
options = this.prepareOptions(selectOptions);
}
Handsontable.Dom.empty(this.select);
for (var option in options){
if (options.hasOwnProperty(option)){
var optionElement = document.createElement('OPTION');
optionElement.value = option;
Handsontable.Dom.fastInnerHTML(optionElement, options[option]);
this.select.appendChild(optionElement);
}
}
};
SelectEditor.prototype.prepareOptions = function(optionsToPrepare){
var preparedOptions = {};
if (Handsontable.helper.isArray(optionsToPrepare)){
for(var i = 0, len = optionsToPrepare.length; i < len; i++){
preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i];
}
}
else if (typeof optionsToPrepare == 'object') {
preparedOptions = optionsToPrepare;
}
return preparedOptions;
};
SelectEditor.prototype.getValue = function () {
return this.select.value;
};
SelectEditor.prototype.setValue = function (value) {
this.select.value = value;
};
var onBeforeKeyDown = function (event) {
var instance = this;
var editor = instance.getActiveEditor();
switch (event.keyCode){
case Handsontable.helper.keyCode.ARROW_UP:
var previousOption = editor.select.find('option:selected').prev();
if (previousOption.length == 1){
previousOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
var nextOption = editor.select.find('option:selected').next();
if (nextOption.length == 1){
nextOption.prop('selected', true);
}
event.stopImmediatePropagation();
event.preventDefault();
break;
}
};
SelectEditor.prototype.open = function () {
var width = Handsontable.Dom.outerWidth(this.TD); //important - group layout reads together for better performance
var height = Handsontable.Dom.outerHeight(this.TD);
var rootOffset = Handsontable.Dom.offset(this.instance.rootElement[0]);
var tdOffset = Handsontable.Dom.offset(this.TD);
this.select.style.height = height + 'px';
this.select.style.minWidth = width + 'px';
this.select.style.top = tdOffset.top - rootOffset.top + 'px';
this.select.style.left = tdOffset.left - rootOffset.left - 2 + 'px'; //2 is cell border
this.select.style.display = '';
this.instance.addHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.close = function () {
this.select.style.display = 'none';
this.instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
SelectEditor.prototype.focus = function () {
this.select.focus();
};
Handsontable.editors.SelectEditor = SelectEditor;
Handsontable.editors.registerEditor('select', SelectEditor);
})(Handsontable);
(function (Handsontable) {
var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend();
DropdownEditor.prototype.prepare = function () {
Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments);
this.cellProperties.filter = false;
this.cellProperties.strict = true;
};
Handsontable.editors.DropdownEditor = DropdownEditor;
Handsontable.editors.registerEditor('dropdown', DropdownEditor);
})(Handsontable);
/**
* Numeric cell validator
* @param {*} value - Value of edited cell
* @param {*} callback - Callback called with validation result
*/
Handsontable.NumericValidator = function (value, callback) {
if (value === null) {
value = '';
}
callback(/^-?\d*(\.|\,)?\d*$/.test(value));
};
/**
* Function responsible for validation of autocomplete value
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
var process = function (value, callback) {
var originalVal = value;
var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null;
return function (source) {
var found = false;
for (var s = 0, slen = source.length; s < slen; s++) {
if (originalVal === source[s]) {
found = true; //perfect match
break;
}
else if (lowercaseVal === source[s].toLowerCase()) {
// changes[i][3] = source[s]; //good match, fix the case << TODO?
found = true;
break;
}
}
callback(found);
}
};
/**
* Autocomplete cell validator
* @param {*} value - Value of edited cell
* @param {*} calback - Callback called with validation result
*/
Handsontable.AutocompleteValidator = function (value, callback) {
if (this.strict && this.source) {
typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source);
} else {
callback(true);
}
};
/**
* Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta)
*/
Handsontable.AutocompleteCell = {
editor: Handsontable.editors.AutocompleteEditor,
renderer: Handsontable.renderers.AutocompleteRenderer,
validator: Handsontable.AutocompleteValidator
};
Handsontable.CheckboxCell = {
editor: Handsontable.editors.CheckboxEditor,
renderer: Handsontable.renderers.CheckboxRenderer
};
Handsontable.TextCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.TextRenderer
};
Handsontable.NumericCell = {
editor: Handsontable.editors.TextEditor,
renderer: Handsontable.renderers.NumericRenderer,
validator: Handsontable.NumericValidator,
dataType: 'number'
};
Handsontable.DateCell = {
editor: Handsontable.editors.DateEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.HandsontableCell = {
editor: Handsontable.editors.HandsontableEditor,
renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell
};
Handsontable.PasswordCell = {
editor: Handsontable.editors.PasswordEditor,
renderer: Handsontable.renderers.PasswordRenderer,
copyable: false
};
Handsontable.DropdownCell = {
editor: Handsontable.editors.DropdownEditor,
renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell
validator: Handsontable.AutocompleteValidator
};
//here setup the friendly aliases that are used by cellProperties.type
Handsontable.cellTypes = {
text: Handsontable.TextCell,
date: Handsontable.DateCell,
numeric: Handsontable.NumericCell,
checkbox: Handsontable.CheckboxCell,
autocomplete: Handsontable.AutocompleteCell,
handsontable: Handsontable.HandsontableCell,
password: Handsontable.PasswordCell,
dropdown: Handsontable.DropdownCell
};
//here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor
Handsontable.cellLookup = {
validator: {
numeric: Handsontable.NumericValidator,
autocomplete: Handsontable.AutocompleteValidator
}
};
/*
* jQuery.fn.autoResize 1.1+
* --
* https://github.com/warpech/jQuery.fn.autoResize
*
* This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically).
* It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future.
*
* originally forked from:
* https://github.com/jamespadolsey/jQuery.fn.autoResize
* which is now located here:
* https://github.com/alexbardas/jQuery.fn.autoResize
* though the mostly maintained for is here:
* https://github.com/dpashkevich/jQuery.fn.autoResize/network
*
* --
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details. */
(function($){
autoResize.defaults = {
onResize: function(){},
animate: {
duration: 200,
complete: function(){}
},
extraSpace: 50,
minHeight: 'original',
maxHeight: 500,
minWidth: 'original',
maxWidth: 500
};
autoResize.cloneCSSProperties = [
'lineHeight', 'textDecoration', 'letterSpacing',
'fontSize', 'fontFamily', 'fontStyle', 'fontWeight',
'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust',
'padding'
];
autoResize.cloneCSSValues = {
position: 'absolute',
top: -9999,
left: -9999,
opacity: 0,
overflow: 'hidden',
overflowX: 'hidden',
overflowY: 'hidden',
border: '1px solid black',
padding: '0.49em' //this must be about the width of caps W character
};
autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]';
autoResize.AutoResizer = AutoResizer;
$.fn.autoResize = autoResize;
function autoResize(config) {
this.filter(autoResize.resizableFilterSelector).each(function(){
new AutoResizer( $(this), config );
});
return this;
}
function AutoResizer(el, config) {
if(this.clones) return;
this.config = $.extend({}, autoResize.defaults, config);
this.el = el;
this.nodeName = el[0].nodeName.toLowerCase();
this.previousScrollTop = null;
if (config.maxWidth === 'original') config.maxWidth = el.width();
if (config.minWidth === 'original') config.minWidth = el.width();
if (config.maxHeight === 'original') config.maxHeight = el.height();
if (config.minHeight === 'original') config.minHeight = el.height();
if (this.nodeName === 'textarea') {
el.css({
resize: 'none',
overflowY: 'none'
});
}
el.data('AutoResizer', this);
this.createClone();
this.injectClone();
this.bind();
}
AutoResizer.prototype = {
bind: function() {
var check = $.proxy(function(){
this.check();
return true;
}, this);
this.unbind();
this.el
.bind('keyup.autoResize', check)
//.bind('keydown.autoResize', check)
.bind('change.autoResize', check);
this.check(null, true);
},
unbind: function() {
this.el.unbind('.autoResize');
},
createClone: function() {
var el = this.el,
self = this,
config = this.config;
this.clones = $();
if (config.minHeight !== 'original' || config.maxHeight !== 'original') {
this.hClone = el.clone().height('auto');
this.clones = this.clones.add(this.hClone);
}
if (config.minWidth !== 'original' || config.maxWidth !== 'original') {
this.wClone = $('<div/>').width('auto').css({
whiteSpace: 'nowrap',
'float': 'left'
});
this.clones = this.clones.add(this.wClone);
}
$.each(autoResize.cloneCSSProperties, function(i, p){
self.clones.css(p, el.css(p));
});
this.clones
.removeAttr('name')
.removeAttr('id')
.attr('tabIndex', -1)
.css(autoResize.cloneCSSValues)
.css('overflowY', 'scroll');
},
check: function(e, immediate) {
var config = this.config,
wClone = this.wClone,
hClone = this.hClone,
el = this.el,
value = el.val();
if (wClone) {
wClone.text(value);
// Calculate new width + whether to change
var cloneWidth = wClone.outerWidth(),
newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ?
cloneWidth + config.extraSpace : config.minWidth,
currentWidth = el.width();
newWidth = Math.min(newWidth, config.maxWidth);
if (
(newWidth < currentWidth && newWidth >= config.minWidth) ||
(newWidth >= config.minWidth && newWidth <= config.maxWidth)
) {
config.onResize.call(el);
el.scrollLeft(0);
config.animate && !immediate ?
el.stop(1,1).animate({
width: newWidth
}, config.animate)
: el.width(newWidth);
}
}
if (hClone) {
if (newWidth) {
hClone.width(newWidth);
}
hClone.height(0).val(value).scrollTop(10000);
var scrollTop = hClone[0].scrollTop + config.extraSpace;
// Don't do anything if scrollTop hasen't changed:
if (this.previousScrollTop === scrollTop) {
return;
}
this.previousScrollTop = scrollTop;
if (scrollTop >= config.maxHeight) {
scrollTop = config.maxHeight;
}
if (scrollTop < config.minHeight) {
scrollTop = config.minHeight;
}
if(scrollTop == config.maxHeight && newWidth == config.maxWidth) {
el.css('overflowY', 'scroll');
}
else {
el.css('overflowY', 'hidden');
}
config.onResize.call(el);
// Either animate or directly apply height:
config.animate && !immediate ?
el.stop(1,1).animate({
height: scrollTop
}, config.animate)
: el.height(scrollTop);
}
},
destroy: function() {
this.unbind();
this.el.removeData('AutoResizer');
this.clones.remove();
delete this.el;
delete this.hClone;
delete this.wClone;
delete this.clones;
},
injectClone: function() {
(
autoResize.cloneContainer ||
(autoResize.cloneContainer = $('<arclones/>').appendTo('body'))
).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once
}
};
})(jQuery);
/**
* SheetClip - Spreadsheet Clipboard Parser
* version 0.2
*
* This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice,
* Google Docs and Microsoft Excel.
*
* Copyright 2012, Marcin Warpechowski
* Licensed under the MIT license.
* http://github.com/warpech/sheetclip/
*/
/*jslint white: true*/
(function (global) {
"use strict";
function countQuotes(str) {
return str.split('"').length - 1;
}
global.SheetClip = {
parse: function (str) {
var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last;
rows = str.split('\n');
if (rows.length > 1 && rows[rows.length - 1] === '') {
rows.pop();
}
for (r = 0, rlen = rows.length; r < rlen; r += 1) {
rows[r] = rows[r].split('\t');
for (c = 0, clen = rows[r].length; c < clen; c += 1) {
if (!arr[a]) {
arr[a] = [];
}
if (multiline && c === 0) {
last = arr[a].length - 1;
arr[a][last] = arr[a][last] + '\n' + rows[r][0];
if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2
multiline = false;
arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"');
}
}
else {
if (c === clen - 1 && rows[r][c].indexOf('"') === 0) {
arr[a].push(rows[r][c].substring(1).replace(/""/g, '"'));
multiline = true;
}
else {
arr[a].push(rows[r][c].replace(/""/g, '"'));
multiline = false;
}
}
}
if (!multiline) {
a += 1;
}
}
return arr;
},
stringify: function (arr) {
var r, rlen, c, clen, str = '', val;
for (r = 0, rlen = arr.length; r < rlen; r += 1) {
for (c = 0, clen = arr[r].length; c < clen; c += 1) {
if (c > 0) {
str += '\t';
}
val = arr[r][c];
if (typeof val === 'string') {
if (val.indexOf('\n') > -1) {
str += '"' + val.replace(/"/g, '""') + '"';
}
else {
str += val;
}
}
else if (val === null || val === void 0) { //void 0 resolves to undefined
str += '';
}
else {
str += val;
}
}
str += '\n';
}
return str;
}
};
}(window));
/**
* CopyPaste.js
* Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused
* In future we may implement a better driver when better APIs are available
* @constructor
*/
var CopyPaste = (function () {
var instance;
return {
getInstance: function () {
if (!instance) {
instance = new CopyPasteClass();
} else if (instance.hasBeenDestroyed()){
instance.init();
}
instance.refCounter++;
return instance;
}
};
})();
function CopyPasteClass() {
this.refCounter = 0;
this.init();
}
CopyPasteClass.prototype.init = function () {
var that = this
, style
, parent;
this.copyCallbacks = [];
this.cutCallbacks = [];
this.pasteCallbacks = [];
this.listenerElement = document.documentElement;
parent = document.body;
if (document.getElementById('CopyPasteDiv')) {
this.elDiv = document.getElementById('CopyPasteDiv');
this.elTextarea = this.elDiv.firstChild;
}
else {
this.elDiv = document.createElement('DIV');
this.elDiv.id = 'CopyPasteDiv';
style = this.elDiv.style;
style.position = 'fixed';
style.top = '-10000px';
style.left = '-10000px';
parent.appendChild(this.elDiv);
this.elTextarea = document.createElement('TEXTAREA');
this.elTextarea.className = 'copyPaste';
style = this.elTextarea.style;
style.width = '10000px';
style.height = '10000px';
style.overflow = 'hidden';
this.elDiv.appendChild(this.elTextarea);
if (typeof style.opacity !== 'undefined') {
style.opacity = 0;
}
else {
/*@cc_on @if (@_jscript)
if(typeof style.filter === 'string') {
style.filter = 'alpha(opacity=0)';
}
@end @*/
}
}
this.keydownListener = function (event) {
var isCtrlDown = false;
if (event.metaKey) { //mac
isCtrlDown = true;
}
else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc
isCtrlDown = true;
}
if (isCtrlDown) {
if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) {
return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected
}
that.selectNodeText(that.elTextarea);
setTimeout(function () {
that.selectNodeText(that.elTextarea);
}, 0);
}
/* 67 = c
* 86 = v
* 88 = x
*/
if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) {
// that.selectNodeText(that.elTextarea);
if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12
setTimeout(function () {
that.triggerCut(event);
}, 0);
}
else if (event.keyCode === 86) {
setTimeout(function () {
that.triggerPaste(event);
}, 0);
}
}
}
this._bindEvent(this.listenerElement, 'keydown', this.keydownListener);
};
//http://jsperf.com/textara-selection
//http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie
CopyPasteClass.prototype.selectNodeText = function (el) {
el.select();
};
//http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text
CopyPasteClass.prototype.getSelectionText = function () {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
};
CopyPasteClass.prototype.copyable = function (str) {
if (typeof str !== 'string' && str.toString === void 0) {
throw new Error('copyable requires string parameter');
}
this.elTextarea.value = str;
};
/*CopyPasteClass.prototype.onCopy = function (fn) {
this.copyCallbacks.push(fn);
};*/
CopyPasteClass.prototype.onCut = function (fn) {
this.cutCallbacks.push(fn);
};
CopyPasteClass.prototype.onPaste = function (fn) {
this.pasteCallbacks.push(fn);
};
CopyPasteClass.prototype.removeCallback = function (fn) {
var i, ilen;
for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) {
if (this.copyCallbacks[i] === fn) {
this.copyCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) {
if (this.cutCallbacks[i] === fn) {
this.cutCallbacks.splice(i, 1);
return true;
}
}
for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) {
if (this.pasteCallbacks[i] === fn) {
this.pasteCallbacks.splice(i, 1);
return true;
}
}
return false;
};
CopyPasteClass.prototype.triggerCut = function (event) {
var that = this;
if (that.cutCallbacks) {
setTimeout(function () {
for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) {
that.cutCallbacks[i](event);
}
}, 50);
}
};
CopyPasteClass.prototype.triggerPaste = function (event, str) {
var that = this;
if (that.pasteCallbacks) {
setTimeout(function () {
var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline
for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) {
that.pasteCallbacks[i](val, event);
}
}, 50);
}
};
CopyPasteClass.prototype.destroy = function () {
if(!this.hasBeenDestroyed() && --this.refCounter == 0){
if (this.elDiv && this.elDiv.parentNode) {
this.elDiv.parentNode.removeChild(this.elDiv);
}
this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener);
}
};
CopyPasteClass.prototype.hasBeenDestroyed = function () {
return !this.refCounter;
};
//old version used this:
// - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/
// - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization
//but that cannot work with jQuery.trigger
CopyPasteClass.prototype._bindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).on(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
CopyPasteClass.prototype._unbindEvent = (function () {
if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests)
return function (elem, type, cb) {
$(elem).off(type + '.copypaste', cb);
};
}
else {
return function (elem, type, cb) {
elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery
};
}
})();
// json-patch-duplex.js 0.3.6
// (c) 2013 Joachim Wester
// MIT license
var jsonpatch;
(function (jsonpatch) {
var objOps = {
add: function (obj, key) {
obj[key] = this.value;
return true;
},
remove: function (obj, key) {
delete obj[key];
return true;
},
replace: function (obj, key) {
obj[key] = this.value;
return true;
},
move: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "remove", path: this.from }
]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
copy: function (obj, key, tree) {
var temp = { op: "_get", path: this.from };
apply(tree, [temp]);
apply(tree, [
{ op: "add", path: this.path, value: temp.value }
]);
return true;
},
test: function (obj, key) {
return (JSON.stringify(obj[key]) === JSON.stringify(this.value));
},
_get: function (obj, key) {
this.value = obj[key];
}
};
var arrOps = {
add: function (arr, i) {
arr.splice(i, 0, this.value);
return true;
},
remove: function (arr, i) {
arr.splice(i, 1);
return true;
},
replace: function (arr, i) {
arr[i] = this.value;
return true;
},
move: objOps.move,
copy: objOps.copy,
test: objOps.test,
_get: objOps._get
};
var observeOps = {
add: function (patches, path) {
var patch = {
op: "add",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
},
'delete': function (patches, path) {
var patch = {
op: "remove",
path: path + escapePathComponent(this.name)
};
patches.push(patch);
},
update: function (patches, path) {
var patch = {
op: "replace",
path: path + escapePathComponent(this.name),
value: this.object[this.name]
};
patches.push(patch);
}
};
function escapePathComponent(str) {
if (str.indexOf('/') === -1 && str.indexOf('~') === -1)
return str;
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function _getPathRecursive(root, obj) {
var found;
for (var key in root) {
if (root.hasOwnProperty(key)) {
if (root[key] === obj) {
return escapePathComponent(key) + '/';
} else if (typeof root[key] === 'object') {
found = _getPathRecursive(root[key], obj);
if (found != '') {
return escapePathComponent(key) + '/' + found;
}
}
}
}
return '';
}
function getPath(root, obj) {
if (root === obj) {
return '/';
}
var path = _getPathRecursive(root, obj);
if (path === '') {
throw new Error("Object not found in root");
}
return '/' + path;
}
var beforeDict = [];
jsonpatch.intervals;
var Mirror = (function () {
function Mirror(obj) {
this.observers = [];
this.obj = obj;
}
return Mirror;
})();
var ObserverInfo = (function () {
function ObserverInfo(callback, observer) {
this.callback = callback;
this.observer = observer;
}
return ObserverInfo;
})();
function getMirror(obj) {
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === obj) {
return beforeDict[i];
}
}
}
function getObserverFromMirror(mirror, callback) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].callback === callback) {
return mirror.observers[j].observer;
}
}
}
function removeObserverFromMirror(mirror, observer) {
for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) {
if (mirror.observers[j].observer === observer) {
mirror.observers.splice(j, 1);
return;
}
}
}
function unobserve(root, observer) {
generate(observer);
if (Object.observe) {
_unobserve(observer, root);
} else {
clearTimeout(observer.next);
}
var mirror = getMirror(root);
removeObserverFromMirror(mirror, observer);
}
jsonpatch.unobserve = unobserve;
function observe(obj, callback) {
var patches = [];
var root = obj;
var observer;
var mirror = getMirror(obj);
if (!mirror) {
mirror = new Mirror(obj);
beforeDict.push(mirror);
} else {
observer = getObserverFromMirror(mirror, callback);
}
if (observer) {
return observer;
}
if (Object.observe) {
observer = function (arr) {
//This "refresh" is needed to begin observing new object properties
_unobserve(observer, obj);
_observe(observer, obj);
var a = 0, alen = arr.length;
while (a < alen) {
if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) {
var type = arr[a].type;
switch (type) {
case 'new':
type = 'add';
break;
case 'deleted':
type = 'delete';
break;
case 'updated':
type = 'update';
break;
}
observeOps[type].call(arr[a], patches, getPath(root, arr[a].object));
}
a++;
}
if (patches) {
if (callback) {
callback(patches);
}
}
observer.patches = patches;
patches = [];
};
} else {
observer = {};
mirror.value = JSON.parse(JSON.stringify(obj));
if (callback) {
//callbacks.push(callback); this has no purpose
observer.callback = callback;
observer.next = null;
var intervals = this.intervals || [100, 1000, 10000, 60000];
var currentInterval = 0;
var dirtyCheck = function () {
generate(observer);
};
var fastCheck = function () {
clearTimeout(observer.next);
observer.next = setTimeout(function () {
dirtyCheck();
currentInterval = 0;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}, 0);
};
var slowCheck = function () {
dirtyCheck();
if (currentInterval == intervals.length)
currentInterval = intervals.length - 1;
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
};
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener('mousedown', fastCheck);
window.addEventListener('mouseup', fastCheck);
window.addEventListener('keydown', fastCheck);
} else {
window.attachEvent('onmousedown', fastCheck);
window.attachEvent('onmouseup', fastCheck);
window.attachEvent('onkeydown', fastCheck);
}
}
observer.next = setTimeout(slowCheck, intervals[currentInterval++]);
}
}
observer.patches = patches;
observer.object = obj;
mirror.observers.push(new ObserverInfo(callback, observer));
return _observe(observer, obj);
}
jsonpatch.observe = observe;
/// Listen to changes on an object tree, accumulate patches
function _observe(observer, obj) {
if (Object.observe) {
Object.observe(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_observe(observer, v);
}
}
}
}
return observer;
}
function _unobserve(observer, obj) {
if (Object.observe) {
Object.unobserve(obj, observer);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var v = obj[key];
if (v && typeof (v) === "object") {
_unobserve(observer, v);
}
}
}
}
return observer;
}
function generate(observer) {
if (Object.observe) {
Object.deliverChangeRecords(observer);
} else {
var mirror;
for (var i = 0, ilen = beforeDict.length; i < ilen; i++) {
if (beforeDict[i].obj === observer.object) {
mirror = beforeDict[i];
break;
}
}
_generate(mirror.value, observer.object, observer.patches, "");
}
var temp = observer.patches;
if (temp.length > 0) {
observer.patches = [];
if (observer.callback) {
observer.callback(temp);
}
}
return temp;
}
jsonpatch.generate = generate;
var _objectKeys;
if (Object.keys) {
_objectKeys = Object.keys;
} else {
_objectKeys = function (obj) {
var keys = [];
for (var o in obj) {
if (obj.hasOwnProperty(o)) {
keys.push(o);
}
}
return keys;
};
}
// Dirty check if obj is different from mirror, generate patches and update mirror
function _generate(mirror, obj, patches, path) {
var newKeys = _objectKeys(obj);
var oldKeys = _objectKeys(mirror);
var changed = false;
var deleted = false;
for (var t = oldKeys.length - 1; t >= 0; t--) {
var key = oldKeys[t];
var oldVal = mirror[key];
if (obj.hasOwnProperty(key)) {
var newVal = obj[key];
if (oldVal instanceof Object) {
_generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key));
} else {
if (oldVal != newVal) {
changed = true;
patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal });
mirror[key] = newVal;
}
}
} else {
patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) });
delete mirror[key];
deleted = true;
}
}
if (!deleted && newKeys.length == oldKeys.length) {
return;
}
for (var t = 0; t < newKeys.length; t++) {
var key = newKeys[t];
if (!mirror.hasOwnProperty(key)) {
patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] });
mirror[key] = JSON.parse(JSON.stringify(obj[key]));
}
}
}
var _isArray;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (obj) {
return obj.push && typeof obj.length === 'number';
};
}
/// Apply a json-patch operation on an object tree
function apply(tree, patches) {
var result = false, p = 0, plen = patches.length, patch;
while (p < plen) {
patch = patches[p];
// Find the object
var keys = patch.path.split('/');
var obj = tree;
var t = 1;
var len = keys.length;
while (true) {
if (_isArray(obj)) {
var index = parseInt(keys[t], 10);
t++;
if (t >= len) {
result = arrOps[patch.op].call(patch, obj, index, tree);
break;
}
obj = obj[index];
} else {
var key = keys[t];
if (key.indexOf('~') != -1)
key = key.replace(/~1/g, '/').replace(/~0/g, '~');
t++;
if (t >= len) {
result = objOps[patch.op].call(patch, obj, key, tree);
break;
}
obj = obj[key];
}
}
p++;
}
return result;
}
jsonpatch.apply = apply;
})(jsonpatch || (jsonpatch = {}));
if (typeof exports !== "undefined") {
exports.apply = jsonpatch.apply;
exports.observe = jsonpatch.observe;
exports.unobserve = jsonpatch.unobserve;
exports.generate = jsonpatch.generate;
}
Handsontable.PluginHookClass = (function () {
var Hooks = function () {
return {
// Hooks
beforeInitWalkontable: [],
beforeInit: [],
beforeRender: [],
beforeSetRangeEnd: [],
beforeChange: [],
beforeChangeRender: [],
beforeRemoveCol: [],
beforeRemoveRow: [],
beforeValidate: [],
beforeGetCellMeta: [],
beforeAutofill: [],
beforeKeyDown: [],
afterInit : [],
afterLoadData : [],
afterUpdateSettings: [],
afterRender : [],
afterRenderer : [],
afterChange : [],
afterValidate: [],
afterGetCellMeta: [],
afterSetCellMeta: [],
afterGetColHeader: [],
afterDestroy: [],
afterRemoveRow: [],
afterCreateRow: [],
afterRemoveCol: [],
afterCreateCol: [],
afterDeselect: [],
afterSelection: [],
afterSelectionByProp: [],
afterSelectionEnd: [],
afterSelectionEndByProp: [],
afterOnCellMouseDown: [],
afterOnCellMouseOver: [],
afterOnCellCornerMouseDown: [],
afterScrollVertically: [],
afterScrollHorizontally: [],
afterCellMetaReset:[],
// Modifiers
modifyColWidth: [],
modifyRowHeight: [],
modifyRow: [],
modifyCol: []
}
};
var legacy = {
onBeforeChange: "beforeChange",
onChange: "afterChange",
onCreateRow: "afterCreateRow",
onCreateCol: "afterCreateCol",
onSelection: "afterSelection",
onCopyLimit: "afterCopyLimit",
onSelectionEnd: "afterSelectionEnd",
onSelectionByProp: "afterSelectionByProp",
onSelectionEndByProp: "afterSelectionEndByProp"
};
function PluginHookClass() {
this.hooks = Hooks();
this.globalBucket = {};
this.legacy = legacy;
}
PluginHookClass.prototype.getBucket = function (instance) {
if(instance) {
if(!instance.pluginHookBucket) {
instance.pluginHookBucket = {};
}
return instance.pluginHookBucket;
}
return this.globalBucket;
};
PluginHookClass.prototype.add = function (key, fn, instance) {
//if fn is array, run this for all the array items
if (Handsontable.helper.isArray(fn)) {
for (var i = 0, len = fn.length; i < len; i++) {
this.add(key, fn[i]);
}
}
else {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
var bucket = this.getBucket(instance);
if (typeof bucket[key] === "undefined") {
bucket[key] = [];
}
fn.skip = false;
if (bucket[key].indexOf(fn) == -1) {
bucket[key].push(fn); //only add a hook if it has not already be added (adding the same hook twice is now silently ignored)
}
}
return this;
};
PluginHookClass.prototype.once = function(key, fn, instance){
if(Handsontable.helper.isArray(fn)){
for(var i = 0, len = fn.length; i < len; i++){
fn[i].runOnce = true;
this.add(key, fn[i], instance);
}
} else {
fn.runOnce = true;
this.add(key, fn, instance);
}
};
PluginHookClass.prototype.remove = function (key, fn, instance) {
var status = false;
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
var bucket = this.getBucket(instance);
if (typeof bucket[key] !== 'undefined') {
for (var i = 0, leni = bucket[key].length; i < leni; i++) {
if (bucket[key][i] == fn) {
bucket[key][i].skip = true;
status = true;
break;
}
}
}
return status;
};
PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
this._runBucket(this.globalBucket, instance, key, p1, p2, p3, p4, p5);
this._runBucket(this.getBucket(instance), instance, key, p1, p2, p3, p4, p5);
};
PluginHookClass.prototype._runBucket = function (bucket, instance, key, p1, p2, p3, p4, p5) {
var handlers = bucket[key];
if (handlers) {
for (var i = 0, leni = handlers.length; i < leni; i++) {
if (!handlers[i].skip) {
handlers[i].call(instance, p1, p2, p3, p4, p5);
if (handlers[i].runOnce) {
this.remove(key, handlers[i], bucket === this.globalBucket ? null : instance);
}
}
}
}
};
PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) {
// provide support for old versions of HOT
if (key in legacy) {
key = legacy[key];
}
p1 = this._executeBucket(this.globalBucket, instance, key, p1, p2, p3, p4, p5);
p1 = this._executeBucket(this.getBucket(instance), instance, key, p1, p2, p3, p4, p5);
return p1;
};
PluginHookClass.prototype._executeBucket = function (bucket, instance, key, p1, p2, p3, p4, p5) {
var res,
handlers = bucket[key];
//performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture
if (handlers) {
for (var i = 0, leni = handlers.length; i < leni; i++) {
if (!handlers[i].skip) {
res = handlers[i].call(instance, p1, p2, p3, p4, p5);
if (res !== void 0) {
p1 = res;
}
if (handlers[i].runOnce) {
this.remove(key, handlers[i], bucket === this.globalBucket ? null : instance);
}
if (res === false) { //if any handler returned false
return false; //event has been cancelled and further execution of handler queue is being aborted
}
}
}
}
return p1;
};
/**
* Registers a hook name (adds it to the list of the known hook names). Used by plugins. It is not neccessary to call,
* register, but if you use it, your plugin hook will be used returned by getRegistered
* (which itself is used in the demo http://handsontable.com/demo/callbacks.html)
* @param key {String}
*/
PluginHookClass.prototype.register = function (key) {
if (!this.isRegistered(key)) {
this.hooks[key] = [];
}
};
/**
* Deregisters a hook name (removes it from the list of known hook names)
* @param key {String}
*/
PluginHookClass.prototype.deregister = function (key) {
delete this.hooks[key];
};
/**
* Returns boolean information if a hook by such name has been registered
* @param key {String}
*/
PluginHookClass.prototype.isRegistered = function (key) {
return (typeof this.hooks[key] !== "undefined");
};
/**
* Returns an array of registered hooks
* @returns {Array}
*/
PluginHookClass.prototype.getRegistered = function () {
return Object.keys(this.hooks);
};
return PluginHookClass;
})();
Handsontable.hooks = new Handsontable.PluginHookClass();
Handsontable.PluginHooks = Handsontable.hooks; //in future move this line to legacy.js
(function (Handsontable) {
function HandsontableAutoColumnSize() {
var plugin = this
, sampleCount = 5; //number of samples to take of each value length
this.beforeInit = function () {
var instance = this;
instance.autoColumnWidths = [];
if (instance.getSettings().autoColumnSize !== false) {
if (!instance.autoColumnSizeTmp) {
instance.autoColumnSizeTmp = {
table: null,
tableStyle: null,
theadTh: null,
tbody: null,
container: null,
containerStyle: null,
determineBeforeNextRender: true
};
instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.addHook('modifyColWidth', htAutoColumnSize.modifyColWidth);
instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy);
instance.determineColumnWidth = plugin.determineColumnWidth;
}
} else {
if (instance.autoColumnSizeTmp) {
instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged);
instance.removeHook('modifyColWidth', htAutoColumnSize.modifyColWidth);
instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy);
delete instance.determineColumnWidth;
plugin.afterDestroy.call(instance);
}
}
};
this.determineIfChanged = function (force) {
if (force) {
htAutoColumnSize.determineColumnsWidth.apply(this, arguments);
}
};
this.determineColumnWidth = function (col) {
var instance = this
, tmp = instance.autoColumnSizeTmp;
if (!tmp.container) {
createTmpContainer.call(tmp, instance);
}
tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize';
tmp.table.className = instance.$table[0].className;
var rows = instance.countRows();
var samples = {};
var maxLen = 0;
for (var r = 0; r < rows; r++) {
var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col));
var len = value.length;
if (len > maxLen) {
maxLen = len;
}
if (!samples[len]) {
samples[len] = {
needed: sampleCount,
strings: []
};
}
if (samples[len].needed) {
samples[len].strings.push({value: value, row: r});
samples[len].needed--;
}
}
var settings = instance.getSettings();
if (settings.colHeaders) {
instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML
}
Handsontable.Dom.empty(tmp.tbody);
for (var i in samples) {
if (samples.hasOwnProperty(i)) {
for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) {
var row = samples[i].strings[j].row;
var cellProperties = instance.getCellMeta(row, col);
cellProperties.col = col;
cellProperties.row = row;
var renderer = instance.getCellRenderer(cellProperties);
var tr = document.createElement('tr');
var td = document.createElement('td');
renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties);
r++;
tr.appendChild(td);
tmp.tbody.appendChild(tr);
}
}
}
var parent = instance.rootElement[0].parentNode;
parent.appendChild(tmp.container);
var width = Handsontable.Dom.outerWidth(tmp.table);
parent.removeChild(tmp.container);
return width;
};
this.determineColumnsWidth = function () {
var instance = this;
var settings = this.getSettings();
if (settings.autoColumnSize || !settings.colWidths) {
var cols = this.countCols();
for (var c = 0; c < cols; c++) {
if (!instance._getColWidthFromSettings(c)) {
this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c);
}
}
}
};
this.modifyColWidth = function (width, col) {
if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > width) {
return this.autoColumnWidths[col];
}
return width;
};
this.afterDestroy = function () {
var instance = this;
if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) {
instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container);
}
instance.autoColumnSizeTmp = null;
};
function createTmpContainer(instance) {
var d = document
, tmp = this;
tmp.table = d.createElement('table');
tmp.theadTh = d.createElement('th');
tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh);
tmp.tableStyle = tmp.table.style;
tmp.tableStyle.tableLayout = 'auto';
tmp.tableStyle.width = 'auto';
tmp.tbody = d.createElement('tbody');
tmp.table.appendChild(tmp.tbody);
tmp.container = d.createElement('div');
tmp.container.className = instance.rootElement[0].className + ' hidden';
tmp.containerStyle = tmp.container.style;
tmp.container.appendChild(tmp.table);
}
}
var htAutoColumnSize = new HandsontableAutoColumnSize();
Handsontable.hooks.add('beforeInit', htAutoColumnSize.beforeInit);
Handsontable.hooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit);
})(Handsontable);
/**
* This plugin sorts the view by a column (but does not sort the data source!)
* @constructor
*/
function HandsontableColumnSorting() {
var plugin = this;
this.init = function (source) {
var instance = this;
var sortingSettings = instance.getSettings().columnSorting;
var sortingColumn, sortingOrder;
instance.sortingEnabled = !!(sortingSettings);
if (instance.sortingEnabled) {
instance.sortIndex = [];
var loadedSortingState = loadSortingState.call(instance);
if (typeof loadedSortingState != 'undefined') {
sortingColumn = loadedSortingState.sortColumn;
sortingOrder = loadedSortingState.sortOrder;
} else {
sortingColumn = sortingSettings.column;
sortingOrder = sortingSettings.sortOrder;
}
plugin.sortByColumn.call(instance, sortingColumn, sortingOrder);
instance.sort = function(){
var args = Array.prototype.slice.call(arguments);
return plugin.sortByColumn.apply(instance, args)
};
if (typeof instance.getSettings().observeChanges == 'undefined'){
enableObserveChangesPlugin.call(instance);
}
if (source == 'afterInit') {
bindColumnSortingAfterClick.call(instance);
instance.addHook('afterCreateRow', plugin.afterCreateRow);
instance.addHook('afterRemoveRow', plugin.afterRemoveRow);
instance.addHook('afterLoadData', plugin.init);
}
} else {
delete instance.sort;
instance.removeHook('afterCreateRow', plugin.afterCreateRow);
instance.removeHook('afterRemoveRow', plugin.afterRemoveRow);
instance.removeHook('afterLoadData', plugin.init);
}
};
this.setSortingColumn = function (col, order) {
var instance = this;
if (typeof col == 'undefined') {
delete instance.sortColumn;
delete instance.sortOrder;
return;
} else if (instance.sortColumn === col && typeof order == 'undefined') {
instance.sortOrder = !instance.sortOrder;
} else {
instance.sortOrder = typeof order != 'undefined' ? order : true;
}
instance.sortColumn = col;
};
this.sortByColumn = function (col, order) {
var instance = this;
plugin.setSortingColumn.call(instance, col, order);
if(typeof instance.sortColumn == 'undefined'){
return;
}
Handsontable.hooks.run(instance, 'beforeColumnSort', instance.sortColumn, instance.sortOrder);
plugin.sort.call(instance);
instance.render();
saveSortingState.call(instance);
Handsontable.hooks.run(instance, 'afterColumnSort', instance.sortColumn, instance.sortOrder);
};
var saveSortingState = function () {
var instance = this;
var sortingState = {};
if (typeof instance.sortColumn != 'undefined') {
sortingState.sortColumn = instance.sortColumn;
}
if (typeof instance.sortOrder != 'undefined') {
sortingState.sortOrder = instance.sortOrder;
}
if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) {
Handsontable.hooks.run(instance, 'persistentStateSave', 'columnSorting', sortingState);
}
};
var loadSortingState = function () {
var instance = this;
var storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'columnSorting', storedState);
return storedState.value;
};
var bindColumnSortingAfterClick = function () {
var instance = this;
instance.rootElement.on('click.handsontable', '.columnSorting', function (e) {
if (Handsontable.Dom.hasClass(e.target, 'columnSorting')) {
var col = getColumn(e.target);
plugin.sortByColumn.call(instance, col);
}
});
function countRowHeaders() {
var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th');
return THs.length;
}
function getColumn(target) {
var TH = Handsontable.Dom.closest(target, 'TH');
return Handsontable.Dom.index(TH) - countRowHeaders();
}
};
function enableObserveChangesPlugin () {
var instance = this;
instance._registerTimeout('enableObserveChanges', function(){
instance.updateSettings({
observeChanges: true
});
}, 0);
}
function defaultSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
if (a[1] < b[1]) return sortOrder ? -1 : 1;
if (a[1] > b[1]) return sortOrder ? 1 : -1;
return 0;
}
}
function dateSort(sortOrder) {
return function (a, b) {
if (a[1] === b[1]) {
return 0;
}
if (a[1] === null) {
return 1;
}
if (b[1] === null) {
return -1;
}
var aDate = new Date(a[1]);
var bDate = new Date(b[1]);
if (aDate < bDate) return sortOrder ? -1 : 1;
if (aDate > bDate) return sortOrder ? 1 : -1;
return 0;
}
}
this.sort = function () {
var instance = this;
if (typeof instance.sortOrder == 'undefined') {
return;
}
instance.sortingEnabled = false; //this is required by translateRow plugin hook
instance.sortIndex.length = 0;
var colOffset = this.colOffset();
for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) {
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
var colMeta = instance.getCellMeta(0, instance.sortColumn);
var sortFunction;
switch (colMeta.type) {
case 'date':
sortFunction = dateSort;
break;
default:
sortFunction = defaultSort;
}
this.sortIndex.sort(sortFunction(instance.sortOrder));
//Append spareRows
for(var i = this.sortIndex.length; i < instance.countRows(); i++){
this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]);
}
instance.sortingEnabled = true; //this is required by translateRow plugin hook
};
this.translateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) {
return instance.sortIndex[row][0];
}
return row;
};
this.untranslateRow = function (row) {
var instance = this;
if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) {
for (var i = 0; i < instance.sortIndex.length; i++) {
if (instance.sortIndex[i][0] == row) {
return i;
}
}
}
};
this.getColHeader = function (col, TH) {
if (this.getSettings().columnSorting) {
Handsontable.Dom.addClass(TH.querySelector('.colHeader'), 'columnSorting');
}
};
function isSorted(instance){
return typeof instance.sortColumn != 'undefined';
}
this.afterCreateRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] >= index){
instance.sortIndex[i][0] += amount;
}
}
for(var i=0; i < amount; i++){
instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]);
}
saveSortingState.call(instance);
};
this.afterRemoveRow = function(index, amount){
var instance = this;
if(!isSorted(instance)){
return;
}
var physicalRemovedIndex = plugin.translateRow.call(instance, index);
instance.sortIndex.splice(index, amount);
for(var i = 0; i < instance.sortIndex.length; i++){
if (instance.sortIndex[i][0] > physicalRemovedIndex){
instance.sortIndex[i][0] -= amount;
}
}
saveSortingState.call(instance);
};
this.afterChangeSort = function (changes/*, source*/) {
var instance = this;
var sortColumnChanged = false;
var selection = {};
if (!changes) {
return;
}
for (var i = 0; i < changes.length; i++) {
if (changes[i][1] == instance.sortColumn) {
sortColumnChanged = true;
selection.row = plugin.translateRow.call(instance, changes[i][0]);
selection.col = changes[i][1];
break;
}
}
if (sortColumnChanged) {
setTimeout(function () {
plugin.sort.call(instance);
instance.render();
instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col);
}, 0);
}
};
}
var htSortColumn = new HandsontableColumnSorting();
Handsontable.hooks.add('afterInit', function () {
htSortColumn.init.call(this, 'afterInit')
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htSortColumn.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyRow', htSortColumn.translateRow);
Handsontable.hooks.add('afterGetColHeader', htSortColumn.getColHeader);
Handsontable.hooks.register('beforeColumnSort');
Handsontable.hooks.register('afterColumnSort');
(function (Handsontable) {
'use strict';
function prepareVerticalAlignClass (className, alignment) {
if (className.indexOf(alignment)!= -1){
return className;
}
className = className
.replace('htTop','')
.replace('htMiddle','')
.replace('htBottom','')
.replace(' ','');
className += " " + alignment;
return className;
}
function prepareHorizontalAlignClass (className, alignment) {
if (className.indexOf(alignment)!= -1){
return className;
}
className = className
.replace('htLeft','')
.replace('htCenter','')
.replace('htRight','')
.replace('htJustify','')
.replace(' ','');
className += " " + alignment;
return className;
}
function doAlign (row, col, type, alignment) {
var cellMeta = this.getCellMeta(row, col),
className = alignment;
if (cellMeta.className) {
if(type === 'vertical') {
className = prepareVerticalAlignClass(cellMeta.className, alignment);
} else {
className = prepareHorizontalAlignClass(cellMeta.className, alignment);
}
}
this.setCellMeta(row, col, 'className',className);
this.render();
}
function align (range, type, alignment) {
// if (range.from.row < 0) {
// range.from = new WalkontableCellCoords(0,range.from.col);
// range.to = new WalkontableCellCoords(this.view.wt.wtTable.getRowStrategy().cellCount - 1, range.to.col);
// }
// if (range.from.col < 0) {
// range.from = new WalkontableCellCoords(range.from.row, 0);
// range.to = new WalkontableCellCoords(range.to.row, this.view.wt.wtTable.getColumnStrategy().cellCount - 1);
// }
if (range.from.row == range.to.row && range.from.col == range.to.col){
doAlign.call(this,range.from.row, range.from.col, type, alignment);
} else {
for(var row = range.from.row; row<= range.to.row; row++) {
for (var col = range.from.col; col <= range.to.col; col++) {
doAlign.call(this,row, col, type, alignment);
}
}
}
}
function ContextMenu(instance, customOptions){
this.instance = instance;
var contextMenu = this;
this.menu = createMenu();
this.enabled = true;
this.bindMouseEvents();
this.instance.addHook('afterDestroy', function () {
contextMenu.destroy();
});
this.defaultOptions = {
items: {
'row_above': {
name: 'Insert row above',
callback: function(key, selection){
this.alter("insert_row", selection.start.row);
},
disabled: function () {
var selected = this.getSelected(),
entireColumnSelection = [0,selected[1],this.view.wt.wtTable.getRowStrategy().cellCount-1,selected[1]],
columnSelected = entireColumnSelection.join(',') == selected.join(',');
return selected[0] < 0 || this.countRows() >= this.getSettings().maxRows || columnSelected;
}
},
'row_below': {
name: 'Insert row below',
callback: function(key, selection){
this.alter("insert_row", selection.end.row + 1);
},
disabled: function () {
var selected = this.getSelected(),
entireColumnSelection = [0,selected[1],this.view.wt.wtTable.getRowStrategy().cellCount-1,selected[1]],
columnSelected = entireColumnSelection.join(',') == selected.join(',');
return this.getSelected()[0] < 0 || this.countRows() >= this.getSettings().maxRows || columnSelected;
}
},
"hsep1": ContextMenu.SEPARATOR,
'col_left': {
name: 'Insert column on the left',
callback: function(key, selection){
this.alter("insert_col", selection.start.col);
},
disabled: function () {
var selected = this.getSelected(),
entireRowSelection = [selected[0],0, selected[0],this.view.wt.wtTable.getColumnStrategy().cellCount-1],
rowSelected = entireRowSelection.join(',') == selected.join(',');
return this.getSelected()[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
}
},
'col_right': {
name: 'Insert column on the right',
callback: function(key, selection){
this.alter("insert_col", selection.end.col + 1);
},
disabled: function () {
var selected = this.getSelected(),
entireRowSelection = [selected[0],0, selected[0],this.view.wt.wtTable.getColumnStrategy().cellCount-1],
rowSelected = entireRowSelection.join(',') == selected.join(',');
return selected[1] < 0 || this.countCols() >= this.getSettings().maxCols || rowSelected;
}
},
"hsep2": ContextMenu.SEPARATOR,
'remove_row': {
name: 'Remove row',
callback: function(key, selection){
var amount = selection.end.row - selection.start.row + 1;
this.alter("remove_row", selection.start.row, amount);
},
disabled: function () {
var selected = this.getSelected(),
entireColumnSelection = [0,selected[1],this.view.wt.wtTable.getRowStrategy().cellCount-1,selected[1]],
columnSelected = entireColumnSelection.join(',') == selected.join(',');
return (selected[0] < 0 || columnSelected);
}
},
'remove_col': {
name: 'Remove column',
callback: function(key, selection){
var amount = selection.end.col - selection.start.col + 1;
this.alter("remove_col", selection.start.col, amount);
},
disabled: function (){
var selected = this.getSelected(),
entireRowSelection = [selected[0],0, selected[0],this.view.wt.wtTable.getColumnStrategy().cellCount-1],
rowSelected = entireRowSelection.join(',') == selected.join(',');
return (selected[1] < 0 || rowSelected);
}
},
"hsep3": ContextMenu.SEPARATOR,
'undo': {
name: 'Undo',
callback: function(){
this.undo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isUndoAvailable();
}
},
'redo': {
name: 'Redo',
callback: function(){
this.redo();
},
disabled: function () {
return this.undoRedo && !this.undoRedo.isRedoAvailable();
}
},
"hsep4": ContextMenu.SEPARATOR,
'make_read_only': {
name: function() {
var atLeastOneReadOnly = contextMenu.checkSelectionReadOnlyConsistency(this);
if(!atLeastOneReadOnly) {
return "Make read-only";
} else {
return "Make writable";
}
},
callback: function() {
var atLeastOneReadOnly = contextMenu.checkSelectionReadOnlyConsistency(this);
var that = this;
this.getSelectedRange().forAll(function(r, c) {
that.getCellMeta(r, c).readOnly = atLeastOneReadOnly ? false : true;
});
this.render();
}
},
"hsep5": ContextMenu.SEPARATOR,
'horizontal_alignment': {
name: function () {
var div = document.createElement('div'),
button = document.createElement('button'),
lButton = button.cloneNode(true),
rButton = button.cloneNode(true),
cButton = button.cloneNode(true),
jButton = button.cloneNode(true),
lText = document.createTextNode('left'),
cText = document.createTextNode('center'),
rText = document.createTextNode('right'),
jText = document.createTextNode('justify');
lButton.appendChild(lText);
cButton.appendChild(cText);
rButton.appendChild(rText);
jButton.appendChild(jText);
Handsontable.Dom.addClass(lButton,'Left');
Handsontable.Dom.addClass(cButton,'Center');
Handsontable.Dom.addClass(rButton,'Right');
Handsontable.Dom.addClass(jButton,'Justify');
div.appendChild(lButton);
div.appendChild(cButton);
div.appendChild(rButton);
div.appendChild(jButton);
return div.outerHTML;
},
callback: function (key, selection ,event) {
var className = event.target.className,
type = event.target.tagName;
if (type === "BUTTON") {
if(className) {
align.call(this, this.getSelectedRange(),'horizontal','ht' + className );
}
}
},
disabled: function () {
return false;
}
},
"hsep6": ContextMenu.SEPARATOR,
'vertical_alignment': {
name: function () {
var div = document.createElement('div'),
button = document.createElement('button'),
tButton = button.cloneNode(true),
mButton = button.cloneNode(true),
bButton = button.cloneNode(true),
tText = document.createTextNode('top'),
mText = document.createTextNode('middle'),
bText = document.createTextNode('bottom');
tButton.appendChild(tText);
mButton.appendChild(mText);
bButton.appendChild(bText);
Handsontable.Dom.addClass(tButton,'Top');
Handsontable.Dom.addClass(mButton,'Middle');
Handsontable.Dom.addClass(bButton,'Bottom');
div.appendChild(tButton);
div.appendChild(mButton);
div.appendChild(bButton);
return div.outerHTML;
},
callback: function (key, selection ,event) {
var className = event.target.className,
type = event.target.tagName;
if (type === "BUTTON") {
if(className) {
align.call(this, this.getSelectedRange(),'vertical','ht' + className );
}
}
},
disabled: function () {
return false;
}
}
}
};
this.checkSelectionReadOnlyConsistency = function(hot) {
var atLeastOneReadOnly = false;
hot.getSelectedRange().forAll(function(r, c) {
if(hot.getCellMeta(r, c).readOnly) {
atLeastOneReadOnly = true;
return false; //breaks forAll
}
});
return atLeastOneReadOnly;
};
Handsontable.hooks.run(instance, 'afterContextMenuDefaultOptions', this.defaultOptions);
this.options = {};
Handsontable.helper.extend(this.options, this.defaultOptions);
this.updateOptions(customOptions);
function createMenu(){
var menu = $('body > .htContextMenu')[0];
if(!menu){
menu = document.createElement('DIV');
Handsontable.Dom.addClass(menu, 'htContextMenu');
document.getElementsByTagName('body')[0].appendChild(menu);
}
return menu;
}
}
ContextMenu.prototype.bindMouseEvents = function (){
function contextMenuOpenListener(event){
event.preventDefault();
var showRowHeaders = this.instance.getSettings().rowHeaders,
showColHeaders = this.instance.getSettings().colHeaders;
if(!(showRowHeaders || showColHeaders)) {
if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){
return;
}
}
//if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){
// return;
//}
this.show(event.pageY, event.pageX);
$(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this));
}
this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this));
};
ContextMenu.prototype.bindTableEvents = function () {
var that = this;
this._afterScrollCallback = function () {
that.close();
};
this.instance.addHook('afterScrollVertically', this._afterScrollCallback);
this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback);
};
ContextMenu.prototype.unbindTableEvents = function () {
if(this._afterScrollCallback){
this.instance.removeHook('afterScrollVertically', this._afterScrollCallback);
this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback);
this._afterScrollCallback = null;
}
};
ContextMenu.prototype.performAction = function (event){
var hot = $(this.menu).handsontable('getInstance');
var selectedItemIndex = hot.getSelected()[0];
var selectedItem = hot.getData()[selectedItemIndex];
if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){
return;
}
if(typeof selectedItem.callback != 'function'){
return;
}
var selRange = this.instance.getSelectedRange();
var normalizedSelection = ContextMenu.utils.normalizeSelection(selRange);
selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection, event);
};
ContextMenu.prototype.unbindMouseEvents = function () {
this.instance.rootElement.off('contextmenu.htContextMenu');
$(document).off('mousedown.htContextMenu');
};
ContextMenu.prototype.show = function(top, left){
this.menu.style.display = 'block';
$(this.menu)
.off('mousedown.htContextMenu')
.on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this));
$(this.menu).handsontable({
data: ContextMenu.utils.convertItemsToArray(this.getItems()),
colHeaders: false,
colWidths: [160],
readOnly: true,
copyPaste: false,
columns: [
{
data: 'name',
renderer: Handsontable.helper.proxy(this.renderer, this)
}
],
beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this),
renderAllRows: true
});
this.bindTableEvents();
this.setMenuPosition(top, left);
$(this.menu).handsontable('listen');
};
ContextMenu.prototype.close = function () {
this.hide();
$(document).off('mousedown.htContextMenu');
this.unbindTableEvents();
this.instance.listen();
};
ContextMenu.prototype.hide = function(){
this.menu.style.display = 'none';
$(this.menu).handsontable('destroy');
};
ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){
var contextMenu = this;
var item = instance.getData()[row];
var wrapper = document.createElement('DIV');
if(typeof value === 'function') {
value = value.call(this.instance);
}
Handsontable.Dom.empty(TD);
TD.appendChild(wrapper);
if(itemIsSeparator(item)){
Handsontable.Dom.addClass(TD, 'htSeparator');
} else {
Handsontable.Dom.fastInnerHTML(wrapper, value);
}
if (itemIsDisabled(item)){
Handsontable.Dom.addClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.deselectCell();
});
} else {
Handsontable.Dom.removeClass(TD, 'htDisabled');
$(wrapper).on('mouseenter', function () {
instance.selectCell(row, col);
});
}
function itemIsSeparator(item){
return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name);
}
function itemIsDisabled(item){
return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true);
}
};
ContextMenu.prototype.onBeforeKeyDown = function (event) {
var contextMenu = this;
var instance = $(contextMenu.menu).handsontable('getInstance');
var selection = instance.getSelected();
switch(event.keyCode){
case Handsontable.helper.keyCode.ESCAPE:
contextMenu.close();
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ENTER:
if(instance.getSelected()){
contextMenu.performAction();
contextMenu.close();
}
break;
case Handsontable.helper.keyCode.ARROW_DOWN:
if(!selection){
selectFirstCell(instance);
} else {
selectNextCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
case Handsontable.helper.keyCode.ARROW_UP:
if(!selection){
selectLastCell(instance);
} else {
selectPrevCell(selection[0], selection[1], instance);
}
event.preventDefault();
event.stopImmediatePropagation();
break;
}
function selectFirstCell(instance) {
var firstCell = instance.getCell(0, 0);
if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){
selectNextCell(0, 0, instance);
} else {
instance.selectCell(0, 0);
}
}
function selectLastCell(instance) {
var lastRow = instance.countRows() - 1;
var lastCell = instance.getCell(lastRow, 0);
if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){
selectPrevCell(lastRow, 0, instance);
} else {
instance.selectCell(lastRow, 0);
}
}
function selectNextCell(row, col, instance){
var nextRow = row + 1;
var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null;
if(!nextCell){
return;
}
if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){
selectNextCell(nextRow, col, instance);
} else {
instance.selectCell(nextRow, col);
}
}
function selectPrevCell(row, col, instance) {
var prevRow = row - 1;
var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null;
if (!prevCell) {
return;
}
if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){
selectPrevCell(prevRow, col, instance);
} else {
instance.selectCell(prevRow, col);
}
}
};
ContextMenu.prototype.getItems = function () {
var items = {};
function Item(rawItem){
if(typeof rawItem == 'string'){
this.name = rawItem;
} else {
Handsontable.helper.extend(this, rawItem);
}
}
Item.prototype = this.options;
for(var itemName in this.options.items){
if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){
items[itemName] = new Item(this.options.items[itemName]);
}
}
return items;
};
ContextMenu.prototype.updateOptions = function(newOptions){
newOptions = newOptions || {};
if(newOptions.items){
for(var itemName in newOptions.items){
var item = {};
if(newOptions.items.hasOwnProperty(itemName)) {
if(this.defaultOptions.items.hasOwnProperty(itemName)
&& Handsontable.helper.isObject(newOptions.items[itemName])){
Handsontable.helper.extend(item, this.defaultOptions.items[itemName]);
Handsontable.helper.extend(item, newOptions.items[itemName]);
newOptions.items[itemName] = item;
}
}
}
}
Handsontable.helper.extend(this.options, newOptions);
};
ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) {
var scrollTop = Handsontable.Dom.getWindowScrollTop();
var scrollLeft = Handsontable.Dom.getWindowScrollLeft();
var cursor = {
top: cursorY,
topRelative: cursorY - scrollTop,
left: cursorX,
leftRelative:cursorX - scrollLeft,
scrollTop: scrollTop,
scrollLeft: scrollLeft
};
if(this.menuFitsBelowCursor(cursor)){
this.positionMenuBelowCursor(cursor);
} else {
if (this.menuFitsAboveCursor(cursor)) {
this.positionMenuAboveCursor(cursor);
} else {
this.positionMenuBelowCursor(cursor);
}
}
if(this.menuFitsOnRightOfCursor(cursor)){
this.positionMenuOnRightOfCursor(cursor);
} else {
this.positionMenuOnLeftOfCursor(cursor);
}
};
ContextMenu.prototype.menuFitsAboveCursor = function (cursor) {
return cursor.topRelative >= this.menu.offsetHeight;
};
ContextMenu.prototype.menuFitsBelowCursor = function (cursor) {
return cursor.topRelative + this.menu.offsetHeight <= cursor.scrollTop + document.body.clientHeight;
};
ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) {
return cursor.leftRelative + this.menu.offsetWidth <= cursor.scrollLeft + document.body.clientWidth;
};
ContextMenu.prototype.positionMenuBelowCursor = function (cursor) {
this.menu.style.top = cursor.top + 'px';
};
ContextMenu.prototype.positionMenuAboveCursor = function (cursor) {
this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px';
};
ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) {
this.menu.style.left = cursor.left + 'px';
};
ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) {
this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px';
};
ContextMenu.utils = {};
ContextMenu.utils.convertItemsToArray = function (items) {
var itemArray = [];
var item;
for(var itemName in items){
if(items.hasOwnProperty(itemName)){
if(typeof items[itemName] == 'string'){
item = {name: items[itemName]};
} else if (items[itemName].visible !== false) {
item = items[itemName];
} else {
continue;
}
item.key = itemName;
itemArray.push(item);
}
}
return itemArray;
};
ContextMenu.utils.normalizeSelection = function(selRange){
return {
start: selRange.getTopLeftCorner(),
end: selRange.getBottomRightCorner()
};
};
ContextMenu.utils.isSeparator = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htSeparator');
};
ContextMenu.utils.isDisabled = function (cell) {
return Handsontable.Dom.hasClass(cell, 'htDisabled');
};
ContextMenu.prototype.enable = function () {
if(!this.enabled){
this.enabled = true;
this.bindMouseEvents();
}
};
ContextMenu.prototype.disable = function () {
if(this.enabled){
this.enabled = false;
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
}
};
ContextMenu.prototype.destroy = function () {
this.close();
this.unbindMouseEvents();
this.unbindTableEvents();
if(!this.isMenuEnabledByOtherHotInstance()){
this.removeMenu();
}
};
ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () {
var hotContainers = $('.handsontable');
var menuEnabled = false;
for(var i = 0, len = hotContainers.length; i < len; i++){
var instance = $(hotContainers[i]).handsontable('getInstance');
if(instance && instance.getSettings().contextMenu){
menuEnabled = true;
break;
}
}
return menuEnabled;
};
ContextMenu.prototype.removeMenu = function () {
if(this.menu.parentNode){
this.menu.parentNode.removeChild(this.menu);
}
};
ContextMenu.prototype.filterItems = function(itemsToLeave){
this.itemsFilter = itemsToLeave;
};
ContextMenu.SEPARATOR = "---------";
function updateHeight() {
if(this.rootElement[0].className.indexOf('htContextMenu')) {
return;
}
var realSeparatorHeight = 0,
realEntrySize = 0,
dataSize = this.getSettings().data.length;
for(var i = 0; i < dataSize; i++) {
if(this.getSettings().data[i].name == ContextMenu.SEPARATOR) {
realSeparatorHeight += 2;
} else {
realEntrySize += 26;
}
}
this.view.wt.wtScrollbars.vertical.fixedContainer.style.height = realEntrySize + realSeparatorHeight + "px";
}
function init(){
var instance = this;
var contextMenuSetting = instance.getSettings().contextMenu;
var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {};
if(contextMenuSetting){
if(!instance.contextMenu){
instance.contextMenu = new ContextMenu(instance, customOptions);
}
instance.contextMenu.enable();
if(Handsontable.helper.isArray(contextMenuSetting)){
instance.contextMenu.filterItems(contextMenuSetting);
}
} else if(instance.contextMenu){
instance.contextMenu.destroy();
delete instance.contextMenu;
}
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
Handsontable.hooks.add('afterInit',updateHeight);
if(Handsontable.PluginHooks.register) { //HOT 0.11+
Handsontable.PluginHooks.register('afterContextMenuDefaultOptions');
}
Handsontable.ContextMenu = ContextMenu;
})(Handsontable);
function HandsontableManualColumnMove() {
var pressed
, startCol
, endCol
, startX
, startOffset;
var ghost = document.createElement('DIV')
, ghostStyle = ghost.style;
ghost.className = 'ghost';
ghostStyle.position = 'absolute';
ghostStyle.top = '25px';
ghostStyle.left = 0;
ghostStyle.width = '10px';
ghostStyle.height = '10px';
ghostStyle.backgroundColor = '#CCC';
ghostStyle.opacity = 0.7;
var saveManualColumnPositions = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions);
};
var loadManualColumnPositions = function () {
var instance = this;
var storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualColumnPositions', storedState);
return storedState.value;
};
var bindMoveColEvents = function () {
var instance = this;
instance.rootElement.on('mousemove.manualColumnMove', function (e) {
if (pressed) {
ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px';
if (ghostStyle.display === 'none') {
ghostStyle.display = 'block';
}
}
});
instance.rootElement.on('mouseup.manualColumnMove', function () {
if (pressed) {
if (startCol < endCol) {
endCol--;
}
if (instance.getSettings().rowHeaders) {
startCol--;
endCol--;
}
instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]);
$('.manualColumnMover.active').removeClass('active');
pressed = false;
instance.forceFullRender = true;
instance.view.render(); //updates all
ghostStyle.display = 'none';
saveManualColumnPositions.call(instance);
Handsontable.hooks.run(instance, 'afterColumnMove', startCol, endCol);
}
});
instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) {
var mover = e.currentTarget;
var TH = Handsontable.Dom.closest(mover, 'TH');
startCol = Handsontable.Dom.index(TH) + instance.colOffset();
endCol = startCol;
pressed = true;
startX = e.pageX;
var TABLE = instance.$table[0];
TABLE.parentNode.appendChild(ghost);
ghostStyle.width = Handsontable.Dom.outerWidth(TH) + 'px';
ghostStyle.height = Handsontable.Dom.outerHeight(TABLE) + 'px';
startOffset = parseInt(Handsontable.Dom.offset(TH).left - Handsontable.Dom.offset(TABLE).left, 10);
ghostStyle.left = startOffset + 6 + 'px';
});
instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () {
if (pressed) {
var active = instance.view.THEAD.querySelector('.manualColumnMover.active');
if (active) {
Handsontable.Dom.removeClass(active, 'active');
}
endCol = Handsontable.Dom.index(this) + instance.colOffset();
var THs = instance.view.THEAD.querySelectorAll('th');
var mover = THs[endCol].querySelector('.manualColumnMover');
Handsontable.Dom.addClass(mover, 'active');
}
});
instance.addHook('afterDestroy', unbindMoveColEvents);
};
var unbindMoveColEvents = function(){
var instance = this;
instance.rootElement.off('mouseup.manualColumnMove');
instance.rootElement.off('mousemove.manualColumnMove');
instance.rootElement.off('mousedown.manualColumnMove');
instance.rootElement.off('mouseenter.manualColumnMove');
};
this.beforeInit = function () {
this.manualColumnPositions = [];
};
this.init = function (source) {
var instance = this;
var manualColMoveEnabled = !!(this.getSettings().manualColumnMove);
if (manualColMoveEnabled) {
var initialManualColumnPositions = this.getSettings().manualColumnMove;
var loadedManualColumnPositions = loadManualColumnPositions.call(instance);
if (typeof loadedManualColumnPositions != 'undefined') {
this.manualColumnPositions = loadedManualColumnPositions;
} else if (initialManualColumnPositions instanceof Array) {
this.manualColumnPositions = initialManualColumnPositions;
} else {
this.manualColumnPositions = [];
}
instance.forceFullRender = true;
if (source == 'afterInit') {
bindMoveColEvents.call(this);
if (this.manualColumnPositions.length > 0) {
this.forceFullRender = true;
this.render();
}
}
} else {
unbindMoveColEvents.call(this);
this.manualColumnPositions = [];
}
};
this.modifyCol = function (col) {
//TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2
if (this.getSettings().manualColumnMove) {
if (typeof this.manualColumnPositions[col] === 'undefined') {
this.manualColumnPositions[col] = col;
}
return this.manualColumnPositions[col];
}
return col;
};
this.getColHeader = function (col, TH) {
if (this.getSettings().manualColumnMove) {
var DIV = document.createElement('DIV');
DIV.className = 'manualColumnMover';
TH.firstChild.appendChild(DIV);
}
};
}
var htManualColumnMove = new HandsontableManualColumnMove();
Handsontable.hooks.add('beforeInit', htManualColumnMove.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualColumnMove.init.call(this, 'afterInit')
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualColumnMove.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('afterGetColHeader', htManualColumnMove.getColHeader);
Handsontable.hooks.add('modifyCol', htManualColumnMove.modifyCol);
Handsontable.hooks.register('afterColumnMove');
function HandsontableManualColumnResize() {
var pressed
, currentTH
, currentCol
, currentWidth
, instance
, newSize
, startX
, startWidth
, startOffset
, scrollTop = 0
, scrollLeft = 0
, resizer = document.createElement('DIV')
, handle = document.createElement('DIV')
, line = document.createElement('DIV')
, lineStyle = line.style;
resizer.className = 'manualColumnResizer';
handle.className = 'manualColumnResizerHandle';
resizer.appendChild(handle);
line.className = 'manualColumnResizerLine';
resizer.appendChild(line);
var $document = $(document);
$document.mousemove(function (e) {
if (pressed) {
currentWidth = startWidth + (e.pageX - startX);
newSize = setManualSize(currentCol, currentWidth); //save col width
resizer.style.left = startOffset + currentWidth + 'px';
}
});
$document.mouseup(function () {
if (pressed) {
Handsontable.Dom.removeClass(resizer, 'active');
pressed = false;
if(newSize != startWidth){
instance.forceFullRender = true;
instance.view.render(); //updates all
saveManualColumnWidths.call(instance);
Handsontable.hooks.run(instance, 'afterColumnResize', currentCol, newSize);
}
refreshResizerPosition.call(instance, currentTH);
}
});
var saveManualColumnWidths = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths);
};
var loadManualColumnWidths = function () {
var instance = this;
var storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualColumnWidths', storedState);
return storedState.value;
};
function refreshResizerPosition(TH) {
instance = this;
currentTH = TH;
var col = this.view.wt.wtTable.getCoords(TH).col; //getCoords returns WalkontableCellCoords
if (col >= 0) { //if not row header
currentCol = col;
var rootOffset = Handsontable.Dom.offset(this.rootElement[0]).left;
var thOffset = Handsontable.Dom.offset(TH).left;
startOffset = (thOffset - rootOffset) - 6 + scrollLeft;
resizer.style.left = startOffset + parseInt(Handsontable.Dom.outerWidth(TH), 10) + 'px';
resizer.style.top = scrollTop + 'px';
this.rootElement[0].appendChild(resizer);
}
}
function refreshLinePosition() {
var instance = this;
startWidth = parseInt(Handsontable.Dom.outerWidth(currentTH), 10);
Handsontable.Dom.addClass(resizer, 'active');
lineStyle.height = Handsontable.Dom.outerHeight(instance.$table[0]) + 'px';
pressed = instance;
}
var bindManualColumnWidthEvents = function () {
var instance = this;
var dblclick = 0;
var autoresizeTimeout = null;
this.rootElement.on('mouseenter.handsontable', 'table thead tr > th', function (e) {
if (!pressed) {
refreshResizerPosition.call(instance, e.currentTarget);
}
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () {
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
newSize = instance.determineColumnWidth.call(instance, currentCol);
setManualSize(currentCol, newSize);
instance.forceFullRender = true;
instance.view.render(); //updates all
Handsontable.hooks.run(instance, 'afterColumnResize', currentCol, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 500);
}
dblclick++;
});
this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) {
startX = e.pageX;
refreshLinePosition.call(instance);
newSize = startWidth;
});
};
this.beforeInit = function () {
this.manualColumnWidths = [];
};
this.init = function (source) {
var instance = this;
var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize);
if (manualColumnWidthEnabled) {
var initialColumnWidths = this.getSettings().manualColumnResize;
var loadedManualColumnWidths = loadManualColumnWidths.call(instance);
if (typeof loadedManualColumnWidths != 'undefined') {
this.manualColumnWidths = loadedManualColumnWidths;
} else if (initialColumnWidths instanceof Array) {
this.manualColumnWidths = initialColumnWidths;
} else {
this.manualColumnWidths = [];
}
if (source == 'afterInit') {
bindManualColumnWidthEvents.call(this);
instance.forceFullRender = true;
instance.render();
Handsontable.hooks.add('afterScrollVertically', afterScrollVertically);
Handsontable.hooks.add('afterScrollHorizontally', afterScrollHorizontally);
}
}
};
var setManualSize = function (col, width) {
width = Math.max(width, 20);
/**
* We need to run col through modifyCol hook, in case the order of displayed columns is different than the order
* in data source. For instance, this order can be modified by manualColumnMove plugin.
*/
col = Handsontable.hooks.execute(instance, 'modifyCol', col);
instance.manualColumnWidths[col] = width;
return width;
};
this.modifyColWidth = function (width, col) {
col = this.runHooksAndReturn('modifyCol', col);
if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) {
return this.manualColumnWidths[col];
}
return width;
};
var afterScrollVertically = function () {
scrollTop = Handsontable.Dom.getScrollTop(this.rootElement[0]);
};
var afterScrollHorizontally = function () {
scrollLeft = Handsontable.Dom.getScrollLeft(this.rootElement[0]);
}
}
var htManualColumnResize = new HandsontableManualColumnResize();
Handsontable.hooks.add('beforeInit', htManualColumnResize.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualColumnResize.init.call(this, 'afterInit')
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualColumnResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyColWidth', htManualColumnResize.modifyColWidth);
Handsontable.hooks.register('afterColumnResize');
(function (Handsontable) {
function HandsontableManualRowResize () {
var pressed
, currentTH
, currentRow
, currentHeight
, instance
, newSize
, startY
, startHeight
, startOffset
, scrollTop = 0
, scrollLeft = 0
, resizer = document.createElement('DIV')
, handle = document.createElement('DIV')
, line = document.createElement('DIV')
, lineStyle = line.style;
resizer.className = 'manualRowResizer';
handle.className = 'manualRowResizerHandle';
resizer.appendChild(handle);
line.className = 'manualRowResizerLine';
resizer.appendChild(line);
var $document = $(document);
$document.mousemove(function (e) {
if (pressed) {
currentHeight = startHeight + (e.pageY - startY);
newSize = setManualSize(currentRow, currentHeight);
resizer.style.top = startOffset + currentHeight + 'px';
}
});
$document.mouseup(function () {
if (pressed) {
Handsontable.Dom.removeClass(resizer, 'active');
pressed = false;
if (newSize != startHeight) {
instance.forceFullRender = true;
instance.view.render();
saveManualRowHeights.call(instance);
Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize);
}
refreshResizerPosition.call(instance, currentTH);
}
});
var saveManualRowHeights = function () {
var instance = this;
Handsontable.hooks.run(instance, 'persistentStateSave', 'manualRowHeights', instance.manualRowHeights);
};
var loadManualRowHeights = function () {
var instance = this
, storedState = {};
Handsontable.hooks.run(instance, 'persistentStateLoad', 'manualRowHeights', storedState);
return storedState.value;
};
var refreshResizerPosition = function(TH) {
instance = this;
currentTH = TH;
var row = this.view.wt.wtTable.getCoords(TH).row; //getCoords returns WalkontableCellCoords
if (row >= 0) { //if not row header
currentRow = row;
var rootOffset = Handsontable.Dom.offset(this.rootElement[0]).top;
var thOffset = Handsontable.Dom.offset(TH).top;
startOffset = (thOffset - rootOffset) + scrollTop - 4;
resizer.style.top = startOffset + parseInt(Handsontable.Dom.outerHeight(TH), 10) + 'px';
resizer.style.left = scrollLeft + 'px';
this.rootElement[0].appendChild(resizer);
}
}
var refreshLinePosition = function() {
var instance = this;
startHeight = parseInt(Handsontable.Dom.outerHeight(currentTH), 10);
Handsontable.Dom.addClass(resizer, 'active');
lineStyle.width = Handsontable.Dom.outerWidth(instance.$table[0]) + 'px';
pressed = instance;
}
var bindManualRowHeightEvents = function () {
var instance = this,
autoresizeTimeout = null,
dblclick = 0;
instance.rootElement.on('mouseenter.handsontable', 'table tbody tr > th', function (e) {
if (!pressed) {
refreshResizerPosition.call(instance, e.currentTarget);
}
});
instance.rootElement.on('mousedown.handsontable', '.manualRowResizer', function () {
if (autoresizeTimeout == null) {
autoresizeTimeout = setTimeout(function () {
if (dblclick >= 2) {
setManualSize(currentRow, null); //double click sets auto row size
instance.forceFullRender = true;
instance.view.render();
Handsontable.hooks.run(instance, 'afterRowResize', currentRow, newSize);
}
dblclick = 0;
autoresizeTimeout = null;
}, 200);
}
dblclick++;
});
instance.rootElement.on('mousedown.handsontable', '.manualRowResizer', function (e) {
startY = e.pageY;
refreshLinePosition.call(instance);
newSize = startHeight;
});
};
this.beforeInit = function () {
this.manualRowHeights = [];
};
this.init = function (source) {
var instance = this;
var manualColumnHeightEnabled = !!(this.getSettings().manualRowResize);
if (manualColumnHeightEnabled) {
var initialRowHeights = this.getSettings().manualRowResize;
var loadedManualRowHeights = loadManualRowHeights.call(instance);
if (typeof loadedManualRowHeights != 'undefined') {
this.manualRowHeights = loadedManualRowHeights;
} else if (initialRowHeights instanceof Array) {
this.manualRowHeights = initialRowHeights;
} else {
this.manualRowHeights = [];
}
if (source === 'afterInit') {
bindManualRowHeightEvents.call(this);
instance.forceFullRender = true;
instance.render();
Handsontable.hooks.add('afterScrollVertically', afterScrollVertically);
Handsontable.hooks.add('afterScrollHorizontally', afterScrollHorizontally);
}
}
};
var setManualSize = function (row, height) {
row = Handsontable.hooks.execute(instance, 'modifyRow', row);
instance.manualRowHeights[row] = height;
return height;
};
this.modifyRowHeight = function (height, row) {
if (this.getSettings().manualRowResize) {
row = this.runHooksAndReturn('modifyRow', row);
if (this.manualRowHeights[row] !== void 0) {
return this.manualRowHeights[row];
}
}
return height;
};
var afterScrollVertically = function () {
scrollTop = Handsontable.Dom.getScrollTop(this.rootElement[0]);
};
var afterScrollHorizontally = function () {
scrollLeft = Handsontable.Dom.getScrollLeft(this.rootElement[0]);
}
}
var htManualRowResize = new HandsontableManualRowResize();
Handsontable.hooks.add('beforeInit', htManualRowResize.beforeInit);
Handsontable.hooks.add('afterInit', function () {
htManualRowResize.init.call(this, 'afterInit');
});
Handsontable.hooks.add('afterUpdateSettings', function () {
htManualRowResize.init.call(this, 'afterUpdateSettings')
});
Handsontable.hooks.add('modifyRowHeight', htManualRowResize.modifyRowHeight);
Handsontable.hooks.register('afterRowResize');
})(Handsontable);
(function HandsontableObserveChanges() {
Handsontable.hooks.add('afterLoadData', init);
Handsontable.hooks.add('afterUpdateSettings', init);
Handsontable.hooks.register('afterChangesObserved');
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().observeChanges;
if (pluginEnabled) {
if(instance.observer) {
destroy.call(instance); //destroy observer for old data object
}
createObserver.call(instance);
bindEvents.call(instance);
} else if (!pluginEnabled){
destroy.call(instance);
}
}
function createObserver(){
var instance = this;
instance.observeChangesActive = true;
instance.pauseObservingChanges = function(){
instance.observeChangesActive = false;
};
instance.resumeObservingChanges = function(){
instance.observeChangesActive = true;
};
instance.observedData = instance.getData();
instance.observer = jsonpatch.observe(instance.observedData, function (patches) {
if(instance.observeChangesActive){
runHookForOperation.call(instance, patches);
instance.render();
}
instance.runHooks('afterChangesObserved');
});
}
function runHookForOperation(rawPatches){
var instance = this;
var patches = cleanPatches(rawPatches);
for(var i = 0, len = patches.length; i < len; i++){
var patch = patches[i];
var parsedPath = parsePath(patch.path);
switch(patch.op){
case 'add':
if(isNaN(parsedPath.col)){
instance.runHooks('afterCreateRow', parsedPath.row);
} else {
instance.runHooks('afterCreateCol', parsedPath.col);
}
break;
case 'remove':
if(isNaN(parsedPath.col)){
instance.runHooks('afterRemoveRow', parsedPath.row, 1);
} else {
instance.runHooks('afterRemoveCol', parsedPath.col, 1);
}
break;
case 'replace':
instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external');
break;
}
}
function cleanPatches(rawPatches){
var patches;
patches = removeLengthRelatedPatches(rawPatches);
patches = removeMultipleAddOrRemoveColPatches(patches);
return patches;
}
/**
* Removing or adding column will produce one patch for each table row.
* This function leaves only one patch for each column add/remove operation
*/
function removeMultipleAddOrRemoveColPatches(rawPatches){
var newOrRemovedColumns = [];
return rawPatches.filter(function(patch){
var parsedPath = parsePath(patch.path);
if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){
if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){
return false;
} else {
newOrRemovedColumns.push(parsedPath.col);
}
}
return true;
});
}
/**
* If observeChanges uses native Object.observe method, then it produces patches for length property.
* This function removes them.
*/
function removeLengthRelatedPatches(rawPatches){
return rawPatches.filter(function(patch){
return !/[/]length/ig.test(patch.path);
})
}
function parsePath(path){
var match = path.match(/^\/(\d+)\/?(.*)?$/);
return {
row: parseInt(match[1], 10),
col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2]
}
}
}
function destroy(){
var instance = this;
if (instance.observer){
destroyObserver.call(instance);
unbindEvents.call(instance);
}
}
function destroyObserver(){
var instance = this;
jsonpatch.unobserve(instance.observedData, instance.observer);
delete instance.observeChangesActive;
delete instance.pauseObservingChanges;
delete instance.resumeObservingChanges;
}
function bindEvents(){
var instance = this;
instance.addHook('afterDestroy', destroy);
instance.addHook('afterCreateRow', afterTableAlter);
instance.addHook('afterRemoveRow', afterTableAlter);
instance.addHook('afterCreateCol', afterTableAlter);
instance.addHook('afterRemoveCol', afterTableAlter);
instance.addHook('afterChange', function(changes, source){
if(source != 'loadData'){
afterTableAlter.call(this);
}
});
}
function unbindEvents(){
var instance = this;
instance.removeHook('afterDestroy', destroy);
instance.removeHook('afterCreateRow', afterTableAlter);
instance.removeHook('afterRemoveRow', afterTableAlter);
instance.removeHook('afterCreateCol', afterTableAlter);
instance.removeHook('afterRemoveCol', afterTableAlter);
instance.removeHook('afterChange', afterTableAlter);
}
function afterTableAlter(){
var instance = this;
instance.pauseObservingChanges();
instance.addHookOnce('afterChangesObserved', function(){
instance.resumeObservingChanges();
});
}
})();
/*
*
* Plugin enables saving table state
*
* */
function Storage(prefix) {
var savedKeys;
var saveSavedKeys = function () {
window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys);
};
var loadSavedKeys = function () {
var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys'];
var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0;
savedKeys = keys ? keys : [];
};
var clearSavedKeys = function () {
savedKeys = [];
saveSavedKeys();
};
loadSavedKeys();
this.saveValue = function (key, value) {
window.localStorage[prefix + '_' + key] = JSON.stringify(value);
if (savedKeys.indexOf(key) == -1) {
savedKeys.push(key);
saveSavedKeys();
}
};
this.loadValue = function (key, defaultValue) {
key = typeof key != 'undefined' ? key : defaultValue;
var value = window.localStorage[prefix + '_' + key];
return typeof value == "undefined" ? void 0 : JSON.parse(value);
};
this.reset = function (key) {
window.localStorage.removeItem(prefix + '_' + key);
};
this.resetAll = function () {
for (var index = 0; index < savedKeys.length; index++) {
window.localStorage.removeItem(prefix + '_' + savedKeys[index]);
}
clearSavedKeys();
};
}
(function (StorageClass) {
function HandsontablePersistentState() {
var plugin = this;
this.init = function () {
var instance = this,
pluginSettings = instance.getSettings()['persistentState'];
plugin.enabled = !!(pluginSettings);
if (!plugin.enabled) {
removeHooks.call(instance);
return;
}
if (!instance.storage) {
instance.storage = new StorageClass(instance.rootElement[0].id);
}
instance.resetState = plugin.resetValue;
addHooks.call(instance);
};
this.saveValue = function (key, value) {
var instance = this;
instance.storage.saveValue(key, value);
};
this.loadValue = function (key, saveTo) {
var instance = this;
saveTo.value = instance.storage.loadValue(key);
};
this.resetValue = function (key) {
var instance = this;
if (typeof key != 'undefined') {
instance.storage.reset(key);
} else {
instance.storage.resetAll();
}
};
var hooks = {
'persistentStateSave': plugin.saveValue,
'persistentStateLoad': plugin.loadValue,
'persistentStateReset': plugin.resetValue
};
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName)) {
Handsontable.hooks.register(hookName);
}
}
function addHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName)) {
instance.addHook(hookName, hooks[hookName]);
}
}
}
function removeHooks() {
var instance = this;
for (var hookName in hooks) {
if (hooks.hasOwnProperty(hookName)) {
instance.removeHook(hookName, hooks[hookName]);
}
}
}
}
var htPersistentState = new HandsontablePersistentState();
Handsontable.hooks.add('beforeInit', htPersistentState.init);
Handsontable.hooks.add('afterUpdateSettings', htPersistentState.init);
})(Storage);
/**
* Handsontable UndoRedo class
*/
(function(Handsontable){
Handsontable.UndoRedo = function (instance) {
var plugin = this;
this.instance = instance;
this.doneActions = [];
this.undoneActions = [];
this.ignoreNewActions = false;
instance.addHook("afterChange", function (changes, origin) {
if(changes){
var action = new Handsontable.UndoRedo.ChangeAction(changes);
plugin.done(action);
}
});
instance.addHook("afterCreateRow", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateRowAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveRow", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( originalData.length + index ) % originalData.length;
var removedData = originalData.slice(index, index + amount);
var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData);
plugin.done(action);
});
instance.addHook("afterCreateCol", function (index, amount, createdAutomatically) {
if (createdAutomatically) {
return;
}
var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount);
plugin.done(action);
});
instance.addHook("beforeRemoveCol", function (index, amount) {
var originalData = plugin.instance.getData();
index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols();
var removedData = [];
for (var i = 0, len = originalData.length; i < len; i++) {
removedData[i] = originalData[i].slice(index, index + amount);
}
var headers;
if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){
headers = instance.getSettings().colHeaders.slice(index, index + removedData.length);
}
var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers);
plugin.done(action);
});
};
Handsontable.UndoRedo.prototype.done = function (action) {
if (!this.ignoreNewActions) {
this.doneActions.push(action);
this.undoneActions.length = 0;
}
};
/**
* Undo operation from current revision
*/
Handsontable.UndoRedo.prototype.undo = function () {
if (this.isUndoAvailable()) {
var action = this.doneActions.pop();
this.ignoreNewActions = true;
var that = this;
action.undo(this.instance, function () {
that.ignoreNewActions = false;
that.undoneActions.push(action);
});
}
};
/**
* Redo operation from current revision
*/
Handsontable.UndoRedo.prototype.redo = function () {
if (this.isRedoAvailable()) {
var action = this.undoneActions.pop();
this.ignoreNewActions = true;
var that = this;
action.redo(this.instance, function () {
that.ignoreNewActions = false;
that.doneActions.push(action);
});
}
};
/**
* Returns true if undo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isUndoAvailable = function () {
return this.doneActions.length > 0;
};
/**
* Returns true if redo point is available
* @return {Boolean}
*/
Handsontable.UndoRedo.prototype.isRedoAvailable = function () {
return this.undoneActions.length > 0;
};
/**
* Clears undo history
*/
Handsontable.UndoRedo.prototype.clear = function () {
this.doneActions.length = 0;
this.undoneActions.length = 0;
};
Handsontable.UndoRedo.Action = function () {
};
Handsontable.UndoRedo.Action.prototype.undo = function () {
};
Handsontable.UndoRedo.Action.prototype.redo = function () {
};
Handsontable.UndoRedo.ChangeAction = function (changes) {
this.changes = changes;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance, undoneCallback) {
var data = $.extend(true, [], this.changes),
emptyRowsAtTheEnd = instance.countEmptyRows(true),
emptyColsAtTheEnd = instance.countEmptyCols(true);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(3, 1);
}
instance.addHookOnce('afterChange', undoneCallback);
instance.setDataAtRowProp(data, null, null, 'undo');
for (var i = 0, len = data.length; i < len; i++) {
if(instance.getSettings().minSpareRows &&
data[i][0] + 1 + instance.getSettings().minSpareRows === instance.countRows()
&& emptyRowsAtTheEnd == instance.getSettings().minSpareRows) {
instance.alter('remove_row', parseInt(data[i][0]+1,10), instance.getSettings().minSpareRows);
instance.undoRedo.doneActions.pop();
}
if (instance.getSettings().minSpareCols &&
data[i][1] + 1 + instance.getSettings().minSpareCols === instance.countCols()
&& emptyColsAtTheEnd == instance.getSettings().minSpareCols) {
instance.alter('remove_col', parseInt(data[i][1]+1,10), instance.getSettings().minSpareCols);
instance.undoRedo.doneActions.pop();
}
}
};
Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance, onFinishCallback) {
var data = $.extend(true, [], this.changes);
for (var i = 0, len = data.length; i < len; i++) {
data[i].splice(2, 1);
}
instance.addHookOnce('afterChange', onFinishCallback);
instance.setDataAtRowProp(data, null, null, 'redo');
};
Handsontable.UndoRedo.CreateRowAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance, undoneCallback) {
instance.addHookOnce('afterRemoveRow', undoneCallback);
instance.alter('remove_row', this.index, this.amount);
};
Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterCreateRow', redoneCallback);
instance.alter('insert_row', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveRowAction = function (index, data) {
this.index = index;
this.data = data;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance, undoneCallback) {
var spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data);
Array.prototype.splice.apply(instance.getData(), spliceArgs);
instance.addHookOnce('afterRender', undoneCallback);
instance.render();
};
Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterRemoveRow', redoneCallback);
instance.alter('remove_row', this.index, this.data.length);
};
Handsontable.UndoRedo.CreateColumnAction = function (index, amount) {
this.index = index;
this.amount = amount;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance, undoneCallback) {
instance.addHookOnce('afterRemoveCol', undoneCallback);
instance.alter('remove_col', this.index, this.amount);
};
Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterCreateCol', redoneCallback);
instance.alter('insert_col', this.index + 1, this.amount);
};
Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) {
this.index = index;
this.data = data;
this.amount = this.data[0].length;
this.headers = headers;
};
Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action);
Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance, undoneCallback) {
var row, spliceArgs;
for (var i = 0, len = instance.getData().length; i < len; i++) {
row = instance.getDataAtRow(i);
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.data[i]);
Array.prototype.splice.apply(row, spliceArgs);
}
if(typeof this.headers != 'undefined'){
spliceArgs = [this.index, 0];
Array.prototype.push.apply(spliceArgs, this.headers);
Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs);
}
instance.addHookOnce('afterRender', undoneCallback);
instance.render();
};
Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance, redoneCallback) {
instance.addHookOnce('afterRemoveCol', redoneCallback);
instance.alter('remove_col', this.index, this.amount);
};
})(Handsontable);
(function(Handsontable){
function init(){
var instance = this;
var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo;
if(pluginEnabled){
if(!instance.undoRedo){
instance.undoRedo = new Handsontable.UndoRedo(instance);
exposeUndoRedoMethods(instance);
instance.addHook('beforeKeyDown', onBeforeKeyDown);
instance.addHook('afterChange', onAfterChange);
}
} else {
if(instance.undoRedo){
delete instance.undoRedo;
removeExposedUndoRedoMethods(instance);
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
instance.removeHook('afterChange', onAfterChange);
}
}
}
function onBeforeKeyDown(event){
var instance = this;
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
if(ctrlDown){
if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z
instance.undoRedo.redo();
event.stopImmediatePropagation();
}
else if (event.keyCode === 90) { //CTRL + Z
instance.undoRedo.undo();
event.stopImmediatePropagation();
}
}
}
function onAfterChange(changes, source){
var instance = this;
if (source == 'loadData'){
return instance.undoRedo.clear();
}
}
function exposeUndoRedoMethods(instance){
instance.undo = function(){
return instance.undoRedo.undo();
};
instance.redo = function(){
return instance.undoRedo.redo();
};
instance.isUndoAvailable = function(){
return instance.undoRedo.isUndoAvailable();
};
instance.isRedoAvailable = function(){
return instance.undoRedo.isRedoAvailable();
};
instance.clearUndo = function(){
return instance.undoRedo.clear();
};
}
function removeExposedUndoRedoMethods(instance){
delete instance.undo;
delete instance.redo;
delete instance.isUndoAvailable;
delete instance.isRedoAvailable;
delete instance.clearUndo;
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
})(Handsontable);
/**
* Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport
* @constructor
*/
function DragToScroll() {
this.boundaries = null;
this.callback = null;
}
/**
* @param boundaries {Object} compatible with getBoundingClientRect
*/
DragToScroll.prototype.setBoundaries = function (boundaries) {
this.boundaries = boundaries;
};
/**
* @param callback {Function}
*/
DragToScroll.prototype.setCallback = function (callback) {
this.callback = callback;
};
/**
* Check if mouse position (x, y) is outside of the viewport
* @param x
* @param y
*/
DragToScroll.prototype.check = function (x, y) {
var diffX = 0;
var diffY = 0;
if (y < this.boundaries.top) {
//y is less than top
diffY = y - this.boundaries.top;
}
else if (y > this.boundaries.bottom) {
//y is more than bottom
diffY = y - this.boundaries.bottom;
}
if (x < this.boundaries.left) {
//x is less than left
diffX = x - this.boundaries.left;
}
else if (x > this.boundaries.right) {
//x is more than right
diffX = x - this.boundaries.right;
}
this.callback(diffX, diffY);
};
var dragToScroll;
var instance;
if (typeof Handsontable !== 'undefined') {
var setupListening = function (instance) {
instance.dragToScrollListening = false;
var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll
dragToScroll = new DragToScroll();
if (scrollHandler === window) {
//not much we can do currently
return;
}
else if (scrollHandler) {
dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect());
}
else {
dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect());
}
dragToScroll.setCallback(function (scrollX, scrollY) {
if (scrollX < 0) {
if (scrollHandler) {
scrollHandler.scrollLeft -= 50;
}
else {
instance.view.wt.scrollHorizontal(-1).draw();
}
}
else if (scrollX > 0) {
if (scrollHandler) {
scrollHandler.scrollLeft += 50;
}
else {
instance.view.wt.scrollHorizontal(1).draw();
}
}
if (scrollY < 0) {
if (scrollHandler) {
scrollHandler.scrollTop -= 20;
}
else {
instance.view.wt.scrollVertical(-1).draw();
}
}
else if (scrollY > 0) {
if (scrollHandler) {
scrollHandler.scrollTop += 20;
}
else {
instance.view.wt.scrollVertical(1).draw();
}
}
});
instance.dragToScrollListening = true;
};
Handsontable.hooks.add('afterInit', function () {
var instance = this;
$(document).on('mouseup.' + this.guid, function () {
instance.dragToScrollListening = false;
});
$(document).on('mousemove.' + this.guid, function (event) {
if (instance.dragToScrollListening) {
dragToScroll.check(event.clientX, event.clientY);
}
});
});
Handsontable.hooks.add('afterDestroy', function () {
$(document).off('.' + this.guid);
});
Handsontable.hooks.add('afterOnCellMouseDown', function () {
setupListening(this);
});
Handsontable.hooks.add('afterOnCellCornerMouseDown', function () {
setupListening(this);
});
Handsontable.plugins.DragToScroll = DragToScroll;
}
(function (Handsontable, CopyPaste, SheetClip) {
function CopyPastePlugin(instance) {
this.copyPasteInstance = CopyPaste.getInstance();
this.copyPasteInstance.onCut(onCut);
this.copyPasteInstance.onPaste(onPaste);
var plugin = this;
instance.addHook('beforeKeyDown', onBeforeKeyDown);
function onCut() {
if (!instance.isListening()) {
return;
}
instance.selection.empty();
}
function onPaste(str) {
if (!instance.isListening() || !instance.selection.isSelected()) {
return;
}
var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input
, inputArray = SheetClip.parse(input)
, selected = instance.getSelected()
, coordsFrom = new WalkontableCellCoords(selected[0], selected[1])
, coordsTo = new WalkontableCellCoords(selected[2], selected[3])
, cellRange = new WalkontableCellRange(coordsFrom, coordsFrom, coordsTo)
, topLeftCorner = cellRange.getTopLeftCorner()
, bottomRightCorner = cellRange.getBottomRightCorner()
, areaStart = topLeftCorner
, areaEnd = new WalkontableCellCoords(
Math.max(bottomRightCorner.row, inputArray.length - 1 + topLeftCorner.row),
Math.max(bottomRightCorner.col, inputArray[0].length - 1 + topLeftCorner.col)
);
instance.addHookOnce('afterChange', function (changes, source) {
if (changes && changes.length) {
this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col);
}
});
instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode);
};
function onBeforeKeyDown (event) {
if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) {
//when CTRL is pressed, prepare selectable text in textarea
//http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript
plugin.setCopyableText();
event.stopImmediatePropagation();
return;
}
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL)
if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) {
setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin));
}
}
this.destroy = function () {
this.copyPasteInstance.removeCallback(onCut);
this.copyPasteInstance.removeCallback(onPaste);
this.copyPasteInstance.destroy();
instance.removeHook('beforeKeyDown', onBeforeKeyDown);
};
instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this));
this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance);
this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance);
/**
* Prepares copyable text in the invisible textarea
*/
this.setCopyableText = function () {
var settings = instance.getSettings();
var copyRowsLimit = settings.copyRowsLimit;
var copyColsLimit = settings.copyColsLimit;
var selRange = instance.getSelectedRange();
var topLeft = selRange.getTopLeftCorner();
var bottomRight = selRange.getBottomRightCorner();
var startRow = topLeft.row;
var startCol = topLeft.col;
var endRow = bottomRight.row;
var endCol = bottomRight.col;
var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1);
var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1);
instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol));
if (endRow !== finalEndRow || endCol !== finalEndCol) {
Handsontable.hooks.run(instance, "afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit);
}
};
}
function init() {
var instance = this;
var pluginEnabled = instance.getSettings().copyPaste !== false;
if(pluginEnabled && !instance.copyPaste){
instance.copyPaste = new CopyPastePlugin(instance);
} else if (!pluginEnabled && instance.copyPaste) {
instance.copyPaste.destroy();
delete instance.copyPaste;
}
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
Handsontable.hooks.register('afterCopyLimit');
})(Handsontable, CopyPaste, SheetClip);
(function (Handsontable) {
'use strict';
Handsontable.Search = function Search(instance) {
this.query = function (queryStr, callback, queryMethod) {
var rowCount = instance.countRows();
var colCount = instance.countCols();
var queryResult = [];
if (!callback) {
callback = Handsontable.Search.global.getDefaultCallback();
}
if (!queryMethod) {
queryMethod = Handsontable.Search.global.getDefaultQueryMethod();
}
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
for (var colIndex = 0; colIndex < colCount; colIndex++) {
var cellData = instance.getDataAtCell(rowIndex, colIndex);
var cellProperties = instance.getCellMeta(rowIndex, colIndex);
var cellCallback = cellProperties.search.callback || callback;
var cellQueryMethod = cellProperties.search.queryMethod || queryMethod;
var testResult = cellQueryMethod(queryStr, cellData);
if (testResult) {
var singleResult = {
row: rowIndex,
col: colIndex,
data: cellData
};
queryResult.push(singleResult);
}
if (cellCallback) {
cellCallback(instance, rowIndex, colIndex, cellData, testResult);
}
}
}
return queryResult;
};
};
Handsontable.Search.DEFAULT_CALLBACK = function (instance, row, col, data, testResult) {
instance.getCellMeta(row, col).isSearchResult = testResult;
};
Handsontable.Search.DEFAULT_QUERY_METHOD = function (query, value) {
if (typeof query == 'undefined' || query == null || !query.toLowerCase || query.length == 0){
return false;
}
return value.toString().toLowerCase().indexOf(query.toLowerCase()) != -1;
};
Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS = 'htSearchResult';
Handsontable.Search.global = (function () {
var defaultCallback = Handsontable.Search.DEFAULT_CALLBACK;
var defaultQueryMethod = Handsontable.Search.DEFAULT_QUERY_METHOD;
var defaultSearchResultClass = Handsontable.Search.DEFAULT_SEARCH_RESULT_CLASS;
return {
getDefaultCallback: function () {
return defaultCallback;
},
setDefaultCallback: function (newDefaultCallback) {
defaultCallback = newDefaultCallback;
},
getDefaultQueryMethod: function () {
return defaultQueryMethod;
},
setDefaultQueryMethod: function (newDefaultQueryMethod) {
defaultQueryMethod = newDefaultQueryMethod;
},
getDefaultSearchResultClass: function () {
return defaultSearchResultClass;
},
setDefaultSearchResultClass: function (newSearchResultClass) {
defaultSearchResultClass = newSearchResultClass;
}
}
})();
Handsontable.SearchCellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
var searchResultClass = (typeof cellProperties.search == 'object' && cellProperties.search.searchResultClass) || Handsontable.Search.global.getDefaultSearchResultClass();
if(cellProperties.isSearchResult){
Handsontable.Dom.addClass(TD, searchResultClass);
} else {
Handsontable.Dom.removeClass(TD, searchResultClass);
}
};
var originalDecorator = Handsontable.renderers.cellDecorator;
Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) {
originalDecorator.apply(this, arguments);
Handsontable.SearchCellDecorator.apply(this, arguments);
};
function init() {
var instance = this;
var pluginEnabled = !!instance.getSettings().search;
if (pluginEnabled) {
instance.search = new Handsontable.Search(instance);
} else {
delete instance.search;
}
}
Handsontable.hooks.add('afterInit', init);
Handsontable.hooks.add('afterUpdateSettings', init);
})(Handsontable);
function CellInfoCollection() {
var collection = [];
collection.getInfo = function (row, col) {
for (var i = 0, ilen = this.length; i < ilen; i++) {
if (this[i].row <= row && this[i].row + this[i].rowspan - 1 >= row && this[i].col <= col && this[i].col + this[i].colspan - 1 >= col) {
return this[i];
}
}
};
collection.setInfo = function (info) {
for (var i = 0, ilen = this.length; i < ilen; i++) {
if (this[i].row === info.row && this[i].col === info.col) {
this[i] = info;
return;
}
}
this.push(info);
};
collection.removeInfo = function (row, col) {
for (var i = 0, ilen = this.length; i < ilen; i++) {
if (this[i].row === row && this[i].col === col) {
this.splice(i, 1);
break;
}
}
};
return collection;
}
/**
* Plugin used to merge cells in Handsontable
* @constructor
*/
function MergeCells(mergeCellsSetting) {
this.mergedCellInfoCollection = new CellInfoCollection();
if (Handsontable.helper.isArray(mergeCellsSetting)) {
for (var i = 0, ilen = mergeCellsSetting.length; i < ilen; i++) {
this.mergedCellInfoCollection.setInfo(mergeCellsSetting[i]);
}
}
}
/**
* @param cellRange (WalkontableCellRange)
*/
MergeCells.prototype.canMergeRange = function (cellRange) {
//is more than one cell selected
return !cellRange.isSingle();
};
MergeCells.prototype.mergeRange = function (cellRange) {
if (!this.canMergeRange(cellRange)) {
return;
}
//normalize top left corner
var topLeft = cellRange.getTopLeftCorner();
var bottomRight = cellRange.getBottomRightCorner();
var mergeParent = {};
mergeParent.row = topLeft.row;
mergeParent.col = topLeft.col;
mergeParent.rowspan = bottomRight.row - topLeft.row + 1; //TD has rowspan == 1 by default. rowspan == 2 means spread over 2 cells
mergeParent.colspan = bottomRight.col - topLeft.col + 1;
this.mergedCellInfoCollection.setInfo(mergeParent);
};
MergeCells.prototype.mergeOrUnmergeSelection = function (cellRange) {
var info = this.mergedCellInfoCollection.getInfo(cellRange.from.row, cellRange.from.col);
if (info) {
//unmerge
this.unmergeSelection(cellRange.from);
}
else {
//merge
this.mergeSelection(cellRange);
}
};
MergeCells.prototype.mergeSelection = function (cellRange) {
this.mergeRange(cellRange);
};
MergeCells.prototype.unmergeSelection = function (cellRange) {
var info = this.mergedCellInfoCollection.getInfo(cellRange.row, cellRange.col);
this.mergedCellInfoCollection.removeInfo(info.row, info.col);
};
MergeCells.prototype.applySpanProperties = function (TD, row, col) {
var info = this.mergedCellInfoCollection.getInfo(row, col);
if (info) {
if (info.row === row && info.col === col) {
TD.setAttribute('rowspan', info.rowspan);
TD.setAttribute('colspan', info.colspan);
}
else {
TD.style.display = "none";
}
}
else {
TD.removeAttribute('rowspan');
TD.removeAttribute('colspan');
}
};
MergeCells.prototype.modifyTransform = function (hook, currentSelectedRange, delta) {
var current;
switch (hook) {
case 'modifyTransformStart':
current = currentSelectedRange.highlight;
break;
case 'modifyTransformEnd':
current = currentSelectedRange.to;
break;
}
if (hook == "modifyTransformStart") {
//in future - can this take the logic from modifyTransformEnd?
var mergeParent = this.mergedCellInfoCollection.getInfo(current.row + delta.row, current.col + delta.col);
if (mergeParent) {
if (current.row > mergeParent.row) { //entering merge by going up or left
this.lastDesiredCoords = new WalkontableCellCoords(current.row + delta.row, current.col + delta.col); //copy
delta.row += (mergeParent.row - current.row) - delta.row;
}
else if (current.row == mergeParent.row && delta.row > 0) { //leaving merge by going down
delta.row += mergeParent.row - current.row + mergeParent.rowspan - 1;
}
else { //leaving merge by going right
if (this.lastDesiredCoords && delta.row === 0) {
delta.row += this.lastDesiredCoords.row - current.row;
this.lastDesiredCoords = null;
}
}
if (current.col > mergeParent.col) { //entering merge by going up or left
if (!this.lastDesiredCoords) {
this.lastDesiredCoords = new WalkontableCellCoords(current.row + delta.row, current.col + delta.col); //copy
}
delta.col += (mergeParent.col - current.col) - delta.col;
}
else if (current.col == mergeParent.col && delta.col > 0) { //leaving merge by going right
delta.col += mergeParent.col - current.col + mergeParent.colspan - 1;
}
else { //leaving merge by going down
if (this.lastDesiredCoords && delta.col === 0) {
delta.col += this.lastDesiredCoords.col - current.col;
this.lastDesiredCoords = null;
}
}
}
else {
if (this.lastDesiredCoords) {
if (delta.col == 0) { //leaving merge by going up
delta.col += this.lastDesiredCoords.col - current.col;
}
else if (delta.row == 0) { //leaving merge by going left
delta.row += this.lastDesiredCoords.row - current.row;
}
this.lastDesiredCoords = null;
}
}
}
else {
//modify transform end
var hightlightMergeParent = this.mergedCellInfoCollection.getInfo(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col);
if (hightlightMergeParent) {
if (currentSelectedRange.isSingle()) {
currentSelectedRange.from = new WalkontableCellCoords(hightlightMergeParent.row, hightlightMergeParent.col);
currentSelectedRange.to = new WalkontableCellCoords(hightlightMergeParent.row + hightlightMergeParent.rowspan - 1, hightlightMergeParent.col + hightlightMergeParent.colspan - 1);
}
}
if (currentSelectedRange.isSingle()) {
//make sure objects are clones but not reference to the same instance
//because we will mutate them
currentSelectedRange.from = new WalkontableCellCoords(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col);
currentSelectedRange.to = new WalkontableCellCoords(currentSelectedRange.highlight.row, currentSelectedRange.highlight.col);
}
var solveDimension = function (dim) {
var altDim = dim == "col" ? "row" : "col";
function changeCoords(obj, altDimValue, dimValue) {
obj[altDim] = altDimValue;
obj[dim] = dimValue;
}
if (delta[dim] != 0) {
var topLeft;
var bottomRight;
var updateCornerInfo = function () {
topLeft = currentSelectedRange.getTopLeftCorner();
bottomRight = currentSelectedRange.getBottomRightCorner();
}
updateCornerInfo();
var expanding = false; //expanding false means shrinking
var examinedCol;
//now check if maybe we are expanding?
if (delta[dim] < 0) {
examinedCol = bottomRight[dim] + delta[dim];
if (bottomRight[dim] == currentSelectedRange.highlight[dim]) {
examinedCol = topLeft[dim] + delta[dim];
expanding = true;
}
else {
for (var i = topLeft[altDim]; i <= bottomRight[altDim]; i++) {
var mergeParent = this.mergedCellInfoCollection.getInfo(i, bottomRight[dim]);
if (mergeParent) {
if (mergeParent[dim] <= currentSelectedRange.highlight[dim]) {
examinedCol = topLeft[dim] + delta[dim];
expanding = true;
break;
}
}
}
}
}
else if (delta[dim] > 0) {
examinedCol = topLeft[dim] + delta[dim];
if (topLeft[dim] == currentSelectedRange.highlight[dim]) {
examinedCol = bottomRight[dim] + delta[dim];
expanding = true;
}
else {
for (var i = topLeft[altDim]; i <= bottomRight[altDim]; i++) {
var mergeParent = this.mergedCellInfoCollection.getInfo(i, topLeft[dim]);
if (mergeParent) {
if (mergeParent[dim] + mergeParent[dim + "span"] > currentSelectedRange.highlight[dim]) {
examinedCol = bottomRight[dim] + delta[dim];
expanding = true;
break;
}
}
}
}
}
if (expanding) {
if (delta[dim] > 0) { //moving East wall further East
changeCoords(currentSelectedRange.from, topLeft[altDim], topLeft[dim]);
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.max(bottomRight[dim], examinedCol));
updateCornerInfo();
}
else { //moving West wall further West
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.min(topLeft[dim], examinedCol));
changeCoords(currentSelectedRange.to, bottomRight[altDim], bottomRight[dim]);
updateCornerInfo();
}
}
else {
if (delta[dim] > 0) { //shrinking West wall towards East
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.max(topLeft[dim], examinedCol));
changeCoords(currentSelectedRange.to, bottomRight[altDim], bottomRight[dim]);
updateCornerInfo();
}
else { //shrinking East wall towards West
changeCoords(currentSelectedRange.from, topLeft[altDim], topLeft[dim]);
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.min(bottomRight[dim], examinedCol));
updateCornerInfo();
}
}
for (var i = topLeft[altDim]; i <= bottomRight[altDim]; i++) {
var mergeParent = dim == "col" ? this.mergedCellInfoCollection.getInfo(i, examinedCol) : this.mergedCellInfoCollection.getInfo(examinedCol, i);
if (mergeParent) {
if (expanding) {
if (delta[dim] > 0) { //moving East wall further East
changeCoords(currentSelectedRange.from, Math.min(topLeft[altDim], mergeParent[altDim]), Math.min(topLeft[dim], mergeParent[dim]));
if (examinedCol > mergeParent[dim]) {
changeCoords(currentSelectedRange.to, Math.max(bottomRight[altDim], mergeParent[altDim] + mergeParent[altDim + "span"] - 1), Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"]));
}
else {
changeCoords(currentSelectedRange.to, Math.max(bottomRight[altDim], mergeParent[altDim] + mergeParent[altDim + "span"] - 1), Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"] - 1));
}
updateCornerInfo();
}
else { //moving West wall further West
changeCoords(currentSelectedRange.from, Math.min(topLeft[altDim], mergeParent[altDim]), Math.min(topLeft[dim], mergeParent[dim]));
changeCoords(currentSelectedRange.to, Math.max(bottomRight[altDim], mergeParent[altDim] + mergeParent[altDim + "span"] - 1), Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"] - 1));
updateCornerInfo();
}
}
else {
if (delta[dim] > 0) { //shrinking West wall towards East
if (examinedCol > mergeParent[dim]) {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.max(topLeft[dim], mergeParent[dim] + mergeParent[dim + "span"]));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"]));
}
else {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.max(topLeft[dim], mergeParent[dim]));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.max(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"] - 1));
}
updateCornerInfo();
}
else { //shrinking East wall towards West
if (examinedCol < mergeParent[dim] + mergeParent[dim + "span"] - 1) {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.min(topLeft[dim], mergeParent[dim] - 1));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.min(bottomRight[dim], mergeParent[dim] - 1));
}
else {
changeCoords(currentSelectedRange.from, topLeft[altDim], Math.min(topLeft[dim], mergeParent[dim]));
changeCoords(currentSelectedRange.to, bottomRight[altDim], Math.min(bottomRight[dim], mergeParent[dim] + mergeParent[dim + "span"]));
}
updateCornerInfo();
}
}
}
}
/*if (expanding) {
//check if corners are not part of merged cells as well
var oneLastCheck = function (row, col) {
var mergeParent = this.mergedCellInfoCollection.getInfo(row, col);
if (mergeParent) {
currentSelectedRange.expand(new WalkontableCellCoords(mergeParent.row, mergeParent.col));
currentSelectedRange.expand(new WalkontableCellCoords(mergeParent.row + mergeParent.rowspan - 1, mergeParent.col + mergeParent.colspan - 1));
updateCornerInfo();
}
}
oneLastCheck.call(this, topLeft.row, topLeft.col);
oneLastCheck.call(this, topLeft.row, bottomRight.col);
oneLastCheck.call(this, bottomRight.row, bottomRight.col);
oneLastCheck.call(this, bottomRight.row, topLeft.col);
}
else {
//TODO there is still a glitch if you go to merge_cells.html, go to D5 and press up, right, down
}*/
}
};
solveDimension.call(this, "col");
solveDimension.call(this, "row");
delta.row = 0;
delta.col = 0;
}
};
if (typeof Handsontable == 'undefined') {
throw new Error('Handsontable is not defined');
}
var init = function () {
var instance = this;
var mergeCellsSetting = instance.getSettings().mergeCells;
if (mergeCellsSetting) {
if (!instance.mergeCells) {
instance.mergeCells = new MergeCells(mergeCellsSetting);
}
}
};
var onBeforeKeyDown = function (event) {
if (!this.mergeCells) {
return;
}
var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey;
if (ctrlDown) {
if (event.keyCode === 77) { //CTRL + M
this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange());
this.render();
event.stopImmediatePropagation();
}
}
};
var addMergeActionsToContextMenu = function (defaultOptions) {
if (!this.getSettings().mergeCells) {
return;
}
defaultOptions.items.mergeCellsSeparator = Handsontable.ContextMenu.SEPARATOR;
defaultOptions.items.mergeCells = {
name: function () {
var sel = this.getSelected();
var info = this.mergeCells.mergedCellInfoCollection.getInfo(sel[0], sel[1]);
if (info) {
return 'Unmerge cells';
}
else {
return 'Merge cells';
}
},
callback: function () {
this.mergeCells.mergeOrUnmergeSelection(this.getSelectedRange());
this.render();
},
disabled: function () {
return false;
}
};
};
var afterRenderer = function (TD, row, col, prop, value, cellProperties) {
if (this.mergeCells) {
this.mergeCells.applySpanProperties(TD, row, col);
}
};
var modifyTransformFactory = function (hook) {
return function (delta) {
var mergeCellsSetting = this.getSettings().mergeCells;
if (mergeCellsSetting) {
var currentSelectedRange = this.getSelectedRange();
this.mergeCells.modifyTransform(hook, currentSelectedRange, delta);
if (hook === "modifyTransformEnd") {
//sanitize "from" (core.js will sanitize to)
var totalRows = this.countRows();
var totalCols = this.countCols();
if (currentSelectedRange.from.row < 0) {
currentSelectedRange.from.row = 0;
}
else if (currentSelectedRange.from.row > 0 && currentSelectedRange.from.row >= totalRows) {
currentSelectedRange.from.row = currentSelectedRange.from - 1;
}
if (currentSelectedRange.from.col < 0) {
currentSelectedRange.from.col = 0;
}
else if (currentSelectedRange.from.col > 0 && currentSelectedRange.from.col >= totalCols) {
currentSelectedRange.from.col = totalCols - 1;
}
}
}
}
};
/**
* While selecting cells with keyboard or mouse, make sure that rectangular area is expanded to the extent of the merged cell
* @param coords
*/
var beforeSetRangeEnd = function (coords) {
this.lastDesiredCoords = null; //unset lastDesiredCoords when selection is changed with mouse
var mergeCellsSetting = this.getSettings().mergeCells;
if (mergeCellsSetting) {
var selRange = this.getSelectedRange();
selRange.highlight = new WalkontableCellCoords(selRange.highlight.row, selRange.highlight.col); //clone in case we will modify its reference
selRange.to = coords;
for (var i = 0, ilen = this.mergeCells.mergedCellInfoCollection.length; i < ilen; i++) {
var cellInfo = this.mergeCells.mergedCellInfoCollection[i];
var mergedCellTopLeft = new WalkontableCellCoords(cellInfo.row, cellInfo.col);
var mergedCellBottomRight = new WalkontableCellCoords(cellInfo.row + cellInfo.rowspan - 1, cellInfo.col + cellInfo.colspan - 1);
var mergedCellRange = new WalkontableCellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight);
if (selRange.expandByRange(mergedCellRange)) {
var selRangeBottomRight = selRange.getBottomRightCorner();
coords.row = selRangeBottomRight.row;
coords.col = selRangeBottomRight.col;
}
}
}
};
var afterGetCellMeta = function(row, col, cellProperties) {
var mergeCellsSetting = this.getSettings().mergeCells;
if (mergeCellsSetting) {
var mergeParent = this.mergeCells.mergedCellInfoCollection.getInfo(row, col);
if(mergeParent && (mergeParent.row != row || mergeParent.col != col)) {
cellProperties.copyable = false;
}
}
};
Handsontable.hooks.add('beforeInit', init);
Handsontable.hooks.add('beforeKeyDown', onBeforeKeyDown);
Handsontable.hooks.add('modifyTransformStart', modifyTransformFactory('modifyTransformStart'));
Handsontable.hooks.add('modifyTransformEnd', modifyTransformFactory('modifyTransformEnd'));
Handsontable.hooks.add('beforeSetRangeEnd', beforeSetRangeEnd);
Handsontable.hooks.add('afterRenderer', afterRenderer);
Handsontable.hooks.add('afterContextMenuDefaultOptions', addMergeActionsToContextMenu);
Handsontable.hooks.add('afterGetCellMeta', afterGetCellMeta);
Handsontable.MergeCells = MergeCells;
/**
* Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable
* and (optionally) implements behavior needed for native horizontal and vertical scrolling
*/
function WalkontableOverlay() {}
/*
Possible optimizations:
[x] don't rerender if scroll delta is smaller than the fragment outside of the viewport
[ ] move .style.top change before .draw()
[ ] put .draw() in requestAnimationFrame
[ ] don't rerender rows that remain visible after the scroll
*/
WalkontableOverlay.prototype.init = function () {
this.TABLE = this.instance.wtTable.TABLE;
this.fixed = this.instance.wtTable.hider;
this.fixedContainer = this.instance.wtTable.holder;
// this.fixed.style.position = 'absolute';
// this.fixed.style.left = '0';
this.scrollHandler = this.getScrollableElement(this.TABLE);
this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here
};
WalkontableOverlay.prototype.makeClone = function (direction) {
var clone = document.createElement('DIV');
clone.className = 'ht_clone_' + direction + ' handsontable';
clone.style.position = 'fixed';
clone.style.overflow = 'hidden';
var table2 = document.createElement('TABLE');
table2.className = this.instance.wtTable.TABLE.className;
clone.appendChild(table2);
this.instance.wtTable.holder.parentNode.appendChild(clone);
return new Walkontable({
cloneSource: this.instance,
cloneOverlay: this,
table: table2
});
};
WalkontableOverlay.prototype.getScrollableElement = function (TABLE) {
var el = TABLE.parentNode;
while (el && el.style) {
if (el.style.overflow !== 'visible' && el.style.overflow !== '') {
return el;
}
if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') {
return el;
}
el = el.parentNode;
}
return window;
};
WalkontableOverlay.prototype.prepare = function () {
};
WalkontableOverlay.prototype.onScroll = function () {
this.windowScrollPosition = this.getScrollPosition();
this.readSettings(); //read window scroll position
this.resetFixedPosition(); //may be redundant
};
WalkontableOverlay.prototype.availableSize = function () {
var availableSize;
if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table
if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) {
availableSize = Handsontable.Dom.outerHeight(this.TABLE);
}
else {
availableSize = this.windowSize;
}
}
else {
availableSize = this.windowSize - (this.tableParentOffset);
}
return availableSize;
};
WalkontableOverlay.prototype.refresh = function (selectionsOnly) {
var last = this.getLastCell();
this.measureBefore = this.sumCellSizes(0, this.offset);
if (last === -1) { //last -1 means that viewport is scrolled behind the table
this.measureAfter = 0;
}
else {
this.measureAfter = this.sumCellSizes(last, this.total - last);
}
this.applyToDOM();
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableOverlay.prototype.destroy = function () {
this.$scrollHandler.off('.' + this.clone.guid);
$(window).off('.' + this.clone.guid);
$(document).off('.' + this.clone.guid);
$(document.body).off('.' + this.clone.guid);
};
/**
* WalkontableAbstractFilter (WalkontableColumnFilter and WalkontableRowFilter inherit from this)
* @constructor
*/
function WalkontableAbstractFilter() {
this.offset = 0;
this.total = 0;
this.fixedCount = 0;
}
WalkontableAbstractFilter.prototype.offsetted = function (n) {
return n + this.offset;
};
WalkontableAbstractFilter.prototype.unOffsetted = function (n) {
return n - this.offset;
};
WalkontableAbstractFilter.prototype.fixed = function (n) {
if (n < this.fixedCount) {
return n - this.offset;
}
else {
return n;
}
};
WalkontableAbstractFilter.prototype.unFixed = function (n) {
if (n < this.fixedCount) {
return n + this.offset;
}
else {
return n;
}
};
WalkontableAbstractFilter.prototype.visibleToSource = function (n) {
return this.offsetted(this.fixed(n));
};
WalkontableAbstractFilter.prototype.sourceToVisible = function (n) {
return this.unOffsetted(this.unFixed(n));
};
/**
* WalkontableAbstractStrategy (WalkontableColumnStrategy and WalkontableRowStrategy inherit from this)
* @constructor
*/
function WalkontableAbstractStrategy(instance) {
this.instance = instance;
}
WalkontableAbstractStrategy.prototype.getSize = function (index) {
return this.cellSizes[index];
};
WalkontableAbstractStrategy.prototype.getContainerSize = function (proposedSize) {
return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn;
};
WalkontableAbstractStrategy.prototype.countVisible = function () {
return this.cellCount;
};
WalkontableAbstractStrategy.prototype.isLastIncomplete = function () {
return this.remainingSize > 0;
};
function WalkontableBorder(instance, settings) {
var style;
//reference to instance
this.instance = instance;
this.settings = settings;
this.main = document.createElement("div");
style = this.main.style;
style.position = 'absolute';
style.top = 0;
style.left = 0;
for (var i = 0; i < 5; i++) {
var DIV = document.createElement('DIV');
DIV.className = 'wtBorder ' + (settings.className || '');
style = DIV.style;
style.backgroundColor = settings.border.color;
style.height = settings.border.width + 'px';
style.width = settings.border.width + 'px';
this.main.appendChild(DIV);
}
this.top = this.main.childNodes[0];
this.left = this.main.childNodes[1];
this.bottom = this.main.childNodes[2];
this.right = this.main.childNodes[3];
this.topStyle = this.top.style;
this.leftStyle = this.left.style;
this.bottomStyle = this.bottom.style;
this.rightStyle = this.right.style;
this.corner = this.main.childNodes[4];
this.corner.className += ' corner';
this.cornerStyle = this.corner.style;
this.cornerStyle.width = '5px';
this.cornerStyle.height = '5px';
this.cornerStyle.border = '2px solid #FFF';
this.disappear();
if (!instance.wtTable.bordersHolder) {
instance.wtTable.bordersHolder = document.createElement('div');
instance.wtTable.bordersHolder.className = 'htBorders';
instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder);
}
instance.wtTable.bordersHolder.appendChild(this.main);
var down = false;
var $body = $(document.body);
$body.on('mousedown.walkontable.' + instance.guid, function () {
down = true;
});
$body.on('mouseup.walkontable.' + instance.guid, function () {
down = false
});
$(this.main.childNodes).on('mouseenter', function (event) {
if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
var bounds = this.getBoundingClientRect();
var $this = $(this);
$this.hide();
var isOutside = function (event) {
if (event.clientY < Math.floor(bounds.top)) {
return true;
}
if (event.clientY > Math.ceil(bounds.top + bounds.height)) {
return true;
}
if (event.clientX < Math.floor(bounds.left)) {
return true;
}
if (event.clientX > Math.ceil(bounds.left + bounds.width)) {
return true;
}
};
$body.on('mousemove.border.' + instance.guid, function (event) {
if (isOutside(event)) {
$body.off('mousemove.border.' + instance.guid);
$this.show();
}
});
});
}
/**
* Show border around one or many cells
* @param {Array} corners
*/
WalkontableBorder.prototype.appear = function (corners) {
var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width;
if (this.disabled) {
return;
}
var instance = this.instance;
var fromRow
, fromColumn
, toRow
, toColumn
, hideTop = false
, hideLeft = false
, hideBottom = false
, hideRight = false
, i
, ilen
, s;
if (!instance.wtTable.isRowInViewport(corners[0])) {
hideTop = true;
}
if (!instance.wtTable.isRowInViewport(corners[2])) {
hideBottom = true;
}
if (instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
ilen = instance.getSetting('fixedRowsTop');
}
else {
ilen = instance.wtTable.getRowStrategy().countVisible();
}
for (i = 0; i < ilen; i++) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
fromRow = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.rowFilter.visibleToSource(i);
if (s >= corners[0] && s <= corners[2]) {
toRow = s;
break;
}
}
if (hideTop && hideBottom) {
hideLeft = true;
hideRight = true;
}
else {
if (!instance.wtTable.isColumnInViewport(corners[1])) {
hideLeft = true;
}
if (!instance.wtTable.isColumnInViewport(corners[3])) {
hideRight = true;
}
if (instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
ilen = instance.getSetting('fixedColumnsLeft');
}
else {
ilen = instance.wtTable.getColumnStrategy().cellCount;
}
for (i = 0; i < ilen; i++) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
fromColumn = s;
break;
}
}
for (i = ilen - 1; i >= 0; i--) {
s = instance.wtTable.columnFilter.visibleToSource(i);
if (s >= corners[1] && s <= corners[3]) {
toColumn = s;
break;
}
}
}
if (fromRow !== void 0 && fromColumn !== void 0) {
isMultiple = (fromRow !== toRow || fromColumn !== toColumn);
fromTD = instance.wtTable.getCell(new WalkontableCellCoords(fromRow, fromColumn));
toTD = isMultiple ? instance.wtTable.getCell(new WalkontableCellCoords(toRow, toColumn)) : fromTD;
fromOffset = Handsontable.Dom.offset(fromTD);
toOffset = isMultiple ? Handsontable.Dom.offset(toTD) : fromOffset;
containerOffset = Handsontable.Dom.offset(instance.wtTable.TABLE);
minTop = fromOffset.top;
height = toOffset.top + Handsontable.Dom.outerHeight(toTD) - minTop;
minLeft = fromOffset.left;
width = toOffset.left + Handsontable.Dom.outerWidth(toTD) - minLeft;
top = minTop - containerOffset.top - 1;
left = minLeft - containerOffset.left - 1;
var style = Handsontable.Dom.getComputedStyle(fromTD);
if (parseInt(style['borderTopWidth'], 10) > 0) {
top += 1;
height = height > 0 ? height - 1 : 0;
}
if (parseInt(style['borderLeftWidth'], 10) > 0) {
left += 1;
width = width > 0 ? width - 1 : 0;
}
}
else {
this.disappear();
return;
}
if (hideTop) {
this.topStyle.display = 'none';
}
else {
this.topStyle.top = top + 'px';
this.topStyle.left = left + 'px';
this.topStyle.width = width + 'px';
this.topStyle.display = 'block';
}
if (hideLeft) {
this.leftStyle.display = 'none';
}
else {
this.leftStyle.top = top + 'px';
this.leftStyle.left = left + 'px';
this.leftStyle.height = height + 'px';
this.leftStyle.display = 'block';
}
var delta = Math.floor(this.settings.border.width / 2);
if (hideBottom) {
this.bottomStyle.display = 'none';
}
else {
this.bottomStyle.top = top + height - delta + 'px';
this.bottomStyle.left = left + 'px';
this.bottomStyle.width = width + 'px';
this.bottomStyle.display = 'block';
}
if (hideRight) {
this.rightStyle.display = 'none';
}
else {
this.rightStyle.top = top + 'px';
this.rightStyle.left = left + width - delta + 'px';
this.rightStyle.height = height + 1 + 'px';
this.rightStyle.display = 'block';
}
if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) {
this.cornerStyle.display = 'none';
}
else {
this.cornerStyle.top = top + height - 4 + 'px';
this.cornerStyle.left = left + width - 4 + 'px';
this.cornerStyle.display = 'block';
}
};
/**
* Hide border
*/
WalkontableBorder.prototype.disappear = function () {
this.topStyle.display = 'none';
this.leftStyle.display = 'none';
this.bottomStyle.display = 'none';
this.rightStyle.display = 'none';
this.cornerStyle.display = 'none';
};
WalkontableBorder.prototype.hasSetting = function (setting) {
if (typeof setting === 'function') {
return setting();
}
return !!setting;
};
/**
* WalkontableCellCoords holds cell coordinates (row, column) and few metiod to validate them and retrieve as an array or an object
* TODO: change interface to WalkontableCellCoords(row, col) everywhere, remove those unnecessary setter and getter functions
*/
function WalkontableCellCoords(row, col) {
if (typeof row !== 'undefined' && typeof col !== 'undefined') {
this.row = row;
this.col = col;
}
else {
this.row = null;
this.col = null;
}
}
/**
* Returns boolean information if given set of coordinates is valid in context of a given Walkontable instance
* @param instance
* @returns {boolean}
*/
WalkontableCellCoords.prototype.isValid = function (instance) {
//is it a valid cell index (0 or higher)
if (this.row < 0 || this.col < 0) {
return false;
}
//is selection within total rows and columns
if (this.row >= instance.getSetting('totalRows') || this.col >= instance.getSetting('totalColumns')) {
return false;
}
return true;
};
/**
* Returns boolean information if this cell coords are the same as cell coords given as a parameter
* @param {WalkontableCellCoords} cellCoords
* @returns {boolean}
*/
WalkontableCellCoords.prototype.isEqual = function (cellCoords) {
if (cellCoords === this) {
return true;
}
return (this.row === cellCoords.row && this.col === cellCoords.col);
};
WalkontableCellCoords.prototype.isSouthEastOf = function (testedCoords) {
return this.row >= testedCoords.row && this.col >= testedCoords.col;
};
WalkontableCellCoords.prototype.isNorthWestOf = function (testedCoords) {
return this.row <= testedCoords.row && this.col <= testedCoords.col;
};
window.WalkontableCellCoords = WalkontableCellCoords; //export
/**
* A cell range is a set of exactly two WalkontableCellCoords (that can be the same or different)
*/
function WalkontableCellRange(highlight, from, to) {
this.highlight = highlight; //this property is used to draw bold border around a cell where selection was started and to edit the cell when you press Enter
this.from = from; //this property is usually the same as highlight, but in Excel there is distinction - one can change highlight within a selection
this.to = to;
}
WalkontableCellRange.prototype.isValid = function (instance) {
return (this.from.isValid(instance) && this.to.isValid(instance));
};
WalkontableCellRange.prototype.isSingle = function () {
return (this.from.row === this.to.row && this.from.col === this.to.col);
};
/**
* Returns boolean information if given cell coords is within `from` and `to` cell coords of this range
* @param {WalkontableCellCoords} cellCoords
* @returns {boolean}
*/
WalkontableCellRange.prototype.includes = function (cellCoords) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
return (topLeft.row <= cellCoords.row && bottomRight.row >= cellCoords.row && topLeft.col <= cellCoords.col && bottomRight.col >= cellCoords.col);
};
WalkontableCellRange.prototype.includesRange = function (testedRange) {
return this.includes(testedRange.getTopLeftCorner()) && this.includes(testedRange.getBottomRightCorner());
};
/**
* Returns true if tested range overlaps with the range.
* Range A is considered to to be overlapping with range B if intersection of A and B or B and A is not empty.
* @param testedRange
* @returns {boolean}
*/
WalkontableCellRange.prototype.overlaps = function (testedRange) {
return testedRange.isSouthEastOf(this.getTopLeftCorner()) && testedRange.isNorthWestOf(this.getBottomRightCorner());
};
WalkontableCellRange.prototype.isSouthEastOf = function (testedCoords) {
return this.getTopLeftCorner().isSouthEastOf(testedCoords) || this.getBottomRightCorner().isSouthEastOf(testedCoords);
};
WalkontableCellRange.prototype.isNorthWestOf = function (testedCoords) {
return this.getTopLeftCorner().isNorthWestOf(testedCoords) || this.getBottomRightCorner().isNorthWestOf(testedCoords);
};
/**
* Adds a cell to a range (only if exceeds corners of the range). Returns information if range was expanded
* @param {WalkontableCellCoords} cellCoords
* @returns {boolean}
*/
WalkontableCellRange.prototype.expand = function (cellCoords) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
if (cellCoords.row < topLeft.row || cellCoords.col < topLeft.col || cellCoords.row > bottomRight.row || cellCoords.col > bottomRight.col) {
this.from = new WalkontableCellCoords(Math.min(topLeft.row, cellCoords.row), Math.min(topLeft.col, cellCoords.col));
this.to = new WalkontableCellCoords(Math.max(bottomRight.row, cellCoords.row), Math.max(bottomRight.col, cellCoords.col));
return true;
}
return false;
};
WalkontableCellRange.prototype.expandByRange = function (expandingRange) {
if (this.includesRange(expandingRange) || !this.overlaps(expandingRange)){
return false;
}
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var expandingTopLeft = expandingRange.getTopLeftCorner();
var expandingBottomRight = expandingRange.getBottomRightCorner();
var resultTopRow = Math.min(topLeft.row, expandingTopLeft.row);
var resultTopCol = Math.min(topLeft.col, expandingTopLeft.col);
var resultBottomRow = Math.max(bottomRight.row, expandingBottomRight.row);
var resultBottomCol = Math.max(bottomRight.col, expandingBottomRight.col);
this.from = new WalkontableCellCoords(resultTopRow, resultTopCol);
this.to = new WalkontableCellCoords(resultBottomRow, resultBottomCol);
return true;
};
WalkontableCellRange.prototype.getTopLeftCorner = function () {
return new WalkontableCellCoords(Math.min(this.from.row, this.to.row), Math.min(this.from.col, this.to.col));
};
WalkontableCellRange.prototype.getBottomRightCorner = function () {
return new WalkontableCellCoords(Math.max(this.from.row, this.to.row), Math.max(this.from.col, this.to.col));
};
WalkontableCellRange.prototype.getInner = function () {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var out = [];
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
if (!(this.from.row === r && this.from.col === c) && !(this.to.row === r && this.to.col === c)) {
out.push(new WalkontableCellCoords(r, c));
}
}
}
return out;
};
WalkontableCellRange.prototype.getAll = function () {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
var out = [];
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
if (topLeft.row === r && topLeft.col === c) {
out.push(topLeft);
}
else if (bottomRight.row === r && bottomRight.col === c) {
out.push(bottomRight);
}
else {
out.push(new WalkontableCellCoords(r, c));
}
}
}
return out;
};
/**
* Runs a callback function against all cells in the range. You can break the iteration by returning false in the callback function
* @param callback {Function}
*/
WalkontableCellRange.prototype.forAll = function (callback) {
var topLeft = this.getTopLeftCorner();
var bottomRight = this.getBottomRightCorner();
for (var r = topLeft.row; r <= bottomRight.row; r++) {
for (var c = topLeft.col; c <= bottomRight.col; c++) {
var breakIteration = callback(r, c);
if (breakIteration === false) {
return;
}
}
}
};
window.WalkontableCellRange = WalkontableCellRange; //export
/**
* WalkontableClassNameList
* @constructor
*/
function WalkontableClassNameCache() {
this.cache = [];
}
WalkontableClassNameCache.prototype.add = function (r, c, cls) {
if (!this.cache[r]) {
this.cache[r] = [];
}
if (!this.cache[r][c]) {
this.cache[r][c] = [];
}
this.cache[r][c][cls] = true;
};
WalkontableClassNameCache.prototype.test = function (r, c, cls) {
return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]);
};
/**
* WalkontableColumnFilter
* @constructor
*/
function WalkontableColumnFilter(offset, total, fixedCount, countTH) {
this.offset = offset;
this.total = total;
this.fixedCount = fixedCount;
this.countTH = countTH;
}
WalkontableColumnFilter.prototype = new WalkontableAbstractFilter();
WalkontableColumnFilter.prototype.offsettedTH = function (n) {
return n - this.countTH;
};
WalkontableColumnFilter.prototype.unOffsettedTH = function (n) {
return n + this.countTH;
};
WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) {
return this.visibleToSource(this.offsettedTH(n));
};
WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) {
return this.unOffsettedTH(this.sourceToVisible(n));
};
/**
* WalkontableColumnStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @param strategy - all, last, none
* @constructor
*/
function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) {
var size
, i = 0;
WalkontableAbstractStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellStretch = [];
this.cellCount = 0;
this.visibleCellCount = 0;
this.remainingSize = 0;
this.strategy = strategy;
//step 1 - determine cells that fit containerSize and cache their widths
while (true) {
size = sizeAtIndex(i);
if (size === void 0) {
break; //total columns exceeded
}
if (this.cellSizesSum < this.getContainerSize(this.cellSizesSum + size)) {
this.visibleCellCount++;
}
this.cellSizes.push(size);
this.cellSizesSum += size;
this.cellCount++;
i++;
}
var containerSize = this.getContainerSize(this.cellSizesSum);
this.remainingSize = this.cellSizesSum - containerSize;
//negative value means the last cell is fully visible and there is some space left for stretching
//positive value means the last cell is not fully visible
}
WalkontableColumnStrategy.prototype = new WalkontableAbstractStrategy();
WalkontableColumnStrategy.prototype.getSize = function (index) {
return this.cellSizes[index] + (this.cellStretch[index] || 0);
};
WalkontableColumnStrategy.prototype.stretch = function () {
//step 2 - apply stretching strategy
var containerSize
, i = 0;
containerSize = this.instance.wtTable.allRowsInViewport() ? this.getContainerSize() : this.getContainerSize(Infinity);
this.remainingSize = this.cellSizesSum - containerSize;
this.cellStretch.length = 0; //clear previous stretch
if (this.strategy === 'all') {
if (this.remainingSize < 0) {
var ratio = containerSize / this.cellSizesSum;
var newSize;
while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop
newSize = Math.floor(ratio * this.cellSizes[i]);
this.remainingSize += newSize - this.cellSizes[i];
this.cellStretch[i] = newSize - this.cellSizes[i];
i++;
}
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
else if (this.strategy === 'last') {
if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test)
this.cellStretch[this.cellCount - 1] = -this.remainingSize;
this.remainingSize = 0;
}
}
};
WalkontableColumnStrategy.prototype.countVisible = function () {
return this.visibleCellCount;
};
WalkontableColumnStrategy.prototype.isLastIncomplete = function () {
var firstRow = this.instance.wtTable.getFirstVisibleRow();
var lastCol = this.instance.wtTable.getLastVisibleColumn();
var cell = this.instance.wtTable.getCell(new WalkontableCellCoords(firstRow, lastCol));
var cellOffset = Handsontable.Dom.offset(cell);
var cellWidth = Handsontable.Dom.outerWidth(cell);
var cellEnd = cellOffset.left + cellWidth;
var viewportOffsetLeft = this.instance.wtScrollbars.vertical.getScrollPosition();
var viewportWitdh = this.instance.wtViewport.getViewportWidth();
var viewportEnd = viewportOffsetLeft + viewportWitdh;
return viewportEnd >= cellEnd;
};
function Walkontable(settings) {
var originalHeaders = [];
this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events
//bootstrap from settings
if (settings.cloneSource) {
this.cloneSource = settings.cloneSource;
this.cloneOverlay = settings.cloneOverlay;
this.wtSettings = settings.cloneSource.wtSettings;
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = settings.cloneSource.wtViewport;
this.wtEvent = new WalkontableEvent(this);
this.selections = this.cloneSource.selections.makeClone(this);
}
else {
this.wtSettings = new WalkontableSettings(this, settings);
this.wtTable = new WalkontableTable(this, settings.table);
this.wtScroll = new WalkontableScroll(this);
this.wtViewport = new WalkontableViewport(this);
this.wtEvent = new WalkontableEvent(this);
this.selections = new WalkontableSelections(this, this.getSetting('selections'));
this.wtScrollbars = new WalkontableScrollbars(this);
}
//find original headers
if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) {
for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) {
originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML);
}
if (!this.getSetting('columnHeaders').length) {
this.update('columnHeaders', [function (column, TH) {
Handsontable.Dom.fastInnerText(TH, originalHeaders[column]);
}]);
}
}
this.drawn = false;
this.drawInterrupted = false;
}
Walkontable.prototype.draw = function (selectionsOnly) {
this.drawInterrupted = false;
if (!selectionsOnly && !Handsontable.Dom.isVisible(this.wtTable.TABLE)) {
this.drawInterrupted = true; //draw interrupted because TABLE is not visible
return;
}
selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn;
this.lastOffsetRow = this.getSetting('offsetRow');
this.lastOffsetColumn = this.getSetting('offsetColumn');
var totalRows = this.getSetting('totalRows');
if (this.lastOffsetRow > totalRows && totalRows > 0) {
this.scrollVertical(-Infinity); //TODO: probably very inefficient!
this.scrollViewport(new WalkontableCellCoords(totalRows - 1, 0));
}
this.wtTable.draw(selectionsOnly);
return this;
};
Walkontable.prototype.update = function (settings, value) {
return this.wtSettings.update(settings, value);
};
Walkontable.prototype.scrollVertical = function (delta) {
var result = this.wtScroll.scrollVertical(delta);
this.getSetting('onScrollVertically');
return result;
};
Walkontable.prototype.scrollHorizontal = function (delta) {
var result = this.wtScroll.scrollHorizontal(delta);
this.getSetting('onScrollHorizontally');
return result;
};
/**
* Scrolls the viewport to a cell (rerenders if needed)
* @param {WalkontableCellCoords} coords
* @returns {Walkontable}
*/
Walkontable.prototype.scrollViewport = function (coords) {
this.wtScroll.scrollViewport(coords);
return this;
};
Walkontable.prototype.getViewport = function () {
return [
this.wtTable.getFirstVisibleRow(),
this.wtTable.getFirstVisibleColumn(),
this.wtTable.getLastVisibleRow(),
this.wtTable.getLastVisibleColumn()
];
};
Walkontable.prototype.getSetting = function (key, param1, param2, param3, param4) {
return this.wtSettings.getSetting(key, param1, param2, param3, param4); //this is faster than .apply - https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
};
Walkontable.prototype.hasSetting = function (key) {
return this.wtSettings.has(key);
};
Walkontable.prototype.destroy = function () {
$(window).off('.' + this.guid);
$(document.body).off('.' + this.guid);
this.wtScrollbars.destroy();
this.wtEvent && this.wtEvent.destroy();
};
/**
* A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays.
* Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly
* @param instance
* @constructor
*/
function WalkontableDebugOverlay(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('debug');
this.clone.wtTable.holder.style.opacity = 0.4;
this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000';
var that = this;
var lastTimeout;
var lastX = 0;
var lastY = 0;
var overlayContainer = that.clone.wtTable.holder.parentNode;
$(document.body).on('mousemove.' + this.instance.guid, function (event) {
if (!that.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) {
return; //ignore minor mouse movement
}
lastX = event.clientX;
lastY = event.clientY;
Handsontable.Dom.addClass(overlayContainer, 'wtDebugHidden');
Handsontable.Dom.removeClass(overlayContainer, 'wtDebugVisible');
clearTimeout(lastTimeout);
lastTimeout = setTimeout(function () {
Handsontable.Dom.removeClass(overlayContainer, 'wtDebugHidden');
Handsontable.Dom.addClass(overlayContainer, 'wtDebugVisible');
}, 1000);
});
}
WalkontableDebugOverlay.prototype = new WalkontableOverlay();
WalkontableDebugOverlay.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box = this.instance.wtTable.holder.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
};
WalkontableDebugOverlay.prototype.prepare = function () {
};
WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) {
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableDebugOverlay.prototype.getScrollPosition = function () {
};
WalkontableDebugOverlay.prototype.getLastCell = function () {
};
WalkontableDebugOverlay.prototype.applyToDOM = function () {
};
WalkontableDebugOverlay.prototype.scrollTo = function () {
};
WalkontableDebugOverlay.prototype.readWindowSize = function () {
};
WalkontableDebugOverlay.prototype.readSettings = function () {
};
function WalkontableEvent(instance) {
var that = this;
//reference to instance
this.instance = instance;
var dblClickOrigin = [null, null];
var dblClickTimeout = [null, null];
var onMouseDown = function (event) {
var cell = that.parentCell(event.target);
if (Handsontable.Dom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerMouseDown', event, event.target);
}
else if (cell.TD){
// if(cell.TD.nodeName == 'TD' || cell.TD.nodeName == 'TH'){
if (that.instance.hasSetting('onCellMouseDown')) {
that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD, that.instance);
}
// }
}
if (event.button !== 2) { //if not right mouse button
// if (cell.TD && cell.TD.nodeName === 'TD') {
if (cell.TD) {
dblClickOrigin[0] = cell.TD;
clearTimeout(dblClickTimeout[0]);
dblClickTimeout[0] = setTimeout(function () {
dblClickOrigin[0] = null;
}, 1000);
}
}
};
var lastMouseOver;
var onMouseOver = function (event) {
if (that.instance.hasSetting('onCellMouseOver')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = Handsontable.Dom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOver && Handsontable.Dom.isChildOf(TD, TABLE)) {
lastMouseOver = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD, that.instance);
}
}
}
};
/* var lastMouseOut;
var onMouseOut = function (event) {
if (that.instance.hasSetting('onCellMouseOut')) {
var TABLE = that.instance.wtTable.TABLE;
var TD = Handsontable.Dom.closest(event.target, ['TD', 'TH'], TABLE);
if (TD && TD !== lastMouseOut && Handsontable.Dom.isChildOf(TD, TABLE)) {
lastMouseOut = TD;
if (TD.nodeName === 'TD') {
that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD);
}
}
}
};*/
var onMouseUp = function (event) {
if (event.button !== 2) { //if not right mouse button
var cell = that.parentCell(event.target);
if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) {
if (Handsontable.Dom.hasClass(event.target, 'corner')) {
that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD, that.instance);
}
// else if (cell.TD) {
else {
that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD, that.instance);
}
dblClickOrigin[0] = null;
dblClickOrigin[1] = null;
}
else if (cell.TD === dblClickOrigin[0]) {
dblClickOrigin[1] = cell.TD;
clearTimeout(dblClickTimeout[1]);
dblClickTimeout[1] = setTimeout(function () {
dblClickOrigin[1] = null;
}, 500);
}
}
};
$(this.instance.wtTable.holder).on('mousedown', onMouseDown);
$(this.instance.wtTable.TABLE).on('mouseover', onMouseOver);
$(this.instance.wtTable.holder).on('mouseup', onMouseUp);
}
WalkontableEvent.prototype.parentCell = function (elem) {
var cell = {};
var TABLE = this.instance.wtTable.TABLE;
var TD = Handsontable.Dom.closest(elem, ['TD', 'TH'], TABLE);
if (TD && Handsontable.Dom.isChildOf(TD, TABLE)) {
cell.coords = this.instance.wtTable.getCoords(TD);
cell.TD = TD;
}
else if (Handsontable.Dom.hasClass(elem, 'wtBorder') && Handsontable.Dom.hasClass(elem, 'current')) {
cell.coords = this.instance.selections.current.cellRange.highlight;
cell.TD = this.instance.wtTable.getCell(cell.coords);
}
return cell;
};
WalkontableEvent.prototype.destroy = function () {
clearTimeout(this.dblClickTimeout0);
clearTimeout(this.dblClickTimeout1);
};
function walkontableRangesIntersect() {
var from = arguments[0];
var to = arguments[1];
for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) {
if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) {
return true;
}
}
return false;
}
/**
* Generates a random hex string. Used as namespace for Walkontable instance events.
* @return {String} - 16 character random string: "92b1bfc74ec4"
*/
function walkontableRandomString() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4();
}
/**
* http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html
*/
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = (function () {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
})();
//http://snipplr.com/view/13523/
//modified for speed
//http://jsperf.com/getcomputedstyle-vs-style-vs-css/8
if (!window.getComputedStyle) {
(function () {
var elem;
var styleObj = {
getPropertyValue: function getPropertyValue(prop) {
if (prop == 'float') prop = 'styleFloat';
return elem.currentStyle[prop.toUpperCase()] || null;
}
};
window.getComputedStyle = function (el) {
elem = el;
return styleObj;
}
})();
}
/**
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
*/
if (!String.prototype.trim) {
var trimRegex = /^\s+|\s+$/g;
String.prototype.trim = function () {
return this.replace(trimRegex, '');
};
}
/**
* WalkontableRowFilter
* @constructor
*/
function WalkontableRowFilter(offset, total, fixedCount, countTH) {
this.offset = offset;
this.total = total;
this.fixedCount = fixedCount;
this.countTH = countTH;
}
WalkontableRowFilter.prototype = new WalkontableAbstractFilter();
WalkontableRowFilter.prototype.offsettedTH = function (n) {
return n - this.countTH;
};
WalkontableRowFilter.prototype.visibleColHeadedColumnToSourceColumn = function (n) {
return this.visibleToSource(this.offsettedTH(n));
};
WalkontableRowFilter.prototype.sourceColumnToVisibleColHeadedColumn = function (n) {
return this.unOffsettedTH(this.sourceToVisible(n));
};
/**
* WalkontableRowStrategy
* @param containerSizeFn
* @param sizeAtIndex
* @constructor
*/
function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) {
WalkontableAbstractStrategy.apply(this, arguments);
this.containerSizeFn = containerSizeFn;
this.sizeAtIndex = sizeAtIndex;
this.cellSizesSum = 0;
this.cellSizes = [];
this.cellCount = 0;
this.visiblCellCount = 0;
this.remainingSize = -Infinity;
this.maxOuts = 10; //max outs in one direction (before and after table)
this.curOuts = this.maxOuts;
}
WalkontableRowStrategy.prototype = new WalkontableAbstractStrategy();
WalkontableRowStrategy.prototype.add = function (i, TD) {
if(!this.canRenderMoreRows()){
return false;
}
var size = this.sizeAtIndex(i, TD);
if (size === void 0) {
return false; //total rows exceeded
}
var containerSize = this.getContainerSize(this.cellSizesSum + size);
this.cellSizes.push(size);
this.cellSizesSum += size;
this.cellCount++;
this.remainingSize = this.cellSizesSum - containerSize;
if (this.remainingSize <= size ){
this.visiblCellCount++;
}
return true;
};
/**
* Checks whether the number of already rendered rows does not exceeds the number of rows visible in viewport + maximal
* number of rows rendered above and below viewport
* @returns {boolean}
*/
WalkontableRowStrategy.prototype.canRenderMoreRows = function () {
return this.remainingSize <= 0 || this.cellCount - this.visiblCellCount < this.curOuts;
};
WalkontableRowStrategy.prototype.remove = function () {
var size = this.cellSizes.pop();
this.cellSizesSum -= size;
this.cellCount--;
this.remainingSize -= size;
};
WalkontableRowStrategy.prototype.removeOutstanding = function () {
while (this.cellCount - this.visiblCellCount > this.curOuts) { //this row is completely off screen!
this.remove();
}
};
WalkontableRowStrategy.prototype.countRendered = function () {
return this.cellCount;
}
WalkontableRowStrategy.prototype.countVisible = function () {
return this.visiblCellCount;
};
WalkontableRowStrategy.prototype.isLastIncomplete = function () {
var lastRow = this.instance.wtTable.getLastVisibleRow();
var firstCol = this.instance.wtTable.getFirstVisibleColumn();
var cell = this.instance.wtTable.getCell(new WalkontableCellCoords(lastRow, firstCol));
var cellOffsetTop = Handsontable.Dom.offset(cell).top;
var cellHeight = Handsontable.Dom.outerHeight(cell);
var cellEnd = cellOffsetTop + cellHeight;
var viewportOffsetTop = this.instance.wtScrollbars.horizontal.scrollHandler.offsetTop + this.instance.wtScrollbars.vertical.getScrollPosition();
var viewportHeight = this.instance.wtViewport.getViewportHeight();
var viewportEnd = viewportOffsetTop + viewportHeight;
return viewportEnd < cellEnd;
};
function WalkontableScroll(instance) {
this.instance = instance;
}
WalkontableScroll.prototype.scrollVertical = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollVertical can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetRow')
, fixedCount = instance.getSetting('fixedRowsTop')
, total = instance.getSetting('totalRows')
, maxSize = instance.wtViewport.getViewportHeight();
if (total > 0 && !this.instance.wtTable.isLastRowFullyVisible()) {
newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) {
if (row - offset < fixedCount && row - offset >= 0) {
return instance.getSetting('rowHeight', row - offset);
}
else {
return instance.getSetting('rowHeight', row);
}
});
} else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.vertical.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollHorizontal = function (delta) {
if (!this.instance.drawn) {
throw new Error('scrollHorizontal can only be called after table was drawn to DOM');
}
var instance = this.instance
, newOffset
, offset = instance.getSetting('offsetColumn')
, fixedCount = instance.getSetting('fixedColumnsLeft')
, total = instance.getSetting('totalColumns')
, maxSize = instance.wtViewport.getViewportWidth();
if (total > 0) {
newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) {
if (col - offset < fixedCount && col - offset >= 0) {
return instance.getSetting('columnWidth', col - offset);
}
else {
return instance.getSetting('columnWidth', col);
}
});
}
else {
newOffset = 0;
}
if (newOffset !== offset) {
this.instance.wtScrollbars.horizontal.scrollTo(newOffset);
}
return instance;
};
WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
var newOffset = offset + delta;
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
}
if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) {
var newOffset = offset + delta
, sum = 0
, col;
if (newOffset > fixedCount) {
if (newOffset >= total - fixedCount) {
newOffset = total - fixedCount - 1;
}
col = newOffset;
while (sum < maxSize && col < total) {
sum += cellSizeFn(col);
col++;
}
if (sum < maxSize) {
while (newOffset > 0) {
//if sum still less than available width, we cannot scroll that far (must move offset to the left)
sum += cellSizeFn(newOffset - 1);
if (sum < maxSize) {
newOffset--;
}
else {
break;
}
}
}
}
else if (newOffset < 0) {
newOffset = 0;
}
return newOffset;
};
/**
* Scrolls viewport to a cell by minimum number of cells
* @param {WalkontableCellCoords} coords
*/
WalkontableScroll.prototype.scrollViewport = function (coords) {
if (!this.instance.drawn) {
return;
}
var offsetRow = this.instance.getSetting('offsetRow')
, offsetColumn = this.instance.getSetting('offsetColumn')
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, fixedRowsTop = this.instance.getSetting('fixedRowsTop')
, fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft');
if (coords.row < 0 || coords.row > totalRows - 1) {
throw new Error('row ' + coords.row + ' does not exist');
}
if (coords.col < 0 || coords.col > totalColumns - 1) {
throw new Error('column ' + coords.col + ' does not exist');
}
var TD = this.instance.wtTable.getCell(coords);
if (typeof TD === 'object') {
this.scrollToRenderedCell(TD);
} else if (coords.row >= this.instance.wtTable.getLastVisibleRow()) {
this.scrollVertical(coords.row - this.instance.wtTable.getLastVisibleRow());
if (coords.row == this.instance.wtTable.getLastVisibleRow() && this.instance.wtTable.getRowStrategy().isLastIncomplete()){
this.scrollViewport(coords)
}
} else if (coords.row >= this.instance.getSetting('fixedColumnsLeft')){
this.scrollVertical(coords.row - this.instance.wtTable.getFirstVisibleRow());
}
};
WalkontableScroll.prototype.scrollToRenderedCell = function (TD) {
var cellOffset = Handsontable.Dom.offset(TD);
var cellWidth = Handsontable.Dom.outerWidth(TD);
var cellHeight = Handsontable.Dom.outerHeight(TD);
var workspaceOffset = Handsontable.Dom.offset(this.instance.wtTable.TABLE);
var viewportScrollPosition = {
left: this.instance.wtScrollbars.horizontal.getScrollPosition(),
top: this.instance.wtScrollbars.vertical.getScrollPosition()
};
var workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
var workspaceHeight = this.instance.wtViewport.getWorkspaceHeight();
var leftCloneWidth = Handsontable.Dom.outerWidth(this.instance.wtScrollbars.horizontal.clone.wtTable.TABLE);
var topCloneHeight = Handsontable.Dom.outerHeight(this.instance.wtScrollbars.vertical.clone.wtTable.TABLE);
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
workspaceOffset.left = 0;
cellOffset.left -= Handsontable.Dom.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left;
}
if (this.instance.wtScrollbars.vertical.scrollHandler !== window) {
workspaceOffset.top = 0;
cellOffset.top = cellOffset.top - Handsontable.Dom.offset(this.instance.wtScrollbars.vertical.scrollHandler).top;
}
if (cellWidth < workspaceWidth) {
if (cellOffset.left < viewportScrollPosition.left + leftCloneWidth) {
this.instance.wtScrollbars.horizontal.setScrollPosition(cellOffset.left - leftCloneWidth);
}
else if (cellOffset.left + cellWidth > workspaceOffset.left + viewportScrollPosition.left + workspaceWidth) {
var delta = (cellOffset.left + cellWidth) - (workspaceOffset.left + viewportScrollPosition.left + workspaceWidth);
this.instance.wtScrollbars.horizontal.setScrollPosition(viewportScrollPosition.left + delta);
}
}
if (cellHeight < workspaceHeight) {
if (cellOffset.top < viewportScrollPosition.top + topCloneHeight) {
this.instance.wtScrollbars.vertical.setScrollPosition(cellOffset.top - topCloneHeight);
this.instance.wtScrollbars.vertical.onScroll();
}
else if (cellOffset.top + cellHeight > viewportScrollPosition.top + workspaceHeight) {
this.instance.wtScrollbars.vertical.setScrollPosition(cellOffset.top - workspaceHeight + cellHeight);
this.instance.wtScrollbars.vertical.onScroll();
}
}
};
function WalkontableCornerScrollbarNative(instance) {
this.instance = instance;
this.init();
this.clone = this.makeClone('corner');
}
WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay();
WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
elem.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px';
elem.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
WalkontableCornerScrollbarNative.prototype.prepare = function () {
};
WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () {
};
WalkontableCornerScrollbarNative.prototype.getLastCell = function () {
};
WalkontableCornerScrollbarNative.prototype.applyToDOM = function () {
};
WalkontableCornerScrollbarNative.prototype.scrollTo = function () {
};
WalkontableCornerScrollbarNative.prototype.readWindowSize = function () {
};
WalkontableCornerScrollbarNative.prototype.readSettings = function () {
};
function WalkontableHorizontalScrollbarNative(instance) {
this.instance = instance;
this.type = 'horizontal';
this.cellSize = 50;
this.init();
this.clone = this.makeClone('left');
}
WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var left = Math.ceil(box.left, 10);
var right = Math.ceil(box.right, 10);
if (left < 0 && right > 0) {
elem.style.left = '0';
}
else {
elem.style.left = left + 'px';
}
}
else {
box = this.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
this.react();
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var overlayContainer = this.clone.wtTable.holder.parentNode;
if (this.instance.wtScrollbars.vertical.scrollHandler === window) {
var box = this.instance.wtTable.hider.getBoundingClientRect();
overlayContainer.style.top = Math.ceil(box.top, 10) + 'px';
overlayContainer.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 'px';
}
else {
this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px';
overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px'
}
overlayContainer.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow
};
WalkontableHorizontalScrollbarNative.prototype.prepare = function () {
};
WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) {
this.measureBefore = 0;
this.measureAfter = 0;
this.clone && this.clone.draw(selectionsOnly);
};
WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () {
return Handsontable.Dom.getScrollLeft(this.scrollHandler);
};
WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) {
if (this.scrollHandler === window){
window.scrollTo(pos, Handsontable.Dom.getWindowScrollTop());
} else {
this.scrollHandler.scrollLeft = pos;
}
};
WalkontableHorizontalScrollbarNative.prototype.onScroll = function () {
WalkontableOverlay.prototype.onScroll.call(this);
this.instance.getSetting('onScrollHorizontally');
};
WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () {
return this.instance.wtTable.getLastVisibleColumn();
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () {
this.fixedContainer.style.paddingLeft = this.measureBefore + 'px';
this.fixedContainer.style.paddingRight = this.measureAfter + 'px';
};
WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) {
this.setScrollPosition(this.tableParentOffset + cell * this.cellSize);
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientWidth;
this.tableParentOffset = this.instance.wtTable.holderOffset.left;
}
else {
this.windowSize = this.scrollHandler.clientWidth;
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableHorizontalScrollbarNative.prototype.readSettings = function () {
this.readWindowSize();
this.offset = this.instance.getSetting('offsetColumn');
this.total = this.instance.getSetting('totalColumns');
};
function WalkontableVerticalScrollbarNative(instance) {
this.instance = instance;
this.type = 'vertical';
this.cellSize = this.instance.wtSettings.settings.defaultRowHeight;
this.offset;
this.total;
this.init();
this.clone = this.makeClone('top');
}
WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay();
//resetFixedPosition (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var elem = this.clone.wtTable.holder.parentNode;
var box;
if (this.scrollHandler === window) {
box = this.instance.wtTable.hider.getBoundingClientRect();
var top = Math.ceil(box.top, 10);
var bottom = Math.ceil(box.bottom, 10);
if (top < 0 && bottom > 0) {
elem.style.top = '0';
}
else {
elem.style.top = top + 'px';
}
}
else {
box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect();
elem.style.top = Math.ceil(box.top, 10) + 'px';
elem.style.left = Math.ceil(box.left, 10) + 'px';
}
if (this.instance.wtScrollbars.horizontal.scrollHandler === window) {
elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px';
}
else {
elem.style.width = Handsontable.Dom.outerWidth(this.instance.wtTable.holder.parentNode) + 'px';
}
elem.style.height = Handsontable.Dom.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px';
};
//react on movement of the other dimension scrollbar (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.react = function () {
if (!this.instance.wtTable.holder.parentNode) {
return; //removed from DOM
}
var overlayContainer = this.clone.wtTable.holder.parentNode;
if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) {
overlayContainer.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px';
} else {
var box = this.instance.wtTable.hider.getBoundingClientRect();
overlayContainer.style.left = Math.ceil(box.left, 10) + 'px';
overlayContainer.style.width = Handsontable.Dom.outerWidth(this.clone.wtTable.TABLE) + 'px';
}
};
WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () {
return Handsontable.Dom.getScrollTop(this.scrollHandler);
};
WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) {
if (this.scrollHandler === window){
window.scrollTo(Handsontable.Dom.getWindowScrollLeft(), pos);
} else {
this.scrollHandler.scrollTop = pos;
}
};
WalkontableVerticalScrollbarNative.prototype.onScroll = function () {
WalkontableOverlay.prototype.onScroll.call(this);
this.instance.draw(true);//
this.instance.getSetting('onScrollVertically');
};
WalkontableVerticalScrollbarNative.prototype.getLastCell = function () {
return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1;
};
WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) {
var sum = 0;
while (from < length) {
sum += this.instance.wtSettings.settings.rowHeight(from) || this.instance.wtSettings.settings.defaultRowHeight; //TODO optimize getSetting, because this is MUCH faster then getSetting
from++;
}
return sum;
};
//applyToDOM (in future merge it with this.refresh?)
WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () {
var headerSize = this.instance.wtViewport.getColumnHeaderHeight();
this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow
this.fixed.style.top = this.measureBefore + 'px';
this.fixed.style.bottom = '';
};
WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) {
var newY = this.tableParentOffset + cell * this.cellSize;
this.setScrollPosition(newY);
this.onScroll();
};
//readWindowSize (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () {
if (this.scrollHandler === window) {
this.windowSize = document.documentElement.clientHeight;
this.tableParentOffset = this.instance.wtTable.holderOffset.top;
}
else {
var elemHeight = Handsontable.Dom.outerHeight(this.scrollHandler);
this.windowSize = elemHeight > 0 && this.scrollHandler.clientHeight > 0 ? this.scrollHandler.clientHeight : Infinity; //returns height without DIV scrollbar
this.tableParentOffset = 0;
}
this.windowScrollPosition = this.getScrollPosition();
};
//readSettings (in future merge it with this.prepare?)
WalkontableVerticalScrollbarNative.prototype.readSettings = function () {
this.readWindowSize();
this.offset = this.instance.getSetting('offsetRow');
this.total = this.instance.getSetting('totalRows');
var scrollDelta = this.windowScrollPosition - this.tableParentOffset;
var sum = 0;
var last;
for (var i = 0; i < this.total; i++) {
last = this.instance.getSetting('rowHeight', i) || this.instance.wtSettings.settings.defaultRowHeight;
sum += last;
if (sum - 1 > scrollDelta) {
break;
}
}
this.offset = Math.min(i, this.total);
this.instance.update('offsetRow', this.offset);
};
function WalkontableScrollbars(instance) {
this.instance = instance;
instance.update('scrollbarWidth', Handsontable.Dom.getScrollbarWidth());
instance.update('scrollbarHeight', Handsontable.Dom.getScrollbarWidth());
this.vertical = new WalkontableVerticalScrollbarNative(instance);
this.horizontal = new WalkontableHorizontalScrollbarNative(instance);
this.corner = new WalkontableCornerScrollbarNative(instance);
if (instance.getSetting('debug')) {
this.debug = new WalkontableDebugOverlay(instance);
}
this.registerListeners();
}
WalkontableScrollbars.prototype.registerListeners = function () {
var that = this;
var oldVerticalScrollPosition
, oldHorizontalScrollPosition
, oldBoxTop
, oldBoxLeft
, oldBoxWidth
, oldBoxHeight;
function refreshAll() {
if(!that.instance.drawn) {
return;
}
if (!that.instance.wtTable.holder.parentNode) {
//Walkontable was detached from DOM, but this handler was not removed
that.destroy();
return;
}
that.vertical.windowScrollPosition = that.vertical.getScrollPosition();
that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition();
that.box = that.instance.wtTable.hider.getBoundingClientRect();
/*if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) {
//that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table
oldBoxWidth = that.box.width;
oldBoxHeight = that.box.height;
that.instance.draw(true);
}*/
if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) {
that.vertical.onScroll();
that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles
that.corner.onScroll();
that.vertical.react();
that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles
oldVerticalScrollPosition = that.vertical.windowScrollPosition;
oldHorizontalScrollPosition = that.horizontal.windowScrollPosition;
oldBoxTop = that.box.top;
oldBoxLeft = that.box.left;
}
}
var $window = $(window);
this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) {
this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll);
}
if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) {
$window.on('scroll.' + this.instance.guid, refreshAll);
}
};
WalkontableScrollbars.prototype.destroy = function () {
this.vertical && this.vertical.destroy();
this.horizontal && this.horizontal.destroy();
this.corner && this.corner.destroy();
};
WalkontableScrollbars.prototype.refresh = function (selectionsOnly) {
this.horizontal && this.horizontal.readSettings();
this.vertical && this.vertical.readSettings();
this.horizontal && this.horizontal.prepare();
this.vertical && this.vertical.prepare();
this.horizontal && this.horizontal.refresh(selectionsOnly);
this.vertical && this.vertical.refresh(selectionsOnly);
this.corner && this.corner.refresh(selectionsOnly);
this.debug && this.debug.refresh(selectionsOnly);
};
function WalkontableSelection(instance, settings) {
this.instance = instance;
this.settings = settings;
this.cellRange = null;
if (settings.border) {
this.border = new WalkontableBorder(instance, settings);
}
}
/**
* Returns boolean information if selection is empty
* @returns {boolean}
*/
WalkontableSelection.prototype.isEmpty = function () {
return (this.cellRange === null);
};
/**
* Adds a cell coords to the selection
* @param {WalkontableCellCoords} coords
*/
WalkontableSelection.prototype.add = function (coords) {
if (this.isEmpty()) {
this.cellRange = new WalkontableCellRange(coords, coords, coords);
}
else {
this.cellRange.expand(coords);
}
};
/**
* If selection range from or to property equals oldCoords, replace it with newCoords. Return boolean information about success
* @param {WalkontableCellCoords} oldCoords
* @param {WalkontableCellCoords} newCoords
* @return {boolean}
*/
WalkontableSelection.prototype.replace = function (oldCoords, newCoords) {
if (!this.isEmpty()) {
if(this.cellRange.from.isEqual(oldCoords)) {
this.cellRange.from = newCoords;
return true;
}
if(this.cellRange.to.isEqual(oldCoords)) {
this.cellRange.to = newCoords;
return true;
}
}
return false;
};
WalkontableSelection.prototype.clear = function () {
this.cellRange = null;
};
/**
* Returns the top left (TL) and bottom right (BR) selection coordinates
* @returns {Object}
*/
WalkontableSelection.prototype.getCorners = function () {
var topLeft = this.cellRange.getTopLeftCorner();
var bottomRight = this.cellRange.getBottomRightCorner();
return [topLeft.row, topLeft.col, bottomRight.row, bottomRight.col];
};
WalkontableSelection.prototype.draw = function () {
var corners, r, c, source_r, source_c,
instance = this.instance,
visibleRows = instance.wtTable.getRowStrategy().countVisible(),
renderedColumns = instance.wtTable.getColumnStrategy().cellCount;
if (!this.isEmpty()) {
corners = this.getCorners();
for (r = 0; r < visibleRows; r++) {
for (c = 0; c < renderedColumns; c++) {
source_r = instance.wtTable.rowFilter.visibleToSource(r);
source_c = instance.wtTable.columnFilter.visibleToSource(c);
if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) {
//selected cell
if (this.settings.className) {
instance.wtTable.currentCellCache.add(r, c, this.settings.className);
}
}
else if (source_r >= corners[0] && source_r <= corners[2]) {
//selection is in this row
if (this.settings.highlightRowClassName) {
instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName);
}
}
else if (source_c >= corners[1] && source_c <= corners[3]) {
//selection is in this column
if (this.settings.highlightColumnClassName) {
instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName);
}
}
}
}
this.border && this.border.appear(corners); //warning! border.appear modifies corners!
}
else {
this.border && this.border.disappear();
}
};
/*
Make a clone of a selection by overriding the WOT instance and creating new WalkontableBorder for the new instance
Method is used for creating selections in overlays
*/
WalkontableSelection.prototype.makeClone = function (instance) {
function WalkontableSelectionClone(){}
WalkontableSelectionClone.prototype = this;
var clone = new WalkontableSelectionClone();
clone.instance = instance;
if (clone.border){
clone.border = new WalkontableBorder(instance, clone.settings);
}
return clone;
};
function WalkontableSelections(instance, config){
if (config) {
for (var i in config) {
if (config.hasOwnProperty(i)) {
this[i] = new WalkontableSelection(instance, config[i]);
}
}
}
}
WalkontableSelections.prototype.makeClone = function (instance) {
function WalkontableSelectionsClone(){}
var clone = new WalkontableSelectionsClone();
for (var selectionName in this){
if (this.hasOwnProperty(selectionName)){
clone[selectionName] = this[selectionName].makeClone(instance);
}
}
return clone;
};
function WalkontableSettings(instance, settings) {
var that = this;
this.instance = instance;
//default settings. void 0 means it is required, null means it can be empty
this.defaults = {
table: void 0,
debug: false, //shows WalkontableDebugOverlay
//presentation mode
scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar)
scrollV: 'auto', //values: see above
stretchH: 'none', //values: all, last, none
currentRowClassName: null,
currentColumnClassName: null,
//data source
data: void 0,
offsetRow: 0,
offsetColumn: 0,
fixedColumnsLeft: 0,
fixedRowsTop: 0,
rowHeaders: function () {
return []
}, //this must be array of functions: [function (row, TH) {}]
columnHeaders: function () {
return []
}, //this must be array of functions: [function (column, TH) {}]
totalRows: void 0,
totalColumns: void 0,
width: null,
height: null,
cellRenderer: function (row, column, TD) {
var cellData = that.getSetting('data', row, column);
Handsontable.Dom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData);
},
columnWidth: 50,
rowHeight: function (row) {
return 23;
},
defaultRowHeight: 23,
selections: null,
hideBorderOnMouseDownOver: false,
//callbacks
onCellMouseDown: null,
onCellMouseOver: null,
// onCellMouseOut: null,
onCellDblClick: null,
onCellCornerMouseDown: null,
onCellCornerDblClick: null,
beforeDraw: null,
onDraw: null,
onScrollVertically: null,
onScrollHorizontally: null,
//constants
scrollbarWidth: 10,
scrollbarHeight: 10,
renderAllRows: false
};
//reference to settings
this.settings = {};
for (var i in this.defaults) {
if (this.defaults.hasOwnProperty(i)) {
if (settings[i] !== void 0) {
this.settings[i] = settings[i];
}
else if (this.defaults[i] === void 0) {
throw new Error('A required setting "' + i + '" was not provided');
}
else {
this.settings[i] = this.defaults[i];
}
}
}
}
/**
* generic methods
*/
WalkontableSettings.prototype.update = function (settings, value) {
if (value === void 0) { //settings is object
for (var i in settings) {
if (settings.hasOwnProperty(i)) {
this.settings[i] = settings[i];
}
}
}
else { //if value is defined then settings is the key
this.settings[settings] = value;
}
return this.instance;
};
WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3, param4) {
if (typeof this.settings[key] === 'function') {
return this.settings[key](param1, param2, param3, param4); //this is faster than .apply - https://github.com/handsontable/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips
}
else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') { //perhaps this can be removed, it is only used in tests
return this.settings[key][param1];
}
else {
return this.settings[key];
}
};
WalkontableSettings.prototype.has = function (key) {
return !!this.settings[key]
};
function WalkontableTable(instance, table) {
//reference to instance
this.instance = instance;
this.TABLE = table;
Handsontable.Dom.removeTextNodes(this.TABLE);
//wtSpreader
var parent = this.TABLE.parentNode;
if (!parent || parent.nodeType !== 1 || !Handsontable.Dom.hasClass(parent, 'wtHolder')) {
var spreader = document.createElement('DIV');
spreader.className = 'wtSpreader';
if (parent) {
parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
spreader.appendChild(this.TABLE);
}
this.spreader = this.TABLE.parentNode;
//wtHider
parent = this.spreader.parentNode;
if (!parent || parent.nodeType !== 1 || !Handsontable.Dom.hasClass(parent, 'wtHolder')) {
var hider = document.createElement('DIV');
hider.className = 'wtHider';
if (parent) {
parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
hider.appendChild(this.spreader);
}
this.hider = this.spreader.parentNode;
this.hiderStyle = this.hider.style;
this.hiderStyle.position = 'relative';
//wtHolder
parent = this.hider.parentNode;
if (!parent || parent.nodeType !== 1 || !Handsontable.Dom.hasClass(parent, 'wtHolder')) {
var holder = document.createElement('DIV');
holder.style.position = 'relative';
holder.className = 'wtHolder';
if(!instance.cloneSource) {
holder.className += ' ht_master';
}
if (parent) {
parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it
}
holder.appendChild(this.hider);
}
this.holder = this.hider.parentNode;
//bootstrap from settings
this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0];
if (!this.TBODY) {
this.TBODY = document.createElement('TBODY');
this.TABLE.appendChild(this.TBODY);
}
this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0];
if (!this.THEAD) {
this.THEAD = document.createElement('THEAD');
this.TABLE.insertBefore(this.THEAD, this.TBODY);
}
this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0];
if (!this.COLGROUP) {
this.COLGROUP = document.createElement('COLGROUP');
this.TABLE.insertBefore(this.COLGROUP, this.THEAD);
}
if (this.instance.getSetting('columnHeaders').length) {
if (!this.THEAD.childNodes.length) {
var TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
}
this.colgroupChildrenLength = this.COLGROUP.childNodes.length;
this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0;
this.tbodyChildrenLength = this.TBODY.childNodes.length;
this.oldCellCache = new WalkontableClassNameCache();
this.currentCellCache = new WalkontableClassNameCache();
this.rowFilter = null;
this.columnFilter = null;
this.columnWidthCache = [];
}
WalkontableTable.prototype.getRowStrategy = function () {
return this.isWorkingOnClone() ? this.instance.cloneSource.wtTable.rowStrategy : this.rowStrategy;
};
WalkontableTable.prototype.getColumnStrategy = function () {
return this.isWorkingOnClone() ? this.instance.cloneSource.wtTable.columnStrategy : this.columnStrategy;
};
WalkontableTable.prototype.isWorkingOnClone = function () {
return !!this.instance.cloneSource;
};
WalkontableTable.prototype.refreshHiderDimensions = function () {
var spreaderStyle = this.spreader.style;
spreaderStyle.position = 'relative';
spreaderStyle.width = 'auto';
spreaderStyle.height = 'auto';
};
WalkontableTable.prototype.draw = function (selectionsOnly) {
if (!selectionsOnly) {
if (this.isWorkingOnClone()) {
this.tableOffset = this.instance.cloneSource.wtTable.tableOffset;
}
else {
this.holderOffset = Handsontable.Dom.offset(this.holder);
this.tableOffset = Handsontable.Dom.offset(this.TABLE);
this.instance.wtScrollbars.vertical.readSettings();
this.instance.wtScrollbars.horizontal.readSettings();
this.instance.wtViewport.resetSettings();
}
var offsetRow;
if (this.instance.cloneOverlay instanceof WalkontableDebugOverlay) {
offsetRow = 0;
}
else {
offsetRow = this.instance.wtSettings.settings.offsetRow;
}
this.rowFilter = new WalkontableRowFilter(
offsetRow,
this.instance.getSetting('totalRows'),
this.instance.getSetting('fixedRowsTop'),
this.instance.getSetting('columnHeaders').length
);
this.columnFilter = new WalkontableColumnFilter(
this.instance.wtSettings.settings.offsetColumn,
this.instance.getSetting('totalColumns'),
this.instance.getSetting('fixedColumnsLeft'),
this.instance.getSetting('rowHeaders').length
);
this._doDraw();
}
else {
this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true);
}
this.refreshPositions(selectionsOnly);
if (!selectionsOnly) {
if (!this.isWorkingOnClone()) {
this.instance.wtScrollbars.vertical.resetFixedPosition();
this.instance.wtScrollbars.horizontal.resetFixedPosition();
this.instance.wtScrollbars.corner.resetFixedPosition();
this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition();
}
}
this.instance.drawn = true;
return this;
};
WalkontableTable.prototype._doDraw = function () {
var wtRenderer = new WalkontableTableRenderer(this);
wtRenderer.render();
};
WalkontableTable.prototype.refreshPositions = function (selectionsOnly) {
this.refreshHiderDimensions();
this.refreshSelections(selectionsOnly);
};
WalkontableTable.prototype.refreshSelections = function (selectionsOnly) {
var vr
, r
, vc
, c
, s
, slen
, classNames = []
, visibleRows = this.getRowStrategy().countVisible()
, renderedCells = this.getColumnStrategy().cellCount;
this.oldCellCache = this.currentCellCache;
this.currentCellCache = new WalkontableClassNameCache();
if (this.instance.selections) {
for (r in this.instance.selections) {
if (this.instance.selections.hasOwnProperty(r)) {
this.instance.selections[r].draw();
if (this.instance.selections[r].settings.className) {
classNames.push(this.instance.selections[r].settings.className);
}
if (this.instance.selections[r].settings.highlightRowClassName) {
classNames.push(this.instance.selections[r].settings.highlightRowClassName);
}
if (this.instance.selections[r].settings.highlightColumnClassName) {
classNames.push(this.instance.selections[r].settings.highlightColumnClassName);
}
}
}
}
slen = classNames.length;
for (vr = 0; vr < visibleRows; vr++) {
for (vc = 0; vc < renderedCells; vc++) {
r = this.rowFilter.visibleToSource(vr);
c = this.columnFilter.visibleToSource(vc);
for (s = 0; s < slen; s++) {
var cell;
if (this.currentCellCache.test(vr, vc, classNames[s])) {
cell = this.getCell(new WalkontableCellCoords(r, c));
if (typeof cell == 'object' ) Handsontable.Dom.addClass(cell, classNames[s]);
}
else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) {
cell = this.getCell(new WalkontableCellCoords(r, c));
if (typeof cell == 'object' ) Handsontable.Dom.removeClass(cell, classNames[s]);
}
}
}
}
};
/**
* getCell
* @param {WalkontableCellCoords} coords
* @return {Object} HTMLElement on success or {Number} one of the exit codes on error:
* -1 row before viewport
* -2 row after viewport
*
*/
WalkontableTable.prototype.getCell = function (coords) {
if (this.isRowBeforeViewport(coords.row)) {
return -1; //row before viewport
}
else if (this.isRowAfterViewport(coords.row)) {
return -2; //row after viewport
}
var TR = this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords.row)];
if (TR) {
return TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords.col)];
}
};
/**
* Returns cell coords object for a given TD
* @param TD
* @returns {WalkontableCellCoords}
*/
WalkontableTable.prototype.getCoords = function (TD) {
var TR = TD.parentNode;
var row = Handsontable.Dom.index(TR);
if (TR.parentNode === this.THEAD) {
row = this.rowFilter.visibleColHeadedColumnToSourceColumn(row);
}
else {
row = this.rowFilter.visibleToSource(row);
}
return new WalkontableCellCoords(
row,
this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex)
);
};
//returns -1 if no row is visible
WalkontableTable.prototype.getFirstVisibleRow = function () {
return this.rowFilter.visibleToSource(0 + this.rowFilter.fixedCount);
};
//returns -1 if no column is visible
WalkontableTable.prototype.getFirstVisibleColumn = function () {
if (this.isWorkingOnClone()){
if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative){
return 0;
} else {
return this.instance.cloneSource.wtTable.getFirstVisibleColumn();
}
}
var leftOffset = this.instance.wtScrollbars.horizontal.getScrollPosition();
var columnCount = this.getColumnStrategy().cellCount;
var firstTR = this.TBODY.firstChild;
if (!firstTR){
return 0;
}
for (var colIndex = 0; colIndex < columnCount; colIndex++){
leftOffset -= firstTR.childNodes[colIndex].offsetWidth;
if (leftOffset < 0){
return colIndex;
}
}
return -1;
};
//returns -1 if no row is visible
WalkontableTable.prototype.getLastVisibleRow = function () {
var lastVisibleRow = this.rowFilter.visibleToSource(this.getRowStrategy().countVisible() - 1);
var instance = this.instance;
if (instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
var fixedRowsTop = this.instance.getSetting('fixedRowsTop');
return Math.min(fixedRowsTop - 1, lastVisibleRow);
} else {
return lastVisibleRow;
}
};
//returns -1 if no column is visible
WalkontableTable.prototype.getLastVisibleColumn = function () {
var instance = this.instance;
if (this.isWorkingOnClone()){
if (instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || instance.cloneOverlay instanceof WalkontableCornerScrollbarNative){
var lastVisibleColumn = this.getColumnStrategy().countVisible() - 1;
var fixedColumnsLeft = instance.getSetting('fixedColumnsLeft');
return Math.min(fixedColumnsLeft - 1, lastVisibleColumn);
} else {
return this.instance.cloneSource.wtTable.getLastVisibleColumn();
}
}
var leftOffset = this.instance.wtScrollbars.horizontal.getScrollPosition();
var leftPartOfTable = leftOffset + this.instance.wtViewport.getWorkspaceWidth(Infinity);
var columnCount = this.getColumnStrategy().cellCount;
var rowHeaderCount = this.instance.getSetting('rowHeaders').length || 0;
var firstTR = this.TBODY.firstChild;
if (!columnCount) {
return -1;
}
for (var colIndex = 0; colIndex < columnCount + rowHeaderCount; colIndex++){
leftPartOfTable -= firstTR.childNodes[colIndex].offsetWidth;
if (leftPartOfTable <= 0){
return colIndex - rowHeaderCount;
}
}
return colIndex - rowHeaderCount - 1;
};
WalkontableTable.prototype.isRowBeforeViewport = function (r) {
return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount);
};
WalkontableTable.prototype.isRowAfterViewport = function (r) {
return (r > this.getLastVisibleRow());
};
WalkontableTable.prototype.isColumnBeforeViewport = function (c) {
return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount);
};
WalkontableTable.prototype.isColumnAfterViewport = function (c) {
return (c > this.getLastVisibleColumn());
};
WalkontableTable.prototype.isRowInViewport = function (r) {
return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r));
};
WalkontableTable.prototype.isColumnInViewport = function (c) {
return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c));
};
WalkontableTable.prototype.isLastRowFullyVisible = function () {
return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.getRowStrategy().isLastIncomplete());
};
WalkontableTable.prototype.isLastColumnFullyVisible = function () {
return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.getColumnStrategy().isLastIncomplete());
};
WalkontableTable.prototype.getVisibleRowsCount = function () {
return this.getRowStrategy().countVisible();
};
WalkontableTable.prototype.allRowsInViewport = function () {
return this.getRowStrategy().cellCount == this.getVisibleRowsCount();
};
function WalkontableTableRenderer(wtTable){
this.wtTable = wtTable;
this.instance = wtTable.instance;
this.rowFilter = wtTable.rowFilter;
this.columnFilter = wtTable.columnFilter;
this.TABLE = wtTable.TABLE;
this.THEAD = wtTable.THEAD;
this.TBODY = wtTable.TBODY;
this.COLGROUP = wtTable.COLGROUP;
this.utils = WalkontableTableRenderer.utils;
}
WalkontableTableRenderer.prototype.render = function () {
if (!this.wtTable.isWorkingOnClone()) {
this.instance.getSetting('beforeDraw', true);
}
this.rowHeaders = this.instance.getSetting('rowHeaders');
this.rowHeaderCount = this.rowHeaders.length;
this.fixedRowsTop = this.instance.getSetting('fixedRowsTop');
this.columnHeaders = this.instance.getSetting('columnHeaders');
var visibleColIndex
, totalRows = this.instance.getSetting('totalRows')
, totalColumns = this.instance.getSetting('totalColumns')
, displayTds
, TR
, TD
, TH
, adjusted = false
, workspaceWidth
, res;
if (totalColumns > 0) {
var cloneLimit;
if (this.wtTable.isWorkingOnClone()) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined
if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) {
cloneLimit = this.fixedRowsTop;
}
else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) {
cloneLimit = this.wtTable.getRowStrategy().cellCount;
}
//else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows
}
this.adjustAvailableNodes();
adjusted = true;
this.renderColGroups();
this.renderColumnHeaders();
displayTds = this.getColumnCount();
//Render table rows
this.renderRows(totalRows, cloneLimit, displayTds);
if (!this.wtTable.isWorkingOnClone()) {
workspaceWidth = this.instance.wtViewport.getWorkspaceWidth();
this.wtTable.getColumnStrategy().stretch();
}
this.adjustColumnWidths(displayTds);
}
if (!adjusted) {
this.adjustAvailableNodes();
}
if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) {
this.removeRedundantRows();
}
if (!this.wtTable.isWorkingOnClone()) {
this.instance.wtScrollbars.refresh(false);
if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) {
//workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching
this.wtTable.getColumnStrategy().stretch();
for (visibleColIndex = 0; visibleColIndex < this.wtTable.getColumnStrategy().cellCount; visibleColIndex++) {
this.COLGROUP.childNodes[visibleColIndex + this.rowHeaderCount].style.width = this.wtTable.getColumnStrategy().getSize(visibleColIndex) + 'px';
}
}
this.instance.getSetting('onDraw', true);
}
};
WalkontableTableRenderer.prototype.removeRedundantRows = function () {
var renderedRowIndex = this.wtTable.getRowStrategy().countRendered();
while (this.wtTable.tbodyChildrenLength > renderedRowIndex) {
this.TBODY.removeChild(this.TBODY.lastChild);
this.wtTable.tbodyChildrenLength--;
}
};
WalkontableTableRenderer.prototype.renderRows = function (totalRows, cloneLimit, displayTds) {
var lastTD, TR, res;
var offsetRow = this.instance.getSetting('offsetRow');
var visibleRowIndex = 0;
var sourceRowIndex = this.rowFilter.visibleToSource(visibleRowIndex);
var isWorkingOnClone = this.wtTable.isWorkingOnClone();
while (sourceRowIndex < totalRows && sourceRowIndex >= 0) {
if (visibleRowIndex > 1000) {
throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.');
}
if (cloneLimit !== void 0 && visibleRowIndex === cloneLimit) {
break; //we have as much rows as needed for this clone
}
TR = this.getTrForRow(visibleRowIndex, TR);
//Render row headers
this.renderRowHeaders(sourceRowIndex, TR);
this.adjustColumns(TR, displayTds + this.rowHeaderCount);
lastTD = this.renderCells(sourceRowIndex, TR, displayTds);
offsetRow = this.instance.getSetting('offsetRow'); //refresh the value
//after last column is rendered, check if last cell is fully displayed
if (!isWorkingOnClone) {
res = this.wtTable.getRowStrategy().add(visibleRowIndex, lastTD);
if (res === false) {
break;
}
if (visibleRowIndex == 0) { //rendering the first row may caused bottom scrollbar to appear, so we need to refresh the window size
this.instance.wtScrollbars.vertical.readWindowSize();
}
}
if (TR.firstChild) {
var height = this.instance.getSetting('rowHeight', sourceRowIndex); //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height
if(height) {
TR.firstChild.style.height = height + 'px';
}
else {
TR.firstChild.style.height = '';
}
}
visibleRowIndex++;
sourceRowIndex = this.rowFilter.visibleToSource(visibleRowIndex);
}
};
WalkontableTableRenderer.prototype.renderCells = function (sourceRowIndex, TR, displayTds) {
var TD, sourceColIndex;
for (var visibleColIndex = 0; visibleColIndex < displayTds; visibleColIndex++) {
sourceColIndex = this.columnFilter.visibleToSource(visibleColIndex);
if (visibleColIndex === 0) {
TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(sourceColIndex)];
}
else {
TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
//If the number of headers has been reduced, we need to replace excess TH with TD
if (TD.nodeName == 'TH') {
TD = this.utils.replaceThWithTd(TD, TR);
}
TD.className = '';
TD.removeAttribute('style');
this.instance.getSetting('cellRenderer', sourceRowIndex, sourceColIndex, TD);
}
return TD;
};
WalkontableTableRenderer.prototype.adjustColumnWidths = function (displayTds) {
var cache = this.instance.wtTable.columnWidthCache;
var cacheChanged = false;
var width;
for (var visibleColIndex = 0; visibleColIndex < displayTds; visibleColIndex++) {
if(this.wtTable.isWorkingOnClone()) {
width = this.instance.cloneSource.wtTable.columnWidthCache[visibleColIndex];
}
else {
width = this.wtTable.getColumnStrategy().getSize(visibleColIndex);
}
if (width !== cache[visibleColIndex]) {
this.COLGROUP.childNodes[visibleColIndex + this.rowHeaderCount].style.width = width + 'px';
cache[visibleColIndex] = width;
cacheChanged = true;
}
}
};
WalkontableTableRenderer.prototype.appendToTbody = function (TR) {
this.TBODY.appendChild(TR);
this.wtTable.tbodyChildrenLength++;
};
WalkontableTableRenderer.prototype.getTrForRow = function (rowIndex, currentTr) {
var TR;
if (rowIndex >= this.wtTable.tbodyChildrenLength) {
TR = this.createRow();
this.appendToTbody(TR);
} else if (rowIndex === 0) {
TR = this.TBODY.firstChild;
} else {
TR = currentTr.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
return TR;
};
WalkontableTableRenderer.prototype.createRow = function() {
var TR = document.createElement('TR');
for (var visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
TR.appendChild(document.createElement('TH'));
}
return TR;
};
WalkontableTableRenderer.prototype.renderRowHeader = function(row, col, TH){
this.rowHeaders[col](row, TH);
};
WalkontableTableRenderer.prototype.renderRowHeaders = function(row, TR){
for (var TH = TR.firstChild, visibleColIndex = 0; visibleColIndex < this.rowHeaderCount; visibleColIndex++) {
//If the number of row headers increased we need to create TH or replace an existing TD node with TH
if (!TH){
TH = document.createElement('TH');
TR.appendChild(TH);
} else if (TH.nodeName == 'TD') {
TH = this.utils.replaceTdWithTh(TH, TR);
}
this.renderRowHeader(row, visibleColIndex, TH);
TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes
}
};
WalkontableTableRenderer.prototype.adjustAvailableNodes = function () {
this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug
//adjust COLGROUP
this.adjustColGroups();
//adjust THEAD
this.adjustThead();
};
WalkontableTableRenderer.prototype.renderColumnHeaders = function () {
if (!this.columnHeaders.length) {
return;
}
var columnCount = this.getColumnCount();
var TR = this.getTrForColumnHeaders();
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) {
if (this.columnHeaders.length) {
this.renderColumnHeader( this.columnFilter.visibleToSource(columnIndex), TR.childNodes[this.rowHeaderCount + columnIndex]);
}
}
};
WalkontableTableRenderer.prototype.adjustColGroups = function () {
var columnCount = this.getColumnCount();
//adjust COLGROUP
while (this.wtTable.colgroupChildrenLength < columnCount + this.rowHeaderCount) {
this.COLGROUP.appendChild(document.createElement('COL'));
this.wtTable.colgroupChildrenLength++;
}
while (this.wtTable.colgroupChildrenLength > columnCount + this.rowHeaderCount) {
this.COLGROUP.removeChild(this.COLGROUP.lastChild);
this.wtTable.colgroupChildrenLength--;
}
};
WalkontableTableRenderer.prototype.adjustThead = function () {
var columnCount = this.getColumnCount();
var TR = this.THEAD.firstChild;
if (this.columnHeaders.length) {
if (!TR) {
TR = document.createElement('TR');
this.THEAD.appendChild(TR);
}
this.theadChildrenLength = TR.childNodes.length;
while (this.theadChildrenLength < columnCount + this.rowHeaderCount) {
TR.appendChild(document.createElement('TH'));
this.theadChildrenLength++;
}
while (this.theadChildrenLength > columnCount + this.rowHeaderCount) {
TR.removeChild(TR.lastChild);
this.theadChildrenLength--;
}
}
else if (TR) {
Handsontable.Dom.empty(TR);
}
};
WalkontableTableRenderer.prototype.getTrForColumnHeaders = function () {
var TR = this.THEAD.firstChild;
if (this.rowHeaderCount) {
this.renderRowHeaders(-1, TR);
}
return TR;
};
WalkontableTableRenderer.prototype.renderColumnHeader = function (col, TR) {
return this.columnHeaders[0](col, TR);
};
WalkontableTableRenderer.prototype.getColumnCount = function () {
if (this.wtTable.isWorkingOnClone() && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) {
return this.instance.getSetting('fixedColumnsLeft');
}
else {
return this.wtTable.getColumnStrategy().cellCount;
}
};
WalkontableTableRenderer.prototype.renderColGroups = function () {
for (var colIndex = 0; colIndex < this.wtTable.colgroupChildrenLength; colIndex++) {
if (colIndex < this.rowHeaderCount) {
Handsontable.Dom.addClass(this.COLGROUP.childNodes[colIndex], 'rowHeader');
}
else {
Handsontable.Dom.removeClass(this.COLGROUP.childNodes[colIndex], 'rowHeader');
}
}
};
WalkontableTableRenderer.prototype.adjustColumns = function (TR, desiredCount) {
var count = TR.childNodes.length;
while (count < desiredCount) {
var TD = document.createElement('TD');
TR.appendChild(TD);
count++;
}
while (count > desiredCount) {
TR.removeChild(TR.lastChild);
count--;
}
};
WalkontableTableRenderer.prototype.refreshStretching = function () {
if (this.wtTable.isWorkingOnClone()) {
return;
}
var instance = this.instance
, stretchH = instance.getSetting('stretchH')
, totalRows = instance.getSetting('totalRows')
, totalColumns = instance.getSetting('totalColumns')
, offsetColumn = instance.getSetting('offsetColumn');
var containerWidthFn = function (cacheWidth) {
var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth);
return viewportWidth;
};
var that = this;
var columnWidthFn = function (i) {
var source_c = that.columnFilter.visibleToSource(i);
if (source_c < totalColumns) {
return instance.getSetting('columnWidth', source_c);
}
};
var containerHeightFn = function (cacheHeight) {
if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay || instance.wtSettings.settings.renderAllRows) {
return Infinity;
}
else {
return that.instance.wtViewport.getViewportHeight(cacheHeight);
}
};
var rowHeightFn = function (i, TD) {
return instance.wtSettings.settings.defaultRowHeight;
};
this.wtTable.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH);
this.wtTable.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn);
};
/*
Helper functions, which does not have any side effects
*/
WalkontableTableRenderer.utils = {};
WalkontableTableRenderer.utils.replaceTdWithTh = function(TD, TR) {
var TH;
TH = document.createElement('TH');
TR.insertBefore(TH, TD);
TR.removeChild(TD);
return TH;
};
WalkontableTableRenderer.utils.replaceThWithTd = function(TH, TR) {
var TD = document.createElement('TD');
TR.insertBefore(TD, TH);
TR.removeChild(TH);
return TD;
};
function WalkontableViewport(instance) {
this.instance = instance;
this.resetSettings();
var that = this;
$(window).on('resize.walkontable.' + this.instance.guid, function () {
that.clientHeight = that.getWorkspaceHeight();
});
}
//used by scrollbar
WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) {
return this.instance.wtScrollbars.vertical.windowSize;
};
WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) {
if (this.instance.wtScrollbars.horizontal.scrollHandler === window){
return Math.min(document.documentElement.offsetWidth - this.getWorkspaceOffset().left, document.documentElement.offsetWidth);
}
return this.instance.wtScrollbars.horizontal.windowSize;
};
WalkontableViewport.prototype.getWorkspaceOffset = function () {
return Handsontable.Dom.offset(this.instance.wtTable.TABLE);
};
WalkontableViewport.prototype.getWorkspaceActualHeight = function () {
return Handsontable.Dom.outerHeight(this.instance.wtTable.TABLE);
};
WalkontableViewport.prototype.getWorkspaceActualWidth = function () {
return Handsontable.Dom.outerWidth(this.instance.wtTable.TABLE) || Handsontable.Dom.outerWidth(this.instance.wtTable.TBODY) || Handsontable.Dom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth;
};
WalkontableViewport.prototype.getColumnHeaderHeight = function () {
if (isNaN(this.columnHeaderHeight)) {
var cellOffset = Handsontable.Dom.offset(this.instance.wtTable.TBODY)
, tableOffset = this.instance.wtTable.tableOffset;
this.columnHeaderHeight = cellOffset.top - tableOffset.top;
}
return this.columnHeaderHeight;
};
WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) {
var containerHeight = this.getWorkspaceHeight(proposedHeight);
if (containerHeight === Infinity) {
return containerHeight;
}
var columnHeaderHeight = this.getColumnHeaderHeight();
if (columnHeaderHeight > 0) {
containerHeight -= columnHeaderHeight;
}
return containerHeight;
};
WalkontableViewport.prototype.getRowHeaderWidth = function () {
if (this.instance.cloneSource) {
return this.instance.cloneSource.wtViewport.getRowHeaderWidth();
}
if (isNaN(this.rowHeaderWidth)) {
var rowHeaders = this.instance.getSetting('rowHeaders');
if (rowHeaders.length) {
var TH = this.instance.wtTable.TABLE.querySelector('TH');
this.rowHeaderWidth = 0;
for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) {
if (TH) {
this.rowHeaderWidth += Handsontable.Dom.outerWidth(TH);
TH = TH.nextSibling;
}
else {
this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix
}
}
}
else {
this.rowHeaderWidth = 0;
}
}
return this.rowHeaderWidth;
};
WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) {
var containerWidth = this.getWorkspaceWidth(proposedWidth);
if (containerWidth === Infinity) {
return containerWidth;
}
var rowHeaderWidth = this.getRowHeaderWidth();
if (rowHeaderWidth > 0) {
return containerWidth - rowHeaderWidth;
}
else {
return containerWidth;
}
};
WalkontableViewport.prototype.resetSettings = function () {
this.rowHeaderWidth = NaN;
this.columnHeaderHeight = NaN;
};
})(jQuery, window, Handsontable);
/*!
* numeral.js
* version : 1.5.3
* author : Adam Draper
* license : MIT
* http://adamwdraper.github.com/Numeral-js/
*/
(function () {
/************************************
Constants
************************************/
var numeral,
VERSION = '1.5.3',
// internal storage for language config files
languages = {},
currentLanguage = 'en',
zeroFormat = null,
defaultFormat = '0,0',
// check for nodeJS
hasModule = (typeof module !== 'undefined' && module.exports);
/************************************
Constructors
************************************/
// Numeral prototype object
function Numeral (number) {
this._value = number;
}
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*/
function toFixed (value, precision, roundingFunction, optionals) {
var power = Math.pow(10, precision),
optionalsRegExp,
output;
//roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value * power) / power).toFixed(precision);
if (optionals) {
optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
/************************************
Formatting
************************************/
// determine what type of formatting we need to do
function formatNumeral (n, format, roundingFunction) {
var output;
// figure out what kind of format we are dealing with
if (format.indexOf('$') > -1) { // currency!!!!!
output = formatCurrency(n, format, roundingFunction);
} else if (format.indexOf('%') > -1) { // percentage
output = formatPercentage(n, format, roundingFunction);
} else if (format.indexOf(':') > -1) { // time
output = formatTime(n, format);
} else { // plain ol' numbers or bytes
output = formatNumber(n._value, format, roundingFunction);
}
// return string
return output;
}
// revert to number
function unformatNumeral (n, string) {
var stringOriginal = string,
thousandRegExp,
millionRegExp,
billionRegExp,
trillionRegExp,
suffixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytesMultiplier = false,
power;
if (string.indexOf(':') > -1) {
n._value = unformatTime(string);
} else {
if (string === zeroFormat) {
n._value = 0;
} else {
if (languages[currentLanguage].delimiters.decimal !== '.') {
string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
thousandRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
millionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
billionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
trillionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
for (power = 0; power <= suffixes.length; power++) {
bytesMultiplier = (string.indexOf(suffixes[power]) > -1) ? Math.pow(1024, power + 1) : false;
if (bytesMultiplier) {
break;
}
}
// do some math to create our number
n._value = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * (((string.split('-').length + Math.min(string.split('(').length-1, string.split(')').length-1)) % 2)? 1: -1) * Number(string.replace(/[^0-9\.]+/g, ''));
// round if we are talking about bytes
n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
}
}
return n._value;
}
function formatCurrency (n, format, roundingFunction) {
var symbolIndex = format.indexOf('$'),
openParenIndex = format.indexOf('('),
minusSignIndex = format.indexOf('-'),
space = '',
spliceIndex,
output;
// check for space before or after currency
if (format.indexOf(' $') > -1) {
space = ' ';
format = format.replace(' $', '');
} else if (format.indexOf('$ ') > -1) {
space = ' ';
format = format.replace('$ ', '');
} else {
format = format.replace('$', '');
}
// format the number
output = formatNumber(n._value, format, roundingFunction);
// position the symbol
if (symbolIndex <= 1) {
if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
output = output.split('');
spliceIndex = 1;
if (symbolIndex < openParenIndex || symbolIndex < minusSignIndex){
// the symbol appears before the "(" or "-"
spliceIndex = 0;
}
output.splice(spliceIndex, 0, languages[currentLanguage].currency.symbol + space);
output = output.join('');
} else {
output = languages[currentLanguage].currency.symbol + space + output;
}
} else {
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + languages[currentLanguage].currency.symbol);
output = output.join('');
} else {
output = output + space + languages[currentLanguage].currency.symbol;
}
}
return output;
}
function formatPercentage (n, format, roundingFunction) {
var space = '',
output,
value = n._value * 100;
// check for space before %
if (format.indexOf(' %') > -1) {
space = ' ';
format = format.replace(' %', '');
} else {
format = format.replace('%', '');
}
output = formatNumber(value, format, roundingFunction);
if (output.indexOf(')') > -1 ) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
}
function formatTime (n) {
var hours = Math.floor(n._value/60/60),
minutes = Math.floor((n._value - (hours * 60 * 60))/60),
seconds = Math.round(n._value - (hours * 60 * 60) - (minutes * 60));
return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds);
}
function unformatTime (string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + (Number(timeArray[0]) * 60 * 60);
// minutes
seconds = seconds + (Number(timeArray[1]) * 60);
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.length === 2) {
// minutes
seconds = seconds + (Number(timeArray[0]) * 60);
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
function formatNumber (value, format, roundingFunction) {
var negP = false,
signed = false,
optDec = false,
abbr = '',
abbrK = false, // force abbreviation to thousands
abbrM = false, // force abbreviation to millions
abbrB = false, // force abbreviation to billions
abbrT = false, // force abbreviation to trillions
abbrForce = false, // force abbreviation
bytes = '',
ord = '',
abs = Math.abs(value),
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
min,
max,
power,
w,
precision,
thousands,
d = '',
neg = false;
// check if number is zero and a custom zero format has been set
if (value === 0 && zeroFormat !== null) {
return zeroFormat;
} else {
// see if we should use parentheses for negative number or if we should prefix with a sign
// if both are present we default to parentheses
if (format.indexOf('(') > -1) {
negP = true;
format = format.slice(1, -1);
} else if (format.indexOf('+') > -1) {
signed = true;
format = format.replace(/\+/g, '');
}
// see if abbreviation is wanted
if (format.indexOf('a') > -1) {
// check if abbreviation is specified
abbrK = format.indexOf('aK') >= 0;
abbrM = format.indexOf('aM') >= 0;
abbrB = format.indexOf('aB') >= 0;
abbrT = format.indexOf('aT') >= 0;
abbrForce = abbrK || abbrM || abbrB || abbrT;
// check for space before abbreviation
if (format.indexOf(' a') > -1) {
abbr = ' ';
format = format.replace(' a', '');
} else {
format = format.replace('a', '');
}
if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
// trillion
abbr = abbr + languages[currentLanguage].abbreviations.trillion;
value = value / Math.pow(10, 12);
} else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
// billion
abbr = abbr + languages[currentLanguage].abbreviations.billion;
value = value / Math.pow(10, 9);
} else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
// million
abbr = abbr + languages[currentLanguage].abbreviations.million;
value = value / Math.pow(10, 6);
} else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
// thousand
abbr = abbr + languages[currentLanguage].abbreviations.thousand;
value = value / Math.pow(10, 3);
}
}
// see if we are formatting bytes
if (format.indexOf('b') > -1) {
// check for space before
if (format.indexOf(' b') > -1) {
bytes = ' ';
format = format.replace(' b', '');
} else {
format = format.replace('b', '');
}
for (power = 0; power <= suffixes.length; power++) {
min = Math.pow(1024, power);
max = Math.pow(1024, power+1);
if (value >= min && value < max) {
bytes = bytes + suffixes[power];
if (min > 0) {
value = value / min;
}
break;
}
}
}
// see if ordinal is wanted
if (format.indexOf('o') > -1) {
// check for space before
if (format.indexOf(' o') > -1) {
ord = ' ';
format = format.replace(' o', '');
} else {
format = format.replace('o', '');
}
ord = ord + languages[currentLanguage].ordinal(value);
}
if (format.indexOf('[.]') > -1) {
optDec = true;
format = format.replace('[.]', '.');
}
w = value.toString().split('.')[0];
precision = format.split('.')[1];
thousands = format.indexOf(',');
if (precision) {
if (precision.indexOf('[') > -1) {
precision = precision.replace(']', '');
precision = precision.split('[');
d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction, precision[1].length);
} else {
d = toFixed(value, precision.length, roundingFunction);
}
w = d.split('.')[0];
if (d.split('.')[1].length) {
d = languages[currentLanguage].delimiters.decimal + d.split('.')[1];
} else {
d = '';
}
if (optDec && Number(d.slice(1)) === 0) {
d = '';
}
} else {
w = toFixed(value, null, roundingFunction);
}
// format number
if (w.indexOf('-') > -1) {
w = w.slice(1);
neg = true;
}
if (thousands > -1) {
w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands);
}
if (format.indexOf('.') === 0) {
w = '';
}
return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + ((!neg && signed) ? '+' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : '');
}
}
/************************************
Top Level Functions
************************************/
numeral = function (input) {
if (numeral.isNumeral(input)) {
input = input.value();
} else if (input === 0 || typeof input === 'undefined') {
input = 0;
} else if (!Number(input)) {
input = numeral.fn.unformat(input);
}
return new Numeral(Number(input));
};
// version number
numeral.version = VERSION;
// compare numeral object
numeral.isNumeral = function (obj) {
return obj instanceof Numeral;
};
// This function will load languages and then set the global language. If
// no arguments are passed in, it will simply return the current global
// language key.
numeral.language = function (key, values) {
if (!key) {
return currentLanguage;
}
if (key && !values) {
if(!languages[key]) {
throw new Error('Unknown language : ' + key);
}
currentLanguage = key;
}
if (values || !languages[key]) {
loadLanguage(key, values);
}
return numeral;
};
// This function provides access to the loaded language data. If
// no arguments are passed in, it will simply return the current
// global language object.
numeral.languageData = function (key) {
if (!key) {
return languages[currentLanguage];
}
if (!languages[key]) {
throw new Error('Unknown language : ' + key);
}
return languages[key];
};
numeral.language('en', {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function (number) {
var b = number % 10;
return (~~ (number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
currency: {
symbol: '$'
}
});
numeral.zeroFormat = function (format) {
zeroFormat = typeof(format) === 'string' ? format : null;
};
numeral.defaultFormat = function (format) {
defaultFormat = typeof(format) === 'string' ? format : '0.0';
};
/************************************
Helpers
************************************/
function loadLanguage(key, values) {
languages[key] = values;
}
/************************************
Floating-point helpers
************************************/
// The floating-point helper functions and implementation
// borrows heavily from sinful.js: http://guipn.github.io/sinful.js/
/**
* Array.prototype.reduce for browsers that don't support it
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Compatibility
*/
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function (callback, opt_initialValue) {
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index,
value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
/**
* Computes the multiplier necessary to make x >= 1,
* effectively eliminating miscalculations caused by
* finite precision.
*/
function multiplier(x) {
var parts = x.toString().split('.');
if (parts.length < 2) {
return 1;
}
return Math.pow(10, parts[1].length);
}
/**
* Given a variable number of arguments, returns the maximum
* multiplier that must be used to normalize an operation involving
* all of them.
*/
function correctionFactor() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (prev, next) {
var mp = multiplier(prev),
mn = multiplier(next);
return mp > mn ? mp : mn;
}, -Infinity);
}
/************************************
Numeral Prototype
************************************/
numeral.fn = Numeral.prototype = {
clone : function () {
return numeral(this);
},
format : function (inputString, roundingFunction) {
return formatNumeral(this,
inputString ? inputString : defaultFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
unformat : function (inputString) {
if (Object.prototype.toString.call(inputString) === '[object Number]') {
return inputString;
}
return unformatNumeral(this, inputString ? inputString : defaultFormat);
},
value : function () {
return this._value;
},
valueOf : function () {
return this._value;
},
set : function (value) {
this._value = Number(value);
return this;
},
add : function (value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum + corrFactor * curr;
}
this._value = [this._value, value].reduce(cback, 0) / corrFactor;
return this;
},
subtract : function (value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum - corrFactor * curr;
}
this._value = [value].reduce(cback, this._value * corrFactor) / corrFactor;
return this;
},
multiply : function (value) {
function cback(accum, curr, currI, O) {
var corrFactor = correctionFactor(accum, curr);
return (accum * corrFactor) * (curr * corrFactor) /
(corrFactor * corrFactor);
}
this._value = [this._value, value].reduce(cback, 1);
return this;
},
divide : function (value) {
function cback(accum, curr, currI, O) {
var corrFactor = correctionFactor(accum, curr);
return (accum * corrFactor) / (curr * corrFactor);
}
this._value = [this._value, value].reduce(cback);
return this;
},
difference : function (value) {
return Math.abs(numeral(this._value).subtract(value).value());
}
};
/************************************
Exposing Numeral
************************************/
// CommonJS module is defined
if (hasModule) {
module.exports = numeral;
}
/*global ender:false */
if (typeof ender === 'undefined') {
// here, `this` means `window` in the browser, or `global` on the server
// add `numeral` as a global object via a string identifier,
// for Closure Compiler 'advanced' mode
this['numeral'] = numeral;
}
/*global define:false */
if (typeof define === 'function' && define.amd) {
define([], function () {
return numeral;
});
}
}).call(this);
|
server/middlewares/clientRoute.js | chikara-chan/react-isomorphic-boilerplate | import React from 'react'
import {renderToString} from 'react-dom/server'
import {match, RouterContext} from 'react-router'
import {Provider} from 'react-redux'
import routes from '../../client/routes'
import configureStore from '../../client/common/store/configureStore'
const store = configureStore()
async function clientRoute(ctx, next) {
let _renderProps
match({routes, location: ctx.url}, (error, redirectLocation, renderProps) => {
_renderProps = renderProps
})
if (_renderProps) {
await ctx.render('index', {
root: renderToString(
<Provider store={store}>
<RouterContext {..._renderProps}/>
</Provider>
),
state: store.getState()
})
} else {
await next()
}
}
export default clientRoute
|
src/client/components/container/App.js | megmatty/letsplay-fullstack | import React, { Component } from 'react';
import NavigationContainer from "./NavigationContainer";
import styles from '../../App.css';
class App extends Component {
render() {
return(
<div>
<NavigationContainer />
{this.props.children}
</div>
)
}
}
export default App; |
app/javascript/mastodon/features/notifications/components/notifications_permission_banner.js | tri-star/mastodon | import React from 'react';
import Icon from 'mastodon/components/icon';
import Button from 'mastodon/components/button';
import IconButton from 'mastodon/components/icon_button';
import { requestBrowserPermission } from 'mastodon/actions/notifications';
import { changeSetting } from 'mastodon/actions/settings';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
});
export default @connect()
@injectIntl
class NotificationsPermissionBanner extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.dispatch(requestBrowserPermission());
}
handleClose = () => {
this.props.dispatch(changeSetting(['notifications', 'dismissPermissionBanner'], true));
}
render () {
const { intl } = this.props;
return (
<div className='notifications-permission-banner'>
<div className='notifications-permission-banner__close'>
<IconButton icon='times' onClick={this.handleClose} title={intl.formatMessage(messages.close)} />
</div>
<h2><FormattedMessage id='notifications_permission_banner.title' defaultMessage='Never miss a thing' /></h2>
<p><FormattedMessage id='notifications_permission_banner.how_to_control' defaultMessage="To receive notifications when Mastodon isn't open, enable desktop notifications. You can control precisely which types of interactions generate desktop notifications through the {icon} button above once they're enabled." values={{ icon: <Icon id='sliders' /> }} /></p>
<Button onClick={this.handleClick}><FormattedMessage id='notifications_permission_banner.enable' defaultMessage='Enable desktop notifications' /></Button>
</div>
);
}
}
|
modules/RouteUtils.js | stshort/react-router | import React from 'react'
function isValidChild(object) {
return object == null || React.isValidElement(object)
}
export function isReactChildren(object) {
return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild))
}
function createRoute(defaultProps, props) {
return { ...defaultProps, ...props }
}
export function createRouteFromReactElement(element) {
const type = element.type
const route = createRoute(type.defaultProps, element.props)
if (route.children) {
const childRoutes = createRoutesFromReactChildren(route.children, route)
if (childRoutes.length)
route.childRoutes = childRoutes
delete route.children
}
return route
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
export function createRoutesFromReactChildren(children, parentRoute) {
const routes = []
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
const route = element.type.createRouteFromReactElement(element, parentRoute)
if (route)
routes.push(route)
} else {
routes.push(createRouteFromReactElement(element))
}
}
})
return routes
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
export function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes)
} else if (routes && !Array.isArray(routes)) {
routes = [ routes ]
}
return routes
}
|
src/containers/ChannelData/index.js | dramich/Chatson | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SparklineChart from '../../components/SparklineChart';
import { getTone, unsetTone } from '../../actions/index';
import { styles } from './styles.scss';
class ChannelData extends Component {
constructor(props) {
super(props);
this.state = {
currentMsgCount: 0,
prevMinMsgCount: 0,
prevSecMsgCount: 0,
avgMsgPerMin: 0,
avgMsgPerSec: 0,
charCount: 0,
avgLength: 0,
lastMsg: '',
time: new Date(),
msgPerMinArray: [],
msgLengthArray: [],
msgPerSecArray: [],
lastMinTotal: 0,
lastSecTotal: 0,
watsonString: '',
};
}
componentDidMount() {
this.minuteInt = setInterval(() => { this.msgRateEveryMinute(); }, 60000);
this.secondInt = setInterval(() => { this.msgRateEverySecond(); }, 1000);
this.watsonInt = setInterval(() => {
if (this.state.watsonString.length) {
const currentWatsonString = this.state.watsonString;
this.setState({ watsonString: '' });
this.props.getTone(currentWatsonString);
} else {
this.props.unsetTone();
}
}, 3000);
}
componentWillReceiveProps(props) {
this.calculateAverages(props);
}
componentWillUnmount() {
clearInterval(this.minuteInt);
clearInterval(this.secondInt);
clearInterval(this.watsonInt);
}
msgRateEveryMinute() {
const newCurrentCount = this.state.currentMsgCount;
const lastMinMsgCount = newCurrentCount - this.state.prevMinMsgCount;
const newMsgPerMinArray = this.state.msgPerMinArray.concat([lastMinMsgCount]);
if (newMsgPerMinArray.length > 60) {
newMsgPerMinArray.shift();
}
this.setState({
prevMinMsgCount: newCurrentCount,
msgPerMinArray: newMsgPerMinArray,
lastMinTotal: lastMinMsgCount,
});
}
msgRateEverySecond() {
const newCurrentCount = this.state.currentMsgCount;
const lastSecMsgCount = newCurrentCount - this.state.prevSecMsgCount;
const newMsgPerSecArray = this.state.msgPerSecArray.concat([lastSecMsgCount]);
if (newMsgPerSecArray.length > 60) {
newMsgPerSecArray.shift();
}
this.setState({
prevSecMsgCount: newCurrentCount,
msgPerSecArray: newMsgPerSecArray,
lastSecTotal: lastSecMsgCount,
});
}
calculateAverages(props) {
let newCount;
let newAvgLength;
let newCharCount;
let newWatsonString;
const elapsedMinutes = (Math.abs(new Date() - this.state.time)) / 60000;
const elapsedSeconds = (Math.abs(new Date() - this.state.time)) / 1000;
if (this.state.lastMsg !== props.message) {
newWatsonString = this.state.watsonString.concat(props.message);
newCount = this.state.currentMsgCount + 1;
newCharCount = this.state.charCount + props.message.length;
newAvgLength = newCharCount / newCount;
} else {
newWatsonString = this.state.watsonString;
newCount = this.state.currentMsgCount;
newCharCount = this.state.charCount;
newAvgLength = this.state.avgLength;
}
const newMsgPerMin = newCount / elapsedMinutes;
const newMsgPerSec = newCount / elapsedSeconds;
const newMsgLengthArray = this.state.msgLengthArray.concat([props.message.length]);
if (newMsgLengthArray.length > 200) {
newMsgLengthArray.shift();
}
this.setState({
currentMsgCount: newCount,
avgMsgPerMin: newMsgPerMin,
avgMsgPerSec: newMsgPerSec,
charCount: newCharCount,
avgLength: newAvgLength,
lastMsg: props.message,
msgLengthArray: newMsgLengthArray,
watsonString: newWatsonString,
});
}
render() {
return (
<section className={`${styles}`}>
<div className="row">
<div className="col-md-4 col-md-push-8">
<section className="msg-data">
<h5>Average message length: {Math.round(this.state.avgLength)}</h5>
<h5>Last message length: {this.state.lastMsg.length}</h5>
<div className="msg-chart"><SparklineChart data={this.state.msgLengthArray} color="blue" limit={200} /></div>
</section>
</div>
<div className="col-md-4">
<section className="msg-data">
<h5>Average Messages per Second: {(this.state.avgMsgPerSec).toFixed(2)}</h5>
<h5>Last second's total: {this.state.lastSecTotal}</h5>
<div className="msg-chart"><SparklineChart data={this.state.msgPerSecArray} color="green" limit={60} /></div>
</section>
</div>
<div className="col-md-4 col-md-pull-8">
<section className="msg-data">
<h5>Average Messages per Minute: {Math.round(this.state.avgMsgPerMin)}</h5>
<h5>Last minute's total: {this.state.lastMinTotal}</h5>
<div className="msg-chart"><SparklineChart data={this.state.msgPerMinArray} color="red" limit={60} /></div>
</section>
</div>
</div>
<div className="row">
<div className="col-xs-12">
<span>Total Messages since arrival: {this.state.currentMsgCount}</span>
</div>
</div>
</section>
);
}
}
ChannelData.propTypes = {
getTone: React.PropTypes.func,
unsetTone: React.PropTypes.func,
};
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getTone, unsetTone }, dispatch);
}
export default connect(null, mapDispatchToProps)(ChannelData);
|
ajax/libs/extjs/4.2.1/src/layout/container/Box.js | zhangbg/cdnjs | /*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314)
*/
/**
* Base Class for HBoxLayout and VBoxLayout Classes. Generally it should not need to be used directly.
*/
Ext.define('Ext.layout.container.Box', {
/* Begin Definitions */
alias: ['layout.box'],
extend: 'Ext.layout.container.Container',
alternateClassName: 'Ext.layout.BoxLayout',
requires: [
'Ext.layout.container.boxOverflow.None',
'Ext.layout.container.boxOverflow.Menu',
'Ext.layout.container.boxOverflow.Scroller',
'Ext.util.Format',
'Ext.dd.DragDropManager'
],
/* End Definitions */
/**
* @cfg {Object} defaultMargins
* If the individual contained items do not have a margins property specified or margin specified via CSS, the
* default margins from this property will be applied to each item.
*
* This property may be specified as an object containing margins to apply in the format:
*
* {
* top: (top margin),
* right: (right margin),
* bottom: (bottom margin),
* left: (left margin)
* }
*
* This property may also be specified as a string containing space-separated, numeric margin values. The order of
* the sides associated with each value matches the way CSS processes margin values:
*
* - If there is only one value, it applies to all sides.
* - If there are two values, the top and bottom borders are set to the first value and the right and left are
* set to the second.
* - If there are three values, the top is set to the first value, the left and right are set to the second,
* and the bottom is set to the third.
* - If there are four values, they apply to the top, right, bottom, and left, respectively.
*/
defaultMargins: {
top: 0,
right: 0,
bottom: 0,
left: 0
},
/**
* @cfg {String} padding
* Sets the padding to be applied to all child items managed by this layout.
*
* This property must be specified as a string containing space-separated, numeric padding values. The order of the
* sides associated with each value matches the way CSS processes padding values:
*
* - If there is only one value, it applies to all sides.
* - If there are two values, the top and bottom borders are set to the first value and the right and left are
* set to the second.
* - If there are three values, the top is set to the first value, the left and right are set to the second,
* and the bottom is set to the third.
* - If there are four values, they apply to the top, right, bottom, and left, respectively.
*/
padding: 0,
/**
* @cfg {String} pack
* Controls how the child items of the container are packed together. Acceptable configuration values for this
* property are:
*
* - **start** - child items are packed together at **left** (HBox) or **top** (VBox) side of container (*default**)
* - **center** - child items are packed together at **mid-width** (HBox) or **mid-height** (VBox) of container
* - **end** - child items are packed together at **right** (HBox) or **bottom** (VBox) side of container
*/
pack: 'start',
/**
* @cfg {Number} flex
* This configuration option is to be applied to **child items** of the container managed by this layout. Each child
* item with a flex property will be flexed (horizontally in `hbox`, vertically in `vbox`) according to each item's
* **relative** flex value compared to the sum of all items with a flex value specified. Any child items that have
* either a `flex = 0` or `flex = undefined` will not be 'flexed' (the initial size will not be changed).
*/
flex: undefined,
/**
* @cfg {String/Ext.Component} stretchMaxPartner
* Allows stretchMax calculation to take into account the max perpendicular size (height for HBox layout and width
* for VBox layout) of another Box layout when calculating its maximum perpendicular child size.
*
* If specified as a string, this may be either a known Container ID, or a ComponentQuery selector which is rooted
* at this layout's Container (ie, to find a sibling, use `"^>#siblingItemId`).
*/
stretchMaxPartner: undefined,
alignRoundingMethod: 'round',
type: 'box',
scrollOffset: 0,
itemCls: Ext.baseCSSPrefix + 'box-item',
targetCls: Ext.baseCSSPrefix + 'box-layout-ct',
targetElCls: Ext.baseCSSPrefix + 'box-target',
innerCls: Ext.baseCSSPrefix + 'box-inner',
// availableSpaceOffset is used to adjust the availableWidth, typically used
// to reserve space for a scrollbar
availableSpaceOffset: 0,
// whether or not to reserve the availableSpaceOffset in layout calculations
reserveOffset: true,
manageMargins: true,
createsInnerCt: true,
childEls: [
'innerCt',
'targetEl'
],
renderTpl: [
'{%var oc,l=values.$comp.layout,oh=l.overflowHandler;',
'if (oh.getPrefixConfig!==Ext.emptyFn) {',
'if(oc=oh.getPrefixConfig())dh.generateMarkup(oc, out)',
'}%}',
'<div id="{ownerId}-innerCt" class="{[l.innerCls]} {[oh.getOverflowCls()]}" role="presentation">',
'<div id="{ownerId}-targetEl" class="{targetElCls}">',
'{%this.renderBody(out, values)%}',
'</div>',
'</div>',
'{%if (oh.getSuffixConfig!==Ext.emptyFn) {',
'if(oc=oh.getSuffixConfig())dh.generateMarkup(oc, out)',
'}%}',
{
disableFormats: true,
definitions: 'var dh=Ext.DomHelper;'
}
],
constructor: function(config) {
var me = this,
type;
me.callParent(arguments);
// The sort function needs access to properties in this, so must be bound.
me.flexSortFn = Ext.Function.bind(me.flexSort, me);
me.initOverflowHandler();
type = typeof me.padding;
if (type == 'string' || type == 'number') {
me.padding = Ext.util.Format.parseBox(me.padding);
me.padding.height = me.padding.top + me.padding.bottom;
me.padding.width = me.padding.left + me.padding.right;
}
},
// Matches: `<spaces>digits[.digits]<spaces>%<spaces>`
// Captures: `digits[.digits]`
_percentageRe: /^\s*(\d+(?:\.\d*)?)\s*[%]\s*$/,
getItemSizePolicy: function (item, ownerSizeModel) {
var me = this,
policy = me.sizePolicy,
align = me.align,
flex = item.flex,
key = align,
names = me.names,
width = item[names.width],
height = item[names.height],
percentageRe = me._percentageRe,
percentageWidth = percentageRe.test(width),
isStretch = (align == 'stretch'),
isStretchMax = (align == 'stretchmax'),
constrain = me.constrainAlign;
// Getting the size model is expensive, so we only want to do so if we really need it
if (!ownerSizeModel && (isStretch || flex || percentageWidth || (constrain && !isStretchMax))) {
ownerSizeModel = me.owner.getSizeModel();
}
if (isStretch) {
// If we are height.shrinkWrap, we behave as if we were stretchmax (for more
// details, see beginLayoutCycle)...
if (!percentageRe.test(height) && ownerSizeModel[names.height].shrinkWrap) {
key = 'stretchmax';
// We leave %age height as stretch since it will not participate in the
// stretchmax size calculation. This avoid running such a child in its
// shrinkWrap mode prior to supplying the calculated size.
}
} else if (!isStretchMax) {
if (percentageRe.test(height)) {
// Height %ages are calculated based on container size, so they are the
// same as align=stretch for this purpose...
key = 'stretch';
} else if (constrain && !ownerSizeModel[names.height].shrinkWrap) {
// Same functionality as stretchmax, only the max is going to be the size
// of the container, not the largest item
key = 'stretchmax';
} else {
key = '';
}
}
if (flex || percentageWidth) {
// If we are width.shrinkWrap, we won't be flexing since that requires a
// container width...
if (!ownerSizeModel[names.width].shrinkWrap) {
policy = policy.flex; // both flex and %age width are calculated
}
}
return policy[key];
},
flexSort: function (a, b) {
// We need to sort the flexed items to ensure that we have
// the items with max/min width first since when we set the
// values we may have the value constrained, so we need to
// react accordingly. Precedence is given from the largest
// value through to the smallest value
var maxWidthName = this.names.maxWidth,
minWidthName = this.names.minWidth,
infiniteValue = Infinity,
aTarget = a.target,
bTarget = b.target,
result = 0,
aMin, bMin, aMax, bMax,
hasMin, hasMax;
aMax = aTarget[maxWidthName] || infiniteValue;
bMax = bTarget[maxWidthName] || infiniteValue;
aMin = aTarget[minWidthName] || 0;
bMin = bTarget[minWidthName] || 0;
hasMin = isFinite(aMin) || isFinite(bMin);
hasMax = isFinite(aMax) || isFinite(bMax);
if (hasMin || hasMax) {
if (hasMax) {
result = aMax - bMax;
}
// If the result is 0, it means either
// a) hasMax was false
// b) The max values were the same
if (result === 0 && hasMin) {
result = bMin - aMin;
}
}
return result;
},
isItemBoxParent: function (itemContext) {
return true;
},
isItemShrinkWrap: function (item) {
return true;
},
roundFlex: function(width) {
return Math.ceil(width);
},
/**
* @private
* Called by an owning Panel before the Panel begins its collapse process.
* Most layouts will not need to override the default Ext.emptyFn implementation.
*/
beginCollapse: function(child) {
var me = this;
if (me.direction === 'vertical' && child.collapsedVertical()) {
child.collapseMemento.capture(['flex']);
delete child.flex;
} else if (me.direction === 'horizontal' && child.collapsedHorizontal()) {
child.collapseMemento.capture(['flex']);
delete child.flex;
}
},
/**
* @private
* Called by an owning Panel before the Panel begins its expand process.
* Most layouts will not need to override the default Ext.emptyFn implementation.
*/
beginExpand: function(child) {
// Restores the flex if we used to be flexed before
child.collapseMemento.restore(['flex']);
},
beginLayout: function (ownerContext) {
var me = this,
owner = me.owner,
smp = owner.stretchMaxPartner,
style = me.innerCt.dom.style,
names = me.names;
ownerContext.boxNames = names;
// this must happen before callParent to allow the overflow handler to do its work
// that can effect the childItems collection...
me.overflowHandler.beginLayout(ownerContext);
// get the contextItem for our stretchMax buddy:
if (typeof smp === 'string') {
smp = Ext.getCmp(smp) || owner.query(smp)[0];
}
ownerContext.stretchMaxPartner = smp && ownerContext.context.getCmp(smp);
me.callParent(arguments);
ownerContext.innerCtContext = ownerContext.getEl('innerCt', me);
// Capture whether the owning Container is scrolling in the parallel direction
me.scrollParallel = owner.scrollFlags[names.x];
// Capture whether the owning Container is scrolling in the perpendicular direction
me.scrollPerpendicular = owner.scrollFlags[names.y];
// If we *are* scrolling parallel, capture the scroll position of the encapsulating element
if (me.scrollParallel) {
me.scrollPos = owner.getTargetEl().dom[names.scrollLeft];
}
// Don't allow sizes burned on to the innerCt to influence measurements.
style.width = '';
style.height = '';
},
beginLayoutCycle: function (ownerContext, firstCycle) {
var me = this,
align = me.align,
names = ownerContext.boxNames,
pack = me.pack,
heightModelName = names.heightModel;
// this must happen before callParent to allow the overflow handler to do its work
// that can effect the childItems collection...
me.overflowHandler.beginLayoutCycle(ownerContext, firstCycle);
me.callParent(arguments);
// Cache several of our string concat/compare results (since width/heightModel can
// change if we are invalidated, we cannot do this in beginLayout)
ownerContext.parallelSizeModel = ownerContext[names.widthModel];
ownerContext.perpendicularSizeModel = ownerContext[heightModelName];
ownerContext.boxOptions = {
align: align = {
stretch: align == 'stretch',
stretchmax: align == 'stretchmax',
center: align == names.center,
bottom: align == names.afterY
},
pack: pack = {
center: pack == 'center',
end: pack == 'end'
}
};
// Consider an hbox w/stretch which means "assign all items the container's height".
// The spirit of this request is make all items the same height, but when shrinkWrap
// height is also requested, the height of the tallest item determines the height.
// This is exactly what the stretchmax option does, so we jiggle the flags here to
// act as if stretchmax were requested.
if (align.stretch && ownerContext.perpendicularSizeModel.shrinkWrap) {
align.stretchmax = true;
align.stretch = false;
}
// This is handy for knowing that we might need to apply height %ages
align.nostretch = !(align.stretch || align.stretchmax);
// In our example hbox, packing items to the right (end) or center can only work if
// there is a container width. So, if we are shrinkWrap, we just turn off the pack
// options for the run.
if (ownerContext.parallelSizeModel.shrinkWrap) {
pack.center = pack.end = false;
}
me.cacheFlexes(ownerContext);
// We set the width of the target el equal to the width of the innerCt
// when the layout cycle is finished, so we need to clear the width here
// to prevent the children from being crushed.
// IE needs it because of its scrollIntoView bug: https://sencha.jira.com/browse/EXTJSIV-6520
// Webkit needs it because of its mouse drag bug: https://sencha.jira.com/browse/EXTJSIV-5962
// FF needs it because of a vertical tab bug: https://sencha.jira.com/browse/EXTJSIV-8614
me.targetEl.setWidth(20000);
},
/**
* This method is called to (re)cache our understanding of flexes. This happens during beginLayout and may need to
* be called again if the flexes are changed during the layout (e.g., like ColumnLayout).
* @param {Object} ownerContext
* @protected
*/
cacheFlexes: function (ownerContext) {
var me = this,
names = ownerContext.boxNames,
widthModelName = names.widthModel,
heightModelName = names.heightModel,
nostretch = ownerContext.boxOptions.align.nostretch,
totalFlex = 0,
childItems = ownerContext.childItems,
i = childItems.length,
flexedItems = [],
minWidth = 0,
minWidthName = names.minWidth,
percentageRe = me._percentageRe,
percentageWidths = 0,
percentageHeights = 0,
child, childContext, flex, match;
while (i--) {
childContext = childItems[i];
child = childContext.target;
// check widthModel to see if we are the sizing layout. If so, copy the flex
// from the item to the contextItem and add it to totalFlex
//
if (childContext[widthModelName].calculated) {
childContext.flex = flex = child.flex;
if (flex) {
totalFlex += flex;
flexedItems.push(childContext);
minWidth += child[minWidthName] || 0;
} else { // a %age width...
match = percentageRe.exec(child[names.width]);
childContext.percentageParallel = parseFloat(match[1]) / 100;
++percentageWidths;
}
}
// the above means that "childContext.flex" is properly truthy/falsy, which is
// often times quite convenient...
if (nostretch && childContext[heightModelName].calculated) {
// the only reason we would be calculated height in this case is due to a
// height %age...
match = percentageRe.exec(child[names.height]);
childContext.percentagePerpendicular = parseFloat(match[1]) / 100;
++percentageHeights;
}
}
ownerContext.flexedItems = flexedItems;
ownerContext.flexedMinSize = minWidth;
ownerContext.totalFlex = totalFlex;
ownerContext.percentageWidths = percentageWidths;
ownerContext.percentageHeights = percentageHeights;
// The flexed boxes need to be sorted in ascending order of maxSize to work properly
// so that unallocated space caused by maxWidth being less than flexed width can be
// reallocated to subsequent flexed boxes.
Ext.Array.sort(flexedItems, me.flexSortFn);
},
calculate: function(ownerContext) {
var me = this,
targetSize = me.getContainerSize(ownerContext),
names = ownerContext.boxNames,
state = ownerContext.state,
plan = state.boxPlan || (state.boxPlan = {}),
targetContext = ownerContext.targetContext;
plan.targetSize = targetSize;
// If we are not widthModel.shrinkWrap, we need the width before we can lay out boxes:
if (!ownerContext.parallelSizeModel.shrinkWrap && !targetSize[names.gotWidth]) {
me.done = false;
return;
}
if (!state.parallelDone) {
state.parallelDone = me.calculateParallel(ownerContext, names, plan);
}
if (!state.perpendicularDone) {
state.perpendicularDone = me.calculatePerpendicular(ownerContext, names, plan);
}
if (state.parallelDone && state.perpendicularDone) {
// Fix for left and right docked Components in a dock component layout. This is for docked Headers and docked Toolbars.
// Older Microsoft browsers do not size a position:absolute element's width to match its content.
// So in this case, in the publishInnerCtSize method we may need to adjust the size of the owning Container's element explicitly based upon
// the discovered max width. So here we put a calculatedWidth property in the metadata to facilitate this.
if (me.owner.dock && (Ext.isIE7m || Ext.isIEQuirks) && !me.owner.width && !me.horizontal) {
plan.isIEVerticalDock = true;
plan.calculatedWidth = plan.maxSize + ownerContext.getPaddingInfo().width + ownerContext.getFrameInfo().width;
if (targetContext !== ownerContext) {
// targetContext can have additional padding, e.g. vertically
// oriented toolbar body element has a few px of left or right padding
// to make room for the tab strip.
plan.calculatedWidth += targetContext.getPaddingInfo().width;
}
}
me.publishInnerCtSize(ownerContext, me.reserveOffset ? me.availableSpaceOffset : 0);
// Calculate stretchmax only if there is >1 child item, or there is a stretchMaxPartner wanting the info
if (me.done && (ownerContext.childItems.length > 1 || ownerContext.stretchMaxPartner) && ownerContext.boxOptions.align.stretchmax && !state.stretchMaxDone) {
me.calculateStretchMax(ownerContext, names, plan);
state.stretchMaxDone = true;
}
me.overflowHandler.calculate(ownerContext);
} else {
me.done = false;
}
},
calculateParallel: function(ownerContext, names, plan) {
var me = this,
widthName = names.width,
childItems = ownerContext.childItems,
beforeXName = names.beforeX,
afterXName = names.afterX,
setWidthName = names.setWidth,
childItemsLength = childItems.length,
flexedItems = ownerContext.flexedItems,
flexedItemsLength = flexedItems.length,
pack = ownerContext.boxOptions.pack,
padding = me.padding,
containerWidth = plan.targetSize[widthName],
totalMargin = 0,
left = padding[beforeXName],
nonFlexWidth = left + padding[afterXName] + me.scrollOffset +
(me.reserveOffset ? me.availableSpaceOffset : 0),
scrollbarWidth = Ext.getScrollbarSize()[names.width],
i, childMargins, remainingWidth, remainingFlex, childContext, flex, flexedWidth,
contentWidth, mayNeedScrollbarAdjust, childWidth, percentageSpace;
// We may need to add scrollbar size to parallel size if
// Scrollbars take up space
// and we are scrolling in the perpendicular direction
// and shrinkWrapping in the parallel direction,
// and NOT stretching perpendicular dimensions to fit
// and NOT shrinkWrapping in the perpendicular direction
if (scrollbarWidth &&
me.scrollPerpendicular &&
ownerContext.parallelSizeModel.shrinkWrap &&
!ownerContext.boxOptions.align.stretch &&
!ownerContext.perpendicularSizeModel.shrinkWrap) {
// If its possible that we may need to add scrollbar size to the parallel size
// then we need to wait until the perpendicular size has been determined,
// so that we know if there is a scrollbar.
if (!ownerContext.state.perpendicularDone) {
return false;
}
mayNeedScrollbarAdjust = true;
}
// Gather the total size taken up by non-flexed items:
for (i = 0; i < childItemsLength; ++i) {
childContext = childItems[i];
childMargins = childContext.marginInfo || childContext.getMarginInfo();
totalMargin += childMargins[widthName];
if (!childContext[names.widthModel].calculated) {
childWidth = childContext.getProp(widthName);
nonFlexWidth += childWidth; // min/maxWidth safe
if (isNaN(nonFlexWidth)) {
return false;
}
}
}
nonFlexWidth += totalMargin;
if (ownerContext.percentageWidths) {
percentageSpace = containerWidth - totalMargin;
if (isNaN(percentageSpace)) {
return false;
}
for (i = 0; i < childItemsLength; ++i) {
childContext = childItems[i];
if (childContext.percentageParallel) {
childWidth = Math.ceil(percentageSpace * childContext.percentageParallel);
childWidth = childContext.setWidth(childWidth);
nonFlexWidth += childWidth;
}
}
}
// if we get here, we have all the childWidths for non-flexed items...
if (ownerContext.parallelSizeModel.shrinkWrap) {
plan.availableSpace = 0;
plan.tooNarrow = false;
} else {
plan.availableSpace = containerWidth - nonFlexWidth;
// If we're going to need space for a parallel scrollbar, then we need to redo the perpendicular measurements
plan.tooNarrow = plan.availableSpace < ownerContext.flexedMinSize;
if (plan.tooNarrow && Ext.getScrollbarSize()[names.height] && me.scrollParallel && ownerContext.state.perpendicularDone) {
ownerContext.state.perpendicularDone = false;
for (i = 0; i < childItemsLength; ++i) {
childItems[i].invalidate();
}
}
}
contentWidth = nonFlexWidth;
remainingWidth = plan.availableSpace;
remainingFlex = ownerContext.totalFlex;
// Calculate flexed item sizes:
for (i = 0; i < flexedItemsLength; i++) {
childContext = flexedItems[i];
flex = childContext.flex;
flexedWidth = me.roundFlex((flex / remainingFlex) * remainingWidth);
flexedWidth = childContext[setWidthName](flexedWidth); // constrained
// due to minWidth constraints, it may be that flexedWidth > remainingWidth
contentWidth += flexedWidth;
// Remaining space has already had margins subtracted, so just subtract size
remainingWidth = Math.max(0, remainingWidth - flexedWidth); // no negatives!
remainingFlex -= flex;
}
if (pack.center) {
left += remainingWidth / 2;
// If content is too wide to pack to center, do not allow the centering calculation to place it off the left edge.
if (left < 0) {
left = 0;
}
} else if (pack.end) {
left += remainingWidth;
}
// Assign parallel position for the boxes:
for (i = 0; i < childItemsLength; ++i) {
childContext = childItems[i];
childMargins = childContext.marginInfo; // already cached by first loop
left += childMargins[beforeXName];
childContext.setProp(names.x, left);
// We can read directly from "props.width" because we have already properly
// requested it in the calculation of nonFlexedWidths or we calculated it.
// We cannot call getProp because that would be inappropriate for flexed items
// and we don't need any extra function call overhead:
left += childMargins[afterXName] + childContext.props[widthName];
}
contentWidth += ownerContext.targetContext.getPaddingInfo()[widthName];
// Stash the contentWidth on the state so that it can always be accessed later in the calculation
ownerContext.state.contentWidth = contentWidth;
// if there is perpendicular overflow, the published parallel content size includes
// the size of the perpendicular scrollbar.
if (mayNeedScrollbarAdjust &&
(ownerContext.peek(names.contentHeight) > plan.targetSize[names.height])) {
contentWidth += scrollbarWidth;
ownerContext[names.hasOverflowY] = true;
// tell the component layout to set the parallel size in the dom
ownerContext.target.componentLayout[names.setWidthInDom] = true;
// IE8 in what passes for "strict" mode will not create a scrollbar if
// there is just the *exactly correct* spare space created for it. We
// have to force that to happen once all the styles have been flushed
// to the DOM (see completeLayout):
ownerContext[names.invalidateScrollY] = Ext.isStrict && Ext.isIE8;
}
ownerContext[names.setContentWidth](contentWidth);
return true;
},
calculatePerpendicular: function(ownerContext, names, plan) {
var me = this,
heightShrinkWrap = ownerContext.perpendicularSizeModel.shrinkWrap,
targetSize = plan.targetSize,
childItems = ownerContext.childItems,
childItemsLength = childItems.length,
mmax = Math.max,
heightName = names.height,
setHeightName = names.setHeight,
beforeYName = names.beforeY,
topPositionName = names.y,
padding = me.padding,
top = padding[beforeYName],
availHeight = targetSize[heightName] - top - padding[names.afterY],
align = ownerContext.boxOptions.align,
isStretch = align.stretch, // never true if heightShrinkWrap (see beginLayoutCycle)
isStretchMax = align.stretchmax,
isCenter = align.center,
isBottom = align.bottom,
constrain = me.constrainAlign,
maxHeight = 0,
hasPercentageSizes = 0,
onBeforeInvalidateChild = me.onBeforeConstrainInvalidateChild,
onAfterInvalidateChild = me.onAfterConstrainInvalidateChild,
scrollbarHeight = Ext.getScrollbarSize().height,
childTop, i, childHeight, childMargins, diff, height, childContext,
stretchMaxPartner, stretchMaxChildren, shrinkWrapParallelOverflow,
percentagePerpendicular;
if (isStretch || ((isCenter || isBottom) && !heightShrinkWrap)) {
if (isNaN(availHeight)) {
return false;
}
}
// If the intention is to horizontally scroll child components, but the container is too narrow,
// then:
// if we are shrinkwrapping height:
// Set a flag because we are going to expand the height taken by the perpendicular dimension to accommodate the scrollbar
// else
// We must allow for the parallel scrollbar to intrude into the height
if (me.scrollParallel && plan.tooNarrow) {
if (heightShrinkWrap) {
shrinkWrapParallelOverflow = true;
} else {
availHeight -= scrollbarHeight;
plan.targetSize[heightName] -= scrollbarHeight;
}
}
if (isStretch) {
height = availHeight; // never heightShrinkWrap...
} else {
for (i = 0; i < childItemsLength; i++) {
childContext = childItems[i];
childMargins = (childContext.marginInfo || childContext.getMarginInfo())[heightName];
if (!(percentagePerpendicular = childContext.percentagePerpendicular)) {
childHeight = childContext.getProp(heightName);
} else {
++hasPercentageSizes;
if (heightShrinkWrap) {
// height %age items cannot contribute to maxHeight... they are going
// to be a %age of that maxHeight!
continue;
} else {
childHeight = percentagePerpendicular * availHeight - childMargins;
childHeight = childContext[names.setHeight](childHeight);
}
}
// Summary:
// 1) Not shrink wrapping height, so the height is not determined by the children
// 2) Constrain is set
// 3) The child item is shrink wrapping
// 4) It execeeds the max
if (!heightShrinkWrap && constrain && childContext[names.heightModel].shrinkWrap && childHeight > availHeight) {
childContext.invalidate({
before: onBeforeInvalidateChild,
after: onAfterInvalidateChild,
layout: me,
childHeight: availHeight,
names: names
});
// By invalidating the height, it could mean the width can change, so we need
// to recalculate in the parallel direction.
ownerContext.state.parallelDone = false;
}
// Max perpendicular measurement (used for stretchmax) must take the min perpendicular size of each child into account in case any fall short.
if (isNaN(maxHeight = mmax(maxHeight, childHeight + childMargins,
childContext.target[names.minHeight] || 0))) {
return false; // heightShrinkWrap || isCenter || isStretchMax ??
}
}
// If there is going to be a parallel scrollbar maxHeight must include it to the outside world.
// ie: a stretchmaxPartner, and the setContentHeight
if (shrinkWrapParallelOverflow) {
maxHeight += scrollbarHeight;
ownerContext[names.hasOverflowX] = true;
// tell the component layout to set the perpendicular size in the dom
ownerContext.target.componentLayout[names.setHeightInDom] = true;
// IE8 in what passes for "strict" mode will not create a scrollbar if
// there is just the *exactly correct* spare space created for it. We
// have to force that to happen once all the styles have been flushed
// to the DOM (see completeLayout):
ownerContext[names.invalidateScrollX] = Ext.isStrict && Ext.isIE8;
}
// If we are associated with another box layout, grab its maxChildHeight
// This must happen before we calculate and publish our contentHeight
stretchMaxPartner = ownerContext.stretchMaxPartner;
if (stretchMaxPartner) {
// Publish maxChildHeight as soon as it has been calculated for our partner:
ownerContext.setProp('maxChildHeight', maxHeight);
stretchMaxChildren = stretchMaxPartner.childItems;
// Only wait for maxChildHeight if our partner has visible items:
if (stretchMaxChildren && stretchMaxChildren.length) {
maxHeight = mmax(maxHeight, stretchMaxPartner.getProp('maxChildHeight'));
if (isNaN(maxHeight)) {
return false;
}
}
}
ownerContext[names.setContentHeight](maxHeight + me.padding[heightName] +
ownerContext.targetContext.getPaddingInfo()[heightName]);
// We have to publish the contentHeight with the additional scrollbarHeight
// to encourage our container to accomodate it, but we must remove the height
// of the scrollbar as we go to sizing or centering the children.
if (shrinkWrapParallelOverflow) {
maxHeight -= scrollbarHeight;
}
plan.maxSize = maxHeight;
if (isStretchMax) {
height = maxHeight;
} else if (isCenter || isBottom || hasPercentageSizes) {
if (constrain) {
height = heightShrinkWrap ? maxHeight : availHeight;
} else {
height = heightShrinkWrap ? maxHeight : mmax(availHeight, maxHeight);
}
// When calculating a centered position within the content box of the innerCt,
// the width of the borders must be subtracted from the size to yield the
// space available to center within. The publishInnerCtSize method explicitly
// adds the border widths to the set size of the innerCt.
height -= ownerContext.innerCtContext.getBorderInfo()[heightName];
}
}
for (i = 0; i < childItemsLength; i++) {
childContext = childItems[i];
childMargins = childContext.marginInfo || childContext.getMarginInfo();
childTop = top + childMargins[beforeYName];
if (isStretch) {
childContext[setHeightName](height - childMargins[heightName]);
} else {
percentagePerpendicular = childContext.percentagePerpendicular;
if (heightShrinkWrap && percentagePerpendicular) {
childMargins = childContext.marginInfo || childContext.getMarginInfo();
childHeight = percentagePerpendicular * height - childMargins[heightName];
childHeight = childContext.setHeight(childHeight);
}
if (isCenter) {
diff = height - childContext.props[heightName];
if (diff > 0) {
childTop = top + Math[me.alignRoundingMethod](diff / 2);
}
} else if (isBottom) {
childTop = mmax(0, height - childTop - childContext.props[heightName]);
}
}
childContext.setProp(topPositionName, childTop);
}
return true;
},
onBeforeConstrainInvalidateChild: function(childContext, options){
// NOTE: No "this" pointer in here...
var heightModelName = options.names.heightModel;
if (!childContext[heightModelName].constrainedMin) {
// if the child hit a min constraint, it needs to be at its configured size, so
// we leave the sizeModel alone
childContext[heightModelName] = Ext.layout.SizeModel.calculated;
}
},
onAfterConstrainInvalidateChild: function(childContext, options){
// NOTE: No "this" pointer in here...
var names = options.names;
// We use 0 here because we know the size exceeds the available size.
// This was chosen on purpose, even for align: 'bottom', because it doesn't
// make practical sense to place the item at the bottom and then have it overflow
// over the top of the container, since it's not possible to scroll to it. As such,
// we always put the component at the top to follow normal document flow.
childContext.setProp(names.beforeY, 0);
if (childContext[names.heightModel].calculated) {
childContext[names.setHeight](options.childHeight);
}
},
calculateStretchMax: function (ownerContext, names, plan) {
var me = this,
heightName = names.height,
widthName = names.width,
childItems = ownerContext.childItems,
length = childItems.length,
height = plan.maxSize,
onBeforeStretchMaxInvalidateChild = me.onBeforeStretchMaxInvalidateChild,
onAfterStretchMaxInvalidateChild = me.onAfterStretchMaxInvalidateChild,
childContext, props, i, childHeight;
for (i = 0; i < length; ++i) {
childContext = childItems[i];
props = childContext.props;
childHeight = height - childContext.getMarginInfo()[heightName];
if (childHeight != props[heightName] || // if (wrong height ...
childContext[names.heightModel].constrained) { // ...or needs invalidation)
// When we invalidate a child, since we won't be around to size or position
// it, we include an after callback that will be run after the invalidate
// that will (re)do that work. The good news here is that we can read the
// results of all that from the childContext props.
//
// We also include a before callback to change the sizeModel to calculated
// prior to the layout being invoked.
childContext.invalidate({
before: onBeforeStretchMaxInvalidateChild,
after: onAfterStretchMaxInvalidateChild,
layout: me,
// passing this data avoids a 'scope' and its Function.bind
childWidth: props[widthName],
// subtract margins from the maximum value
childHeight: childHeight,
childX: props.x,
childY: props.y,
names: names
});
}
}
},
onBeforeStretchMaxInvalidateChild: function (childContext, options) {
// NOTE: No "this" pointer in here...
var heightModelName = options.names.heightModel;
// Change the childItem to calculated (i.e., "set by ownerCt"). The component layout
// of the child can course-correct (like dock layout does for a collapsed panel),
// so we must make these changes here before that layout's beginLayoutCycle is
// called.
if (!childContext[heightModelName].constrainedMax) {
// if the child hit a max constraint, it needs to be at its configured size, so
// we leave the sizeModel alone...
childContext[heightModelName] = Ext.layout.SizeModel.calculated;
}
},
onAfterStretchMaxInvalidateChild: function (childContext, options) {
// NOTE: No "this" pointer in here...
var names = options.names,
childHeight = options.childHeight,
childWidth = options.childWidth;
childContext.setProp('x', options.childX);
childContext.setProp('y', options.childY);
if (childContext[names.heightModel].calculated) {
// We need to respect a child that is still not calculated (such as a collapsed
// panel)...
childContext[names.setHeight](childHeight);
}
if (childContext[names.widthModel].calculated) {
childContext[names.setWidth](childWidth);
}
},
completeLayout: function(ownerContext) {
var me = this,
names = ownerContext.boxNames,
invalidateScrollX = ownerContext.invalidateScrollX,
invalidateScrollY = ownerContext.invalidateScrollY,
dom, el, overflowX, overflowY, styles;
me.overflowHandler.completeLayout(ownerContext);
if (invalidateScrollX || invalidateScrollY) {
el = me.getTarget();
dom = el.dom;
styles = dom.style;
if (invalidateScrollX) {
// get computed style to see if we are 'auto'
overflowX = el.getStyle('overflowX');
if (overflowX == 'auto') {
// capture the inline style (if any) so we can restore it later:
overflowX = styles.overflowX;
styles.overflowX = 'scroll'; // force the scrollbar to appear
} else {
invalidateScrollX = false; // no work really since not 'auto'
}
}
if (invalidateScrollY) {
// get computed style to see if we are 'auto'
overflowY = el.getStyle('overflowY');
if (overflowY == 'auto') {
// capture the inline style (if any) so we can restore it later:
overflowY = styles.overflowY;
styles.overflowY = 'scroll'; // force the scrollbar to appear
} else {
invalidateScrollY = false; // no work really since not 'auto'
}
}
if (invalidateScrollX || invalidateScrollY) { // if (some form of 'auto' in play)
// force a reflow...
dom.scrollWidth;
if (invalidateScrollX) {
styles.overflowX = overflowX; // restore inline style
}
if (invalidateScrollY) {
styles.overflowY = overflowY; // restore inline style
}
}
}
// If we are scrolling parallel, restore the saved scroll position
if (me.scrollParallel) {
me.owner.getTargetEl().dom[names.scrollLeft] = me.scrollPos;
}
},
finishedLayout: function(ownerContext) {
this.overflowHandler.finishedLayout(ownerContext);
this.callParent(arguments);
// Fix for an obscure webkit bug (EXTJSIV-5962) caused by the targetEl's 20000px
// width. We set a very large width on the targetEl at the beginning of the
// layout cycle to prevent any "crushing" effect on the child items, however
// in some cases the very large width makes it possible to scroll the innerCt
// by dragging on certain child elements. To prevent this from happening we ensure
// that the targetEl's width is the same as the innerCt.
// IE needs it because of its scrollIntoView bug: https://sencha.jira.com/browse/EXTJSIV-6520
// Webkit needs it because of its mouse drag bug: https://sencha.jira.com/browse/EXTJSIV-5962
// FF needs it because of a vertical tab bug: https://sencha.jira.com/browse/EXTJSIV-8614
this.targetEl.setWidth(ownerContext.innerCtContext.props.width);
},
publishInnerCtSize: function(ownerContext, reservedSpace) {
var me = this,
names = ownerContext.boxNames,
heightName = names.height,
widthName = names.width,
align = ownerContext.boxOptions.align,
dock = me.owner.dock,
padding = me.padding,
plan = ownerContext.state.boxPlan,
targetSize = plan.targetSize,
height = targetSize[heightName],
innerCtContext = ownerContext.innerCtContext,
innerCtWidth = (ownerContext.parallelSizeModel.shrinkWrap || (plan.tooNarrow && me.scrollParallel)
? ownerContext.state.contentWidth - ownerContext.targetContext.getPaddingInfo()[widthName]
: targetSize[widthName]) - (reservedSpace || 0),
innerCtHeight;
if (align.stretch) {
innerCtHeight = height;
} else {
innerCtHeight = plan.maxSize + padding[names.beforeY] + padding[names.afterY] + innerCtContext.getBorderInfo()[heightName];
if (!ownerContext.perpendicularSizeModel.shrinkWrap && (align.center || align.bottom)) {
innerCtHeight = Math.max(height, innerCtHeight);
}
}
innerCtContext[names.setWidth](innerCtWidth);
innerCtContext[names.setHeight](innerCtHeight);
// If unable to publish both dimensions, this layout needs to run again
if (isNaN(innerCtWidth + innerCtHeight)) {
me.done = false;
}
// If a calculated width has been found (this only happens for widthModel.shrinkWrap
// vertical docked Components in old Microsoft browsers) then, if the Component has
// not assumed the size of its content, set it to do so.
//
// We MUST pass the dirty flag to get that into the DOM, and because we are a Container
// layout, and not really supposed to perform sizing, we must also use the force flag.
if (plan.calculatedWidth && (dock == 'left' || dock == 'right')) {
// TODO: setting the owner size should be the job of the component layout.
ownerContext.setWidth(plan.calculatedWidth, true, true);
}
},
onRemove: function(comp){
var me = this;
me.callParent(arguments);
if (me.overflowHandler) {
me.overflowHandler.onRemove(comp);
}
if (comp.layoutMarginCap == me.id) {
delete comp.layoutMarginCap;
}
},
/**
* @private
*/
initOverflowHandler: function() {
var me = this,
handler = me.overflowHandler,
handlerType,
constructor;
if (typeof handler == 'string') {
handler = {
type: handler
};
}
handlerType = 'None';
if (handler && handler.type !== undefined) {
handlerType = handler.type;
}
constructor = Ext.layout.container.boxOverflow[handlerType];
if (constructor[me.type]) {
constructor = constructor[me.type];
}
me.overflowHandler = Ext.create('Ext.layout.container.boxOverflow.' + handlerType, me, handler);
},
// Overridden method from Ext.layout.container.Container.
// Used in the beforeLayout method to render all items into.
getRenderTarget: function() {
return this.targetEl;
},
// Overridden method from Ext.layout.container.Container.
// Used by Container classes to insert special DOM elements which must exist in addition to the child components
getElementTarget: function() {
return this.innerCt;
},
//<debug>
calculateChildBox: Ext.deprecated(),
calculateChildBoxes: Ext.deprecated(),
updateChildBoxes: Ext.deprecated(),
//</debug>
/**
* @private
*/
destroy: function() {
Ext.destroy(this.innerCt, this.overflowHandler);
this.callParent(arguments);
},
getRenderData: function() {
var data = this.callParent();
data.targetElCls = this.targetElCls;
return data;
}
});
|
tests/mocha/unit-tests/react/components/CoreFonts/core.font.counter.spec.js | blueliquiddesigns/gravity-forms-pdf-extended | import React from 'react'
import { shallow } from 'enzyme'
import CoreFontCounter from '../../../../../../src/assets/js/react/components/CoreFonts/CoreFontCounter'
describe('<CoreFontCounter />', () => {
it('Render the counter', () => {
const comp = shallow(<CoreFontCounter text='Prefix:' queue={1} />)
expect(comp.text()).to.equal('Prefix: 1')
})
})
|
src/routes/privacy/index.js | SgtRock91/FantasyOptimizer | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Page from '../../components/Page';
import privacy from './privacy.md';
function action() {
return {
chunks: ['privacy'],
title: privacy.title,
component: (
<Layout>
<Page {...privacy} />
</Layout>
),
};
}
export default action;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.